问:
How to achieve desired results in multidimensional array? C#
I am trying to achieve the output by using multidimensional array which I can get by using KeyValuePair.

Input:

```<code>var foodPair = new Dictionary<string, string>
{
    {"Pizza", "Italian"},
    {"Curry", "Indian"},
    {"Masala", "Indian"}
};

var teamPreference = new Dictionary<string, string>
{
    {"Jose", "Italian" },
    {"John", "Indian" },
    {"Sarah", "Thai" },
    {"Mary", "*" }
};

* means give everything
If selected food type is not available than give nothing. i.e Thai
</code>```

Output:

```<code>Jose, Pizza
John, Curry
John, Masala
Mary, Pizza
Mary, Curry
Mary, Masala
</code>```

Working Result by using KeyValuePair<string, string>:

https://dotnetfiddle.net/hNdlfy

I want to achieve same result by using string[,] but I don't know how to insert in dimensional array. Basically I am trying to learn how multidimensional arrays works by doing this kind of example.

答:
You cannot "insert" in any array (single-dimensional or multidimensional). But you can create array with enough space.

```<code>    var foodPair = new Dictionary<string, string> { { "Pizza", "Italian" }, { "Curry", "Indian" }, { "Masala", "Indian" } };
    var teamPreference = new Dictionary<string, string> { { "Jose", "Italian" }, { "John", "Indian" }, { "Sarah", "Thai" }, { "Mary", "*" } };
    var results = new List<KeyValuePair<string, string>>();

    var results2 = new string[10, 2];
    int rowIndex = 0;

    foreach (var teamMember in teamPreference)
    {
        switch (teamMember.Key)
        {
            case "Jose":
                var key = foodPair.FirstOrDefault(x => x.Value == "Italian").Key;
                results.Add(new KeyValuePair<string, string>(teamMember.Key, key));
                results2[rowIndex, 0] = teamMember.Key;
                results2[rowIndex, 1] = key;
                rowIndex++;
                break;

            case "John":
                var getAll = foodPair.Where(x => x.Value == "Indian").ToList();
                if (getAll.Any())
                {
                    results.AddRange(getAll.Select(a => new KeyValuePair<string, string>(teamMember.Key, a.Key)));
                }
                foreach (var item in getAll)
                {
                    results2[rowIndex, 0] = teamMember.Key;
                    results2[rowIndex, 1] = item.Key;
                    rowIndex++;
                }
                break;

            case "Sarah":
                var c = foodPair.FirstOrDefault(x => x.Value == "Thai").Key;
                if (!string.IsNullOrEmpty(c))
                {
                    results.Add(new KeyValuePair<string, string>(teamMember.Key, c));
                }
                if (!string.IsNullOrEmpty(c))
                {
                    results2[rowIndex, 0] = teamMember.Key;
                    results2[rowIndex, 1] = c;
                    rowIndex++;
                }

                break;

            case "Mary":
                if (teamMember.Value == "*")
                {
                    var everything = foodPair.Keys.ToList();
                    if (everything.Any())
                    {
                        results.AddRange(everything.Select(food => new KeyValuePair<string, string>(teamMember.Key, food)));
                    }
                    foreach (var item in everything)
                    {
                        results2[rowIndex, 0] = teamMember.Key;
                        results2[rowIndex, 1] = item;
                        rowIndex++;
                    }
                }

                break;
        }
    }

    if (results.Any())
    {
        foreach (var result in results)
        {
            Console.WriteLine("{0}, {1}", result.Key, result.Value);
        }
    }

    Console.WriteLine("Using multidimensional array");

    for (int row = 0; row < rowIndex; row++)
    {
        Console.WriteLine("{0}, {1}", results2[row, 0], results2[row, 1]);
    }
</code>```

But multidimensional array is not suitable data structure for this task. (You can see code with array looks terrible). Data structure that you need is called tuple and the definition for results can look like var results3 = new List<Tuple<string, string>>();

Additional note - you not need using .Any() with foreach statement. foreach is not executed for empty collections.

Good luck with learning C#!

Body:
I am trying to achieve the output by using multidimensional array which I can get by using KeyValuePair.

Input:

var foodPair = new Dictionary<string, string>
{
    {"Pizza", "Italian"},
    {"Curry", "Indian"},
    {"Masala", "Indian"}
};

var teamPreference = new Dictionary<string, string>
{
    {"Jose", "Italian" },
    {"John", "Indian" },
    {"Sarah", "Thai" },
    {"Mary", "*" }
};

* means give everything
If selected food type is not available than give nothing. i.e Thai

Output:

Jose, Pizza
John, Curry
John, Masala
Mary, Pizza
Mary, Curry
Mary, Masala

Working Result by using KeyValuePair<string, string>:

https://dotnetfiddle.net/hNdlfy

I want to achieve same result by using string[,] but I don't know how to insert in dimensional array. Basically I am trying to learn how multidimensional arrays works by doing this kind of example.

Body:
You cannot "insert" in any array (single-dimensional or multidimensional). But you can create array with enough space.

    var foodPair = new Dictionary<string, string> { { "Pizza", "Italian" }, { "Curry", "Indian" }, { "Masala", "Indian" } };
    var teamPreference = new Dictionary<string, string> { { "Jose", "Italian" }, { "John", "Indian" }, { "Sarah", "Thai" }, { "Mary", "*" } };
    var results = new List<KeyValuePair<string, string>>();

    var results2 = new string[10, 2];
    int rowIndex = 0;

    foreach (var teamMember in teamPreference)
    {
        switch (teamMember.Key)
        {
            case "Jose":
                var key = foodPair.FirstOrDefault(x => x.Value == "Italian").Key;
                results.Add(new KeyValuePair<string, string>(teamMember.Key, key));
                results2[rowIndex, 0] = teamMember.Key;
                results2[rowIndex, 1] = key;
                rowIndex++;
                break;

            case "John":
                var getAll = foodPair.Where(x => x.Value == "Indian").ToList();
                if (getAll.Any())
                {
                    results.AddRange(getAll.Select(a => new KeyValuePair<string, string>(teamMember.Key, a.Key)));
                }
                foreach (var item in getAll)
                {
                    results2[rowIndex, 0] = teamMember.Key;
                    results2[rowIndex, 1] = item.Key;
                    rowIndex++;
                }
                break;

            case "Sarah":
                var c = foodPair.FirstOrDefault(x => x.Value == "Thai").Key;
                if (!string.IsNullOrEmpty(c))
                {
                    results.Add(new KeyValuePair<string, string>(teamMember.Key, c));
                }
                if (!string.IsNullOrEmpty(c))
                {
                    results2[rowIndex, 0] = teamMember.Key;
                    results2[rowIndex, 1] = c;
                    rowIndex++;
                }

                break;

            case "Mary":
                if (teamMember.Value == "*")
                {
                    var everything = foodPair.Keys.ToList();
                    if (everything.Any())
                    {
                        results.AddRange(everything.Select(food => new KeyValuePair<string, string>(teamMember.Key, food)));
                    }
                    foreach (var item in everything)
                    {
                        results2[rowIndex, 0] = teamMember.Key;
                        results2[rowIndex, 1] = item;
                        rowIndex++;
                    }
                }

                break;
        }
    }

    if (results.Any())
    {
        foreach (var result in results)
        {
            Console.WriteLine("{0}, {1}", result.Key, result.Value);
        }
    }

    Console.WriteLine("Using multidimensional array");

    for (int row = 0; row < rowIndex; row++)
    {
        Console.WriteLine("{0}, {1}", results2[row, 0], results2[row, 1]);
    }

But multidimensional array is not suitable data structure for this task. (You can see code with array looks terrible). Data structure that you need is called tuple and the definition for results can look like var results3 = new List<Tuple<string, string>>();

Additional note - you not need using .Any() with foreach statement. foreach is not executed for empty collections.

Good luck with learning C#!


来源: stackexchange

问:
How do I insert text to the 1st line of a file using sed?
Hi I'm trying to add text to the 1st line of a file using sed
so far iv'e tried

```<code>#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test
</code>```

And this dosn't work
also tried

```<code>#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test
</code>```

this dosn't seem to work either
oddly when I try

```<code>#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test
</code>```

I get the 1st line of text to appear when i use cat test
but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

Can text be inserted into the 1st line of a newly created file using sed?

If yes whats the best way of inserting text after the 1st line of text?

答:
Your command will work if you make sure the input file has at least one line:</p>

```<code>[ "$(wc -l < test)" -gt 0 ] || printf '\n' >> test
sed -i -e '1 i/etc/example/live/example.com/fullchain.pem;\' test
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Hi I'm trying to add text to the 1st line of a file using sed
so far iv'e tried

#!/bin/bash
touch test
sed -i -e '1i/etc/example/live/example.com/fullchain.pem;\' test

And this dosn't work
also tried

#!/bin/bash
touch test
sed -i "1i ssl_certificate /etc/example/live/example.com/fullchain.pem;" test

this dosn't seem to work either
oddly when I try

#!/bin/bash
touch test
echo "ssl_certificate /etc/example/live/example.com/fullchain.pem;" > test

I get the 1st line of text to appear when i use cat test
but as soon as i type sed -i "2i ssl_certificate_key /etc/example/live/example.com/privkey.pem;"
I can't see the information that i sould do on line 2 this being ssl_certificate_key /etc/example/live/example.com/privkey.pem;

so my question to summerise

Can text be inserted into the 1st line of a newly created file using sed?

If yes whats the best way of inserting text after the 1st line of text?

Body:
Your command will work if you make sure the input file has at least one line:

[ "$(wc -l < test)" -gt 0 ] || printf '\n' >> test
sed -i -e '1 i/etc/example/live/example.com/fullchain.pem;\' test


问:
Errorlevel variable not changing after error..?
I'm trying to do a script that will run constantly in background. Its goal is to detect USB flash drives, external hard drives, or any writable device that you'd connect to your computer. Once it detected one, it'd copy a file at the root of this device. Here's my code (the echo lines are for clearer debugging):

```<code>@echo off
:loop
for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do (
    for %%c in (%%b) do (
        for /F "tokens=4" %%d in ('fsutil fsinfo drivetype %%c') do (
            if %%d equ amovible (
                echo Found out that %%c is removable. Trying to echo the content...
                dir %%c >NUL
                echo Error: %errorlevel%
                if %errorlevel%==0 (
                    echo Errorlevel is 0! Copying...
                    if not exist %%c\test.txt (
                        copy .\test.txt %%c\test.txt
                        echo.
                    )
                ) else (
                    echo Errorlevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                  echo.
                )
            )
        )
    )
)
TIMEOUT 2
goto :loop
</code>```

And here's the problem. The condition "if %errorlevel%==0" is supposed to check if the "dir %%c >NUL" command succeeded, so if errorlevel is 0, that means there's a filesystem on the device, and it's not like an empty card reader or an empty floppy drive. The thing is when I execute my code, errorlevel is always 0, and I can't figure out why ("echo Error: %errorlevel%" tells it). So the file test.txt does copy on my USB flash drive, so this basically work, the thing is when it comes to copy the file to my floppy drive, an error box shows up, saying that I should insert a device in the reader, that's why I want to do this errorlevel check.

So if someone has a solution, please help, I'm really stuck.
Thanks in advance.

答:
You need to use delayed expansion (!ErrorLevel!), because otherwise, you get the ErrorLevel value that is present when the entire parenthesised block (that is the nested for loop structure here) is parsed. Since exclamation marks are consumed by the delayed expansion feature, I would enable it only where it is actually needed, like this:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
:loop
for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do (
    for %%c in (%%b) do (
        for /F "tokens=4" %%d in ('fsutil fsinfo drivetype %%c') do (
            if "%%d"=="amovible" (
                echo Found out that %%c is removable. Trying to echo the content...
                dir "%%~c" > nul
                setlocal EnableDelayedExpansion
                echo Error: !ErrorLevel!
                if !ErrorLevel! equ 0 (
                    endlocal
                    echo ErrorLevel is 0! Copying...
                    if not exist "%%~c\test.txt" (
                        copy ".\test.txt" "%%~c\test.txt"
                        echo/
                    )
                ) else (
                    endlocal
                    echo ErrorLevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                    echo/
                )
            )
        )
    )
)
timeout 2
goto :loop
endlocal
```

<p>Alternatively, since <code>dir</code> does never set <code>ErrorLevel</code> to a negative value, you could also use the <code>if not errorlevel 1</code> syntax, meaning "if not <code>ErrorLevel</code> is greater than or equal to <code>1</code>", and therefore "if <code>ErrorLevel</code> is less than <code>1</code>" (apparently you cannot echo the actual <code>ErrorLevel</code> value then):</p>

<pre class="lang-cmd prettyprint-override"><code>                ...
                dir "%%~c" > nul
                if not ErrorLevel 1 (
                    echo ErrorLevel is 0! Copying...
                    if not exist "%%~c\test.txt" (
                        copy ".\test.txt" "%%~c\test.txt"
                        echo/
                    )
                ) else (
                    echo ErrorLevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                    echo/
                )
                ...
</code>```

Another method is to use the conditional execution operators && and/or ||, which lets the following command or block execute only in case the preceding command returns an exit code of zero (most of the time, and also for the dir command here, the exit code is the same value as ErrorLevel):

                ...
                dir "%%~c" > nul && (
                    echo ErrorLevel is 0! Copying...
                    if not exist "%%~c\test.txt" (
                        copy ".\test.txt" "%%~c\test.txt"
                        echo/
                    )
                ) || (
                    echo ErrorLevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                    echo/
                )
                ...
```

Body:
I'm trying to do a script that will run constantly in background. Its goal is to detect USB flash drives, external hard drives, or any writable device that you'd connect to your computer. Once it detected one, it'd copy a file at the root of this device. Here's my code (the echo lines are for clearer debugging):

@echo off
:loop
for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do (
    for %%c in (%%b) do (
        for /F "tokens=4" %%d in ('fsutil fsinfo drivetype %%c') do (
            if %%d equ amovible (
                echo Found out that %%c is removable. Trying to echo the content...
                dir %%c >NUL
                echo Error: %errorlevel%
                if %errorlevel%==0 (
                    echo Errorlevel is 0! Copying...
                    if not exist %%c\test.txt (
                        copy .\test.txt %%c\test.txt
                        echo.
                    )
                ) else (
                    echo Errorlevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                  echo.
                )
            )
        )
    )
)
TIMEOUT 2
goto :loop

And here's the problem. The condition "if %errorlevel%==0" is supposed to check if the "dir %%c >NUL" command succeeded, so if errorlevel is 0, that means there's a filesystem on the device, and it's not like an empty card reader or an empty floppy drive. The thing is when I execute my code, errorlevel is always 0, and I can't figure out why ("echo Error: %errorlevel%" tells it). So the file test.txt does copy on my USB flash drive, so this basically work, the thing is when it comes to copy the file to my floppy drive, an error box shows up, saying that I should insert a device in the reader, that's why I want to do this errorlevel check.

So if someone has a solution, please help, I'm really stuck.
Thanks in advance.

Body:
You need to use delayed expansion (!ErrorLevel!), because otherwise, you get the ErrorLevel value that is present when the entire parenthesised block (that is the nested for loop structure here) is parsed. Since exclamation marks are consumed by the delayed expansion feature, I would enable it only where it is actually needed, like this:

@echo off
setlocal EnableExtensions DisableDelayedExpansion
:loop
for /F "tokens=1*" %%a in ('fsutil fsinfo drives') do (
    for %%c in (%%b) do (
        for /F "tokens=4" %%d in ('fsutil fsinfo drivetype %%c') do (
            if "%%d"=="amovible" (
                echo Found out that %%c is removable. Trying to echo the content...
                dir "%%~c" > nul
                setlocal EnableDelayedExpansion
                echo Error: !ErrorLevel!
                if !ErrorLevel! equ 0 (
                    endlocal
                    echo ErrorLevel is 0! Copying...
                    if not exist "%%~c\test.txt" (
                        copy ".\test.txt" "%%~c\test.txt"
                        echo/
                    )
                ) else (
                    endlocal
                    echo ErrorLevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                    echo/
                )
            )
        )
    )
)
timeout 2
goto :loop
endlocal

Alternatively, since dir does never set ErrorLevel to a negative value, you could also use the if not errorlevel 1 syntax, meaning "if not ErrorLevel is greater than or equal to 1", and therefore "if ErrorLevel is less than 1" (apparently you cannot echo the actual ErrorLevel value then):

                ...
                dir "%%~c" > nul
                if not ErrorLevel 1 (
                    echo ErrorLevel is 0! Copying...
                    if not exist "%%~c\test.txt" (
                        copy ".\test.txt" "%%~c\test.txt"
                        echo/
                    )
                ) else (
                    echo ErrorLevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                    echo/
                )
                ...

Another method is to use the conditional execution operators && and/or ||, which lets the following command or block execute only in case the preceding command returns an exit code of zero (most of the time, and also for the dir command here, the exit code is the same value as ErrorLevel):

                ...
                dir "%%~c" > nul && (
                    echo ErrorLevel is 0! Copying...
                    if not exist "%%~c\test.txt" (
                        copy ".\test.txt" "%%~c\test.txt"
                        echo/
                    )
                ) || (
                    echo ErrorLevel isn't 0. Looks like the drive isn't here, or is unavailable. Aborting copying...
                    echo/
                )
                ...


问:
Use x/y coordinates to set bounds of a moving particle
I have two bitmaps that I draw onto the center of a canvas:
One is only a background, it's a spirit level in top view which doesnt move. The second one is a bitmap looking like a "air bubble". When the user tilts the phone, the sensors read the tilt and the air bubble moves according to the sensor values along the x-axis. However, I need to make sure that the air bubble doesnt move too far, e.g out of the background-bitmap.
So I tried to which x coordinate the bubble can travel to,
before I have to set xPos = xPos -1 using trial and error
This works fine on my device.

To clarify: On my phone, the air bubble could move to the coordinate x = 50 from the middle of the screen. This would be the point, where the bitmap is at the very left of the background spirit level.
On a larger phone, the position x = 50 is too far left, and therefore looking like the air bubble travelled out of the water level.

Now I've tried following:
I calculated the area in % in which the air bubble can move. Let's say that
is 70% of the entire width of the bitmap. So I tried to calculate the two x boundary values:

leftBoundary = XmiddlePoint - (backgroundBitmap.getWidth() * 0.35);
 rightBoundary = XmiddlePoint + (backgroundBitmap.getWidth() * 0.35);

...which doesnt work when testing with different screen sizes :(

Is it possible to compensate for different screen sizes and densities using absolute coordinates or do I have to rethink my idea?

If you need any information that I forgot about, please let me know. If this question has already been answered, I would appreciate a link :) Thanks in advance!

Edit:
I load my bitmaps like this:

```<code>private Bitmap backgroundBitmap;
private static final int BITMAP_WIDTH = 1898;
private static final int BITMAP_HEIGHT = 438;

public class SimulationView extends View implements SensorEventListener{
public SimulationView(Context context){
Bitmap map = BitmapFactory.decodeResource(getResources, R.mipmap.backgroundImage);
backgroundBitmap = Bitmap.createScaledBitmap(map, BITMAP_WIDTH, BITMAP_HEIGHT, true;
}
</code>```

and draw it like this:

```<code>protected void onDraw(Canvas canvas){
canvas.drawBitmap(backgroundBitmap, XmiddlePoint - BITMAP_WIDTH / 2, YmiddlePont - BITMAP_HEIGHT / 2, null);
}
</code>```

backgroundBitmap.getWidth() and getHeight() prints out the correct sizes.
Calculating like mentioned above would return following boundaries:

```<code>DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity)  getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int width = displayMetrics.widthPixels;
    //which prints out width = 2392
    xMiddlePoint = width / 2;
    // = 1196
    leftBoundary = xMiddlePoint - (BITMAP.getWidth()* 0.35);
    // = 531,7
</code>```

However, when I use trial and error, the right x coordinate seems to be at around 700.

答:
I've come across a great explanation on how to fix my issue here.
As user AgentKnopf explained, you have to scale coordinates or bitmaps like this:

X = (targetScreenWidth / defaultScreenWidth) * defaultXCoordinate

Y = (targetScreenHeight / defaultScreenHeight) * defaultYCoordinate

which, in my case, translates to:

```<code>int defaultScreenWidth = 1920;
int defaultXCoordinate = 333;
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
displayWidth = displayMetrics.widthPixels;
leftBoundary = (displayWidth / defaultScreenWidth) * defaultXCoordinates
</code>```

Body:
I have two bitmaps that I draw onto the center of a canvas:
One is only a background, it's a spirit level in top view which doesnt move. The second one is a bitmap looking like a "air bubble". When the user tilts the phone, the sensors read the tilt and the air bubble moves according to the sensor values along the x-axis. However, I need to make sure that the air bubble doesnt move too far, e.g out of the background-bitmap.
So I tried to which x coordinate the bubble can travel to,
before I have to set xPos = xPos -1 using trial and error
This works fine on my device.

To clarify: On my phone, the air bubble could move to the coordinate x = 50 from the middle of the screen. This would be the point, where the bitmap is at the very left of the background spirit level.
On a larger phone, the position x = 50 is too far left, and therefore looking like the air bubble travelled out of the water level.

Now I've tried following:
I calculated the area in % in which the air bubble can move. Let's say that
is 70% of the entire width of the bitmap. So I tried to calculate the two x boundary values:

leftBoundary = XmiddlePoint - (backgroundBitmap.getWidth() * 0.35);
 rightBoundary = XmiddlePoint + (backgroundBitmap.getWidth() * 0.35);

...which doesnt work when testing with different screen sizes :(

Is it possible to compensate for different screen sizes and densities using absolute coordinates or do I have to rethink my idea?

If you need any information that I forgot about, please let me know. If this question has already been answered, I would appreciate a link :) Thanks in advance!

Edit:
I load my bitmaps like this:

private Bitmap backgroundBitmap;
private static final int BITMAP_WIDTH = 1898;
private static final int BITMAP_HEIGHT = 438;

public class SimulationView extends View implements SensorEventListener{
public SimulationView(Context context){
Bitmap map = BitmapFactory.decodeResource(getResources, R.mipmap.backgroundImage);
backgroundBitmap = Bitmap.createScaledBitmap(map, BITMAP_WIDTH, BITMAP_HEIGHT, true;
}

and draw it like this:

protected void onDraw(Canvas canvas){
canvas.drawBitmap(backgroundBitmap, XmiddlePoint - BITMAP_WIDTH / 2, YmiddlePont - BITMAP_HEIGHT / 2, null);
}

backgroundBitmap.getWidth() and getHeight() prints out the correct sizes.
Calculating like mentioned above would return following boundaries:

DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity)  getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int width = displayMetrics.widthPixels;
    //which prints out width = 2392
    xMiddlePoint = width / 2;
    // = 1196
    leftBoundary = xMiddlePoint - (BITMAP.getWidth()* 0.35);
    // = 531,7

However, when I use trial and error, the right x coordinate seems to be at around 700.

Body:
I've come across a great explanation on how to fix my issue here.
As user AgentKnopf explained, you have to scale coordinates or bitmaps like this:

X = (targetScreenWidth / defaultScreenWidth) * defaultXCoordinate

Y = (targetScreenHeight / defaultScreenHeight) * defaultYCoordinate

which, in my case, translates to:

int defaultScreenWidth = 1920;
int defaultXCoordinate = 333;
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
displayWidth = displayMetrics.widthPixels;
leftBoundary = (displayWidth / defaultScreenWidth) * defaultXCoordinates


问:
Word loses focus (minimized) after closing non-modal form
I have a problem with the Word Add-in I'm developing.

The problem:
If I open non-modal form called Form1, and inside this form I press a button that opens another modal form called Form2. Now I close both forms, but Word windows is losing focus and minimized.

Note that this is not happening when I just open Form1 and close it.

When I open a non-modal form (let's call it Form1) by using Form1.Show(IWin32Window);

where the IWin32Window object is created by this method:

```<code>public static MyWin32Window getWordWindow()
{
    IntPtr wordWindow = NativeMethods.FindWindowW("OpusApp", Globals.ThisAddIn.Application.ActiveWindow.Caption + " - Microsoft Word");
    MyWin32Window myWin = new MyWin32Window(wordWindow);
    return myWin;
}
</code>```

The problem occurs only when I open another form from Form1, let's say Form2 is opened, but Form2 is modal form and opened with:

```<code>Form2.ShowDialog();
</code>```

It works fine, but when I close Form2 and then Form1, the Word window is minimized. How can I prevent this behavior?

I also tried setting Form1 as the owner of Form2, like this:

```<code>Form2.ShowDialog(this);
</code>```

but same result.

答:
I found that I was able to resolve this problem by using

```<code>Form.Show();
</code>```

instead of ShowDialog().

Body:
I have a problem with the Word Add-in I'm developing.

The problem:
If I open non-modal form called Form1, and inside this form I press a button that opens another modal form called Form2. Now I close both forms, but Word windows is losing focus and minimized.

Note that this is not happening when I just open Form1 and close it.

When I open a non-modal form (let's call it Form1) by using Form1.Show(IWin32Window);

where the IWin32Window object is created by this method:

public static MyWin32Window getWordWindow()
{
    IntPtr wordWindow = NativeMethods.FindWindowW("OpusApp", Globals.ThisAddIn.Application.ActiveWindow.Caption + " - Microsoft Word");
    MyWin32Window myWin = new MyWin32Window(wordWindow);
    return myWin;
}

The problem occurs only when I open another form from Form1, let's say Form2 is opened, but Form2 is modal form and opened with:

Form2.ShowDialog();

It works fine, but when I close Form2 and then Form1, the Word window is minimized. How can I prevent this behavior?

I also tried setting Form1 as the owner of Form2, like this:

Form2.ShowDialog(this);

but same result.

Body:
I found that I was able to resolve this problem by using

Form.Show();

instead of ShowDialog().


问:
How to locate a specific form field in this image
In Brazil a standard form filled (by hand) for every newborn in a hospital. This form is called "DNV" (after the Portuguese for "Born Alive Declaration"). There is also a form called "DO" (after the Portuguese for "Decease Declaration"). In my state the hospitals send close to a million of these forms to the agency where I work where we compute a database called "Vital Statistics". I'm investigating if it is possible to automate the work. Since commercial ICR solutions cost a lot of money nobody in charge believe it can be done internally so it is  a grassroots project.

The top of the form is like this:

I got my hands into 100K PDF files sent from several hospitals and was able to classify them into one of the two types (DNV or DO) using a naive algorithm: first I locate the black rectangle that contains the type of the document (using cv2.findContours and a bit of heuristics) and apply a OCR (pytesseract.image_to_string). I've found 20k "decease declaration" (DO) and 80k "born alive declaration".

Using a similar algorithm I was able to OCR the number at the right of the black rectangle and link 55k form images with the corresponding record in a database filled by professional typists based on these documents.

Now I want to locate the date field (in red) in order to try a bit of machine learning for recognizing the digits - the field is highlighted below:

First I tried a "template matching" algorithm using this as the template:

This works well but only if the template and the form image are in the same scale and angle. The cv2.matchTemplate method is really sensitive about scale. I tried feature matching algorithms using SURF but I'm having a hard time getting it to work (feels like overkill).

Since it is easy to locate the black rectangle in the left, I'm thinking some options in order to locate the digits:

normalizing the scale and angle based on the black rectangle and trying cv2.matchTemplate.

trying to locate the contour, simplify it using cv2.approxPolyDP and guess the digits location.

My question is: any advice about how to attack the problem? What other algorithm can I use in order to locate this form field if the input is not normalized in terms of resolution/angle?

[update #1]

Given (x, y, w, h) as the position and size of the black rectangle in the left, I can narrow down the search with reasonable confidence.

Trying random samples, this formula gives me:

```<code>img.crop((x+w, y+h/3, x+h*3.05, y+2*h/3))
</code>```

[update #2]

I just learned about erode and dilate, now they are my new best friends.

```<code>horizontal = edges.copy()
vertical = edges.copy()

kv = np.ones((25, 1), np.uint8)
kh = np.ones((1, 30), np.uint8)

horizontal = cv2.dilate(cv2.erode(horizontal, kh, iterations=2), kh, iterations=2)
vertical = cv2.dilate(cv2.erode(vertical, kv, iterations=2), kv, iterations=2)

grid = horizontal | vertical

plt.imshow(edges, 'gray')
</code>```

```<code>plt.imshow(grid, 'gray')
</code>```

BTW I don't have a clue about computer vision. Lets get back to google...

答: Try find fields corners, calc angle/scale and than just transform image into normalized image.</p>

Body:
In Brazil a standard form filled (by hand) for every newborn in a hospital. This form is called "DNV" (after the Portuguese for "Born Alive Declaration"). There is also a form called "DO" (after the Portuguese for "Decease Declaration"). In my state the hospitals send close to a million of these forms to the agency where I work where we compute a database called "Vital Statistics". I'm investigating if it is possible to automate the work. Since commercial ICR solutions cost a lot of money nobody in charge believe it can be done internally so it is  a grassroots project.

The top of the form is like this:

I got my hands into 100K PDF files sent from several hospitals and was able to classify them into one of the two types (DNV or DO) using a naive algorithm: first I locate the black rectangle that contains the type of the document (using cv2.findContours and a bit of heuristics) and apply a OCR (pytesseract.image_to_string). I've found 20k "decease declaration" (DO) and 80k "born alive declaration".

Using a similar algorithm I was able to OCR the number at the right of the black rectangle and link 55k form images with the corresponding record in a database filled by professional typists based on these documents.

Now I want to locate the date field (in red) in order to try a bit of machine learning for recognizing the digits - the field is highlighted below:

First I tried a "template matching" algorithm using this as the template:

This works well but only if the template and the form image are in the same scale and angle. The cv2.matchTemplate method is really sensitive about scale. I tried feature matching algorithms using SURF but I'm having a hard time getting it to work (feels like overkill).

Since it is easy to locate the black rectangle in the left, I'm thinking some options in order to locate the digits:

normalizing the scale and angle based on the black rectangle and trying cv2.matchTemplate.

trying to locate the contour, simplify it using cv2.approxPolyDP and guess the digits location.

My question is: any advice about how to attack the problem? What other algorithm can I use in order to locate this form field if the input is not normalized in terms of resolution/angle?

[update #1]

Given (x, y, w, h) as the position and size of the black rectangle in the left, I can narrow down the search with reasonable confidence.

Trying random samples, this formula gives me:

img.crop((x+w, y+h/3, x+h*3.05, y+2*h/3))

[update #2]

I just learned about erode and dilate, now they are my new best friends.

horizontal = edges.copy()
vertical = edges.copy()

kv = np.ones((25, 1), np.uint8)
kh = np.ones((1, 30), np.uint8)

horizontal = cv2.dilate(cv2.erode(horizontal, kh, iterations=2), kh, iterations=2)
vertical = cv2.dilate(cv2.erode(vertical, kv, iterations=2), kv, iterations=2)

grid = horizontal | vertical

plt.imshow(edges, 'gray')

plt.imshow(grid, 'gray')

BTW I don't have a clue about computer vision. Lets get back to google...


问:
Update ejs variable on server side using socket.io, node.js, and mongodb
I am using mongodb with mongoose to maintain a list of stocks across clients. I want to simultaneously update the list using socket.io when one user makes a change. I can connect to the socket and update client javascript but not make changes to variable on server side.

app.js - Server

```<code>// connect to socket.io
io.on('connection', function (socket) {
   console.log('Client Connected..');

    ///retrieve new stock from client
    socket.on('submitStock', function (data) {
       console.log(data);
       ///do mongodb stuff here

       ///send new stocks to all clients
       socket.emit('activeStocks', data);
     });
});
</code>```

script.js - client

```<code>var socket = io.connect();

///connect to socket
socket.on('connect', function (data) {
   socket.emit('join', 'Hello World from client');
});

///use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
    //var stockList = $('#stockList');
    socket.emit('submitStock', 'here is the data');
});

//retrieve the new stock from the server and update list
socket.on('activeStocks', function(data) {
   //how to update activeStocks here??
   console.log(data);
});
</code>```

index.ejs

```<code><% if (message.length > 0) { %>
   <div class="alert alert-danger"><p><%= message %></p></div>
<% } %>

<div class="container">
  <form id="addStock" action="/add" method="post">
    <div class="form-inline">
      <input type="text" class="form-control" name="stockTicker" placeholder="Enter a stock ticker">
      <button type="submit" class="btn btn-primary"><span>Add Stock</span></button>
    </div>
  </form>
</div>

<% if (activeStocks) { %>
  <% for (var i=0; i< activeStocks.length; i++) { %>
    <div> <%- activeStocks[i] %></div>
  <% } %>
<% } %>
</code>```

答:
Suppose that we have a div in index.js let it be
,

Let data be an array of strings,

Try the following code:

```<code>socket.on('activeStocks', function(data) {
    document.getElementById('stocks').innerHTML = '';
    data.forEach( function (stock) {
        document.getElementById('stocks').innerHTML += stock + '<br>';
    });
});
</code>```

Body:
I am using mongodb with mongoose to maintain a list of stocks across clients. I want to simultaneously update the list using socket.io when one user makes a change. I can connect to the socket and update client javascript but not make changes to variable on server side.

app.js - Server

// connect to socket.io
io.on('connection', function (socket) {
   console.log('Client Connected..');

    ///retrieve new stock from client
    socket.on('submitStock', function (data) {
       console.log(data);
       ///do mongodb stuff here

       ///send new stocks to all clients
       socket.emit('activeStocks', data);
     });
});

script.js - client

var socket = io.connect();

///connect to socket
socket.on('connect', function (data) {
   socket.emit('join', 'Hello World from client');
});

///use submit button to send the new stock to server
$('#addStock').on('submit', function(e){
    //var stockList = $('#stockList');
    socket.emit('submitStock', 'here is the data');
});

//retrieve the new stock from the server and update list
socket.on('activeStocks', function(data) {
   //how to update activeStocks here??
   console.log(data);
});

index.ejs

<% if (message.length > 0) { %>

<%= message %>

<% } %>

  <form id="addStock" action="/add" method="post">

      <input type="text" class="form-control" name="stockTicker" placeholder="Enter a stock ticker">
      <button type="submit" class="btn btn-primary">Add Stock</button>

  </form>

<% if (activeStocks) { %>
  <% for (var i=0; i< activeStocks.length; i++) { %>

 <%- activeStocks[i] %>

  <% } %>
<% } %>

Body:
Suppose that we have a div in index.js let it be <div id="stocks">,

Let data be an array of strings,

Try the following code:

socket.on('activeStocks', function(data) {
    document.getElementById('stocks').innerHTML = '';
    data.forEach( function (stock) {
        document.getElementById('stocks').innerHTML += stock + '<br>';
    });
});


问:
Choosing a simple web application framework
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages. </p>

<p>I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail. </p>

答:
I'd guess something that would run upon a LAMP stack would be the easiest to set up. In that case, I guess there would be some good choices in CodeIgniter and Zend Framework. Then there's Symphony and CakePHP, but I've heard mixed reviews (concerning stagnating community and/or tricky configuration) of the two latter.

Unfortunately, I haven't had the time to test thoroughly any of the four, because I've been busy coding my own framework, which I will not shamelessly (or otherwise) plug.

OwnerDisplayName: nagul

ContentLicense: CC BY-SA 2.5

Body:
I'm evaluating web application frameworks for a hobby project I'm starting, and am beginning to go crazy trying to decide among the vast number of frameworks available to choose. The framework language isn't helping me filter out frameworks as I have varying levels of experience with Java, Python, Ruby and C#, and don't mind frameworks in any of these languages.

I'm looking for help in narrowing the choice down to a few that I can then investigate in more detail.

LastEditorDisplayName: Marko Dumic

OwnerDisplayName: wolfie


问:
Optimized GPU to CPU data transfer
I'm a bit out of my depth here (best way to be me thinks), but I am poking around looking for an optimization that could reduce GPU to CPU data transfer for my application.

I have an application that performs some modifications to vertex data in the GPU. Occasionally the CPU has to read back parts of the modified vertex data and then compute some parameters which then get passed back into the GPU shader via uniforms, forming a loop.

It takes too long to transfer all the vertex data back to the CPU and then sift through it on the CPU (millions of points), and so I have a "hack" in place to reduce the workload to usable, although not optimal.

What I do:

CPU: read image

CPU: generate 1 vertex per pixel, Z based on colour information/filter etc

CPU: transfer all vertex data to GPU

GPU: transform feedback used to update GL_POINT vertex coords in realtime based on some uniform parameters set from the CPU.

When I wish to read only a rectangular "section", I use glMapBufferRange to map the entire rows that comprise the desired rect (bad diagram alert):

This is supposed to represent the image/set of vertices in the GPU. My "hack" involves having to read all the blue and red vertices. This is because I can only specify 1 continuous range of data to read back.

Does anyone know a clever way to efficiently get at the red, without the blue? (without having to issue a series of glMapBufferRange calls)

EDIT-

The use case is that I render the image into a 3D world as GLPoints, coloured and offset in the Z by an amount based on the colour info (sized etc according to distance). Then the user can modify the vertex Z data with a mouse cursor brush. The logic behind some of the brush application code needs to know the Z's of the area under the mouse (brush circle), eg. min/max/average etc so that the CPU can control the shaders modification of data by setting a series of uniforms that feed into the shader. So for example the user can say, I want all points under the cursor to set to the average value. This could all probably be done entirely in the GPU, but the idea is that once I get the CPU-GPU "loop" (optimised as far as I can reasonably do), I can then expand out the min/max/avg stuff to do interesting things on the CPU that would be cumbersome (probably) to do entirely on the GPU.

Cheers!
Laythe

答:
I suppose you are asking because you can not do all work at shaders, right?

If you render to a Frame Buffer Object, then bind it as GL_READ_FRAMEBUFFER, you can read a block of it by glReadPixels.

Title: Optimized GPU to CPU data transfer


问:
Replace values in a pandas column using another pandas df which has the corresponding replacements
I have a pandas df named inventory, which has a column containing Part Numbers (AlphaNumeric). Some of those part numbers have been superseded and I have another df named replace_with containing two columns, 'old part numbers' and 'new part numbers'.
For example:

Inventory has values like:

```<code>* 123AAA
* 123BBB
* 123CCC
......
</code>```

and replace-with has values like

```<code>**oldPartnumbers**   .....        **newPartnumbers**

* 123AAA        ............            123ABC
* 123CCC          ...........          123DEF
</code>```

SO, i need to replace corresponding values in inventory with the new numbers. After replacement inventory will look like as follows:

```<code>* 123ABC
* 123BBB
* 123DEF
</code>```

Is there a simple way to do that in python? Thanks!

答:
This solution is relatively fast - it uses pandas data alignment and the numpy "copyto" function.

```<code>import pandas as pd
import numpy as np

df1 = pd.DataFrame({'partNumbers': ['123AAA', '123BBB', '123CCC', '123DDD']})
df2 = pd.DataFrame({'oldPartnumbers': ['123AAA', '123BBB', '123CCC'],
                    'newPartnumbers': ['123ABC', '123DEF', '123GHI']})

# assign index in each dataframe to original part number columns
# (faster than set_index method, but use set_index if original index must be preserved)
df1.index = df1.partNumbers
df2.index = df2.oldPartnumbers
# use pandas index data alignment
df1['updatedPartNumbers'] = df2.newPartnumbers
# use numpy to copy in old part num when a new part num is not found
np.copyto(df1.updatedPartNumbers.values,
          df1.partNumbers.values,
          where=pd.isnull(df1.updatedPartNumbers))
# reset index
df1.reset_index(drop=True, inplace=True)
</code>```

df1:

```<code>  partNumbers updatedPartNumbers
0      123AAA             123ABC
1      123BBB             123DEF
2      123CCC             123GHI
3      123DDD             123DDD
</code>```

Body:
I have a pandas df named inventory, which has a column containing Part Numbers (AlphaNumeric). Some of those part numbers have been superseded and I have another df named replace_with containing two columns, 'old part numbers' and 'new part numbers'.
For example:

Inventory has values like:

* 123AAA
* 123BBB
* 123CCC
......

and replace-with has values like

**oldPartnumbers**   .....        **newPartnumbers**

* 123AAA        ............            123ABC
* 123CCC          ...........          123DEF

SO, i need to replace corresponding values in inventory with the new numbers. After replacement inventory will look like as follows:

* 123ABC
* 123BBB
* 123DEF

Is there a simple way to do that in python? Thanks!

Body:
This solution is relatively fast - it uses pandas data alignment and the numpy "copyto" function.

import pandas as pd
import numpy as np

df1 = pd.DataFrame({'partNumbers': ['123AAA', '123BBB', '123CCC', '123DDD']})
df2 = pd.DataFrame({'oldPartnumbers': ['123AAA', '123BBB', '123CCC'],
                    'newPartnumbers': ['123ABC', '123DEF', '123GHI']})

# assign index in each dataframe to original part number columns
# (faster than set_index method, but use set_index if original index must be preserved)
df1.index = df1.partNumbers
df2.index = df2.oldPartnumbers
# use pandas index data alignment
df1['updatedPartNumbers'] = df2.newPartnumbers
# use numpy to copy in old part num when a new part num is not found
np.copyto(df1.updatedPartNumbers.values,
          df1.partNumbers.values,
          where=pd.isnull(df1.updatedPartNumbers))
# reset index
df1.reset_index(drop=True, inplace=True)

df1:

  partNumbers updatedPartNumbers
0      123AAA             123ABC
1      123BBB             123DEF
2      123CCC             123GHI
3      123DDD             123DDD


答:
For reducing boilerplate code, download Google Guava and use this code:</p>

```<code>File inputFile = new File("input.log");
File outputLog1 = new File("log1.log");
File outputLog2 = new File("log2.log");

String match1 = "[ 6796]";
String match2 = "[ 5960]";

Files.append("Request from Centercord.\n", outputLog1, Charsets.UTF_8);
Files.append("Response from Centercord.\n", outputLog2, Charsets.UTF_8);

List<String> lines = Files.readLines(inputFile, Charsets.UTF_8);

for (String line : lines) {
    if(line.contains(match1)) Files.append(line + "\n", outputLog1, Charsets.UTF_8);
    if(line.contains(match2)) Files.append(line + "\n", outputLog2, Charsets.UTF_8);
}
</code>```

Title: Parsing a log file in Java

Body:
All,

I have a log file with the below content.

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************

I need to create two log files one is for storing all the Request details and the other one is for storing all the Response details. How can I parse this and prepare two log files?.

I need the below answer.

Log 1:

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

2010-12-14 12:42:13.724 [ 6796] ****************************

Log 2:

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Regards,
Kanagaraj

Body:
For reducing boilerplate code, download Google Guava and use this code:

File inputFile = new File("input.log");
File outputLog1 = new File("log1.log");
File outputLog2 = new File("log2.log");

String match1 = "[ 6796]";
String match2 = "[ 5960]";

Files.append("Request from Centercord.\n", outputLog1, Charsets.UTF_8);
Files.append("Response from Centercord.\n", outputLog2, Charsets.UTF_8);

List<String> lines = Files.readLines(inputFile, Charsets.UTF_8);

for (String line : lines) {
    if(line.contains(match1)) Files.append(line + "\n", outputLog1, Charsets.UTF_8);
    if(line.contains(match2)) Files.append(line + "\n", outputLog2, Charsets.UTF_8);
}


问:
awk to extract lines in file that contain matching pattern and variable digit
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa
</code>```

desired output tab-delimeted

```<code>Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa
</code>```

awk

```<code> awk '$2 ~ /^exon [0-9][0-9] sequence$/' file
</code>```

答:
Given:

```<code>awk 'BEGIN{FS="\t"; OFS="|"} $1=$1' file
Tier 2|exon 10 sequence|xxxxx
Tier 2|full sequence|yyyyy
Tier 1|exon 5 sequence|aaaaa
</code>```

(i.e., the tabs are where the | are above)

You can do:

```<code>$ awk -F"\t" '$2~/exon[ ]+[0-9][0-9]?/' /tmp/file
Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa
</code>```

Body:
I am trying to use awk to extract those lines that in $2 contain exon (some digit that is 1-99) sequence. The text will always be the same but the digit will be variable.

file tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 2  full sequence   yyyyy
Tier 1  exon 5 sequence aaaaa

desired output tab-delimeted

Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa

awk

 awk '$2 ~ /^exon [0-9][0-9] sequence$/' file

Body:
Given:

awk 'BEGIN{FS="\t"; OFS="|"} $1=$1' file
Tier 2|exon 10 sequence|xxxxx
Tier 2|full sequence|yyyyy
Tier 1|exon 5 sequence|aaaaa

(i.e., the tabs are where the | are above)

You can do:

$ awk -F"\t" '$2~/exon[ ]+[0-9][0-9]?/' /tmp/file
Tier 2  exon 10 sequence    xxxxx
Tier 1  exon 5 sequence aaaaa


问:
How to validate user input with filter_var?
I'm creating a basic sign up form, where I want to validate the user input. I've read a LOT of different methods of doing this. First of all, mine is not working because it echoes "Email is valid" when it is not a valid email. I really wish I could figure out the most efficient, succinct way of doing this!

So my two questions are:

1.) Is there something wrong in my code that says it's a valid email even though it isn't?

2.) How can I make this as efficient as possible?

Here is the code:

```<code><?php
include('functions.php');

$server = "localhost";
$auth = "root";
$pass = "password";
$db = "users";

$conn = connect_to_db($server, $auth, $pass, $db);

$signup = isset($_POST['submit']);
$output = NULL;

if( $signup ){
  $username = htmlspecialchars($_POST['username']);
  $password = md5($_POST['password']);
  $email = $_POST['email'];
  if( filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($username) && !empty($password) && !empty($email) ){
    echo 'Email is valid';
      $sql = "SELECT username FROM info WHERE username = '$username'";
      $result = mysqli_query($conn, $sql);
      if( mysqli_num_rows($result) > 0 ){
        echo "Sorry, there is already an account registered with that username";
      } else {
        $sql = "INSERT INTO info (username, password, date_created) VALUES ('$username', '$password', NOW())";
        mysqli_query($conn, $sql);
        $output = "<p> Username: $username <br />" . "Password: $password </p>";
      }
  } elseif ( empty($username) || empty($password) ) {
        $output = "<p> Both fields are required </p>";
  }
  echo $output;
}

?>

<!DOCTYPE html>
<html>

<head>
  <title>My Website</title>
</head>

<body>

<form method="POST">
  <h1>Signup: </h1><br />
  Choose a username: <input type="text" name="username" /> <br />
  Choose a password: <input type="password" name="password" /> <br />
  Enter your email: <input type="email" name="email" /> <br />
  <input type="submit" name="submit" value="Signup" />
  <p>Already have an account? Login here: <br /> <a href="index.php">Login</a></p>
</form>

</body>
</html>
</code>```

答:
Emm .. For the username and password inputs you can use ths function and put it in the functions file:

```<code> function makeItSafe($value) {
        htmlspecialchars($value);
        strip_tags($value);
        htmlentities($value, ENT_QUOTES);
        return $value;
    }
</code>```

And for the email, yes it is you can use the filter_var function or use the RegExp way .. But in my opinion the filter_var is easier for use :)

Body:
I'm creating a basic sign up form, where I want to validate the user input. I've read a LOT of different methods of doing this. First of all, mine is not working because it echoes "Email is valid" when it is not a valid email. I really wish I could figure out the most efficient, succinct way of doing this!

So my two questions are:

1.) Is there something wrong in my code that says it's a valid email even though it isn't?

2.) How can I make this as efficient as possible?

Here is the code:

<?php
include('functions.php');

$server = "localhost";
$auth = "root";
$pass = "password";
$db = "users";

$conn = connect_to_db($server, $auth, $pass, $db);

$signup = isset($_POST['submit']);
$output = NULL;

if( $signup ){
  $username = htmlspecialchars($_POST['username']);
  $password = md5($_POST['password']);
  $email = $_POST['email'];
  if( filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($username) && !empty($password) && !empty($email) ){
    echo 'Email is valid';
      $sql = "SELECT username FROM info WHERE username = '$username'";
      $result = mysqli_query($conn, $sql);
      if( mysqli_num_rows($result) > 0 ){
        echo "Sorry, there is already an account registered with that username";
      } else {
        $sql = "INSERT INTO info (username, password, date_created) VALUES ('$username', '$password', NOW())";
        mysqli_query($conn, $sql);
        $output = "
 Username: $username
" . "Password: $password
";
      }
  } elseif ( empty($username) || empty($password) ) {
        $output = "
 Both fields are required
";
  }
  echo $output;
}

?>

<!DOCTYPE html>

  <title>My Website</title>

<form method="POST">

Signup:

  Choose a username: <input type="text" name="username" />

  Choose a password: <input type="password" name="password" />

  Enter your email: <input type="email" name="email" />

  <input type="submit" name="submit" value="Signup" />

Already have an account? Login here:
 Login

</form>

Body:
Emm .. For the username and password inputs you can use ths function and put it in the functions file:

 function makeItSafe($value) {
        htmlspecialchars($value);
        strip_tags($value);
        htmlentities($value, ENT_QUOTES);
        return $value;
    }

And for the email, yes it is you can use the filter_var function or use the RegExp way .. But in my opinion the filter_var is easier for use :)


问:
error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml
When I followed the instructions to add an ad into my app by xml, I got the following errors:

```<code>Description Resource Path Location Type
error: No resource identifier found for attribute 'adSize' in package 'com.google.example'  main.xml    /HelloWorld/res/layout  line 12 Android AAPT Problem
Description Resource Path Location Type
error: No resource identifier found for attribute 'adUnitId' in package 'com.google.example'    main.xml    /HelloWorld/res/layout  line 12 Android AAPT Problem
</code>```

I did edit the main.xml, add attrs.xml file but the compiler didn't like it.

答:
I added in android.support.design.widget.NawigationView this parameter:

```<code>android:layout_gravity="start"
</code>```

And problem was solved.

Body:
When I followed the instructions to add an ad into my app by xml, I got the following errors:

Description Resource Path Location Type
error: No resource identifier found for attribute 'adSize' in package 'com.google.example'  main.xml    /HelloWorld/res/layout  line 12 Android AAPT Problem
Description Resource Path Location Type
error: No resource identifier found for attribute 'adUnitId' in package 'com.google.example'    main.xml    /HelloWorld/res/layout  line 12 Android AAPT Problem

I did edit the main.xml, add attrs.xml file but the compiler didn't like it.

Body:
I added in android.support.design.widget.NawigationView this parameter:

android:layout_gravity="start"

And problem was solved.


问:
How to create complex ViewModels in MVC ASP.NET
So I get the concept of ViewModels, in particular the security issue, where you want to restrict the controller capabilities to the reduced set of fields in a ViewModel (as the typical User model, where the ViewModel has no information about passwords and roles).

Assume a ViewModel deriving from different Models, how would one correctly implement this (keeping e.g. the security thought in mind). Here an image that depicts the issue

I could imagine, that it is better to derive from "Sub-ViewModels" rather than directly from the Models themselves. Is there a best-practice way to do this?

答:
No man, the whole purpose of a view model is to model the exact data you need for a view, nothing more, nothing less. It's not really a security issue, I mean, if you were to be storing things like passwords and stuff in the viewmodel than your doing wrong on such a level I've never seen before. ViewModels main purpose in the mvc framework is to allow you to pack and unpack multiple models and extra properties in order for your user to be able complete whatever targeted action they need to complete without giving them the impression they are drinking from a firehouse. I guess it has some "security" standpoints as you don't need to pass full models but just because something is included in the view model doesn't mean that you have to actively output HTML for that property. Most of those actions should occur server side anyway or in razor checks that generate the HTML.

If you are overlyconcerned about security and your controllers then you should look into 3 tier architecture anyway.


问:
JSON file proper Case and word spacing
I am wondering what will be the best approach for word case and word delimiter in JSON

considering that later on the JSON file will be converted to a Java Pojo and i would like this Java Pojo to be in ProperCase

I am debating between:

```<code>"sectionSuspensionTiresSteering": [{
"SectionSuspensionTiresSteering": [{
"section_suspension_tires_steering": [{
"section Suspension Tires Steering": [{
</code>```

答:
Use always the first one:

```<code>"sectionSuspensionTiresSteering": [{
</code>```

Examples of similar files in official guides:
https://spring.io/guides/gs/authenticating-ldap/

As you can see here, the gradle file uses this notation and XMLs files too.

Title: JSON file proper Case and word spacing

Body:
I am wondering what will be the best approach for word case and word delimiter in JSON

considering that later on the JSON file will be converted to a Java Pojo and i would like this Java Pojo to be in ProperCase

I am debating between:

"sectionSuspensionTiresSteering": [{
"SectionSuspensionTiresSteering": [{
"section_suspension_tires_steering": [{
"section Suspension Tires Steering": [{

Body:
Use always the first one:

"sectionSuspensionTiresSteering": [{

Examples of similar files in official guides:
https://spring.io/guides/gs/authenticating-ldap/

As you can see here, the gradle file uses this notation and XMLs files too.


问:
Simple regex - ignoring certain characters
I'm trying to use the match method with an argument of a regex to select a valid phone number, by definition, any string with nine digits.

For example:

9347584987 is valid,

(456)322-3456 is valid,

(324)5688890 is valid.

But

(340)HelloWorld is NOT valid and

456748 is NOT valid.

So far, I'm able to use \d{9} to select the example string of 9 digit characters in a row, but I'm not sure how to specifically ignore any character, such as '-' or '(' or ')' in the middle of the sequence.

What kind of Regex could I use here?

答:
I suggest using one regular expression for each valid pattern rather than constructing a single regex. It would be easier to test and debug, and easier to maintain the code. If, for example, "123-456-7890" or 123-456-7890 x231" were in future deemed valid numbers, one need only add a single, simple regex for each to the array VALID_PATTERS below.

```<code>VALID_PATTERS = [/\A\d{10}\z/, /\A\(\d{3}\)\d{3}-\d{4}\z/, /\A\(\d{3}\)\d{7}\z/]

def valid?(str)
  VALID_PATTERS.any? { |r| str.match?(r) }
end

ph_nbrs = %w| 9347584987 (456)322-3456 (324)5688890 (340)HelloWorld 456748 |
ph_nbrs.each { |s| puts "#{s.ljust(15)} \#=> #{valid?(s)}" }
9347584987      #=> true
(456)322-3456   #=> true
(324)5688890    #=> true
(340)HelloWorld #=> false
456748          #=> false
</code>```

String#match? made its debut in Ruby v2.4. There are many alternatives, including str.match(r) and str =~ r.

Body:
I suggest using one regular expression for each valid pattern rather than constructing a single regex. It would be easier to test and debug, and easier to maintain the code. If, for example, "123-456-7890" or 123-456-7890 x231" were in future deemed valid numbers, one need only add a single, simple regex for each to the array VALID_PATTERS below.

VALID_PATTERS = [/\A\d{10}\z/, /\A\(\d{3}\)\d{3}-\d{4}\z/, /\A\(\d{3}\)\d{7}\z/]

def valid?(str)
  VALID_PATTERS.any? { |r| str.match?(r) }
end

ph_nbrs = %w| 9347584987 (456)322-3456 (324)5688890 (340)HelloWorld 456748 |
ph_nbrs.each { |s| puts "#{s.ljust(15)} \#=> #{valid?(s)}" }
9347584987      #=> true
(456)322-3456   #=> true
(324)5688890    #=> true
(340)HelloWorld #=> false
456748          #=> false

String#match? made its debut in Ruby v2.4. There are many alternatives, including str.match(r) and str =~ r.


问:
Python Scipy Kernel Density Estimate Smoothing Issues
Sorry to ask a question with probably a very obvious answer but I'm a bit confused as to how to tweak how much I can smooth with the KDE. My code looks something like this in python:

```<code>kde = scipy.stats.gaussian_kde(c)
P_0 = kde(3)
P_c = kde(c)
</code>```

where c is just a column of numbers and I want to do an integral with the above (that's not too important for the problem I'm having). I'm a bit confused as to how I would change the scott/silverman method in scipy to allow a bit of over/undersmoothing.

答:
You appear to want to tweak the set_bandwidth parameter. That link contains simple example code, which I reduce here to the most basic elements:

```<code>kde = stats.gaussian_kde(c)
kde.set_bandwidth(bw_method=.3)
P = kde(c)
</code>```

So basically, the bandwidth is set via the kde.set_bandwidth(bw_method=X) call, where X is usually a float or one of the methods silverman, scott. The full description actually states that bw_method:

can be ‘scott’, ‘silverman’, a scalar constant or a callable. If a scalar, this will be used directly as kde.factor. If a callable, it should take a gaussian_kde instance as only parameter and return a scalar.

Body:
Sorry to ask a question with probably a very obvious answer but I'm a bit confused as to how to tweak how much I can smooth with the KDE. My code looks something like this in python:

kde = scipy.stats.gaussian_kde(c)
P_0 = kde(3)
P_c = kde(c)

where c is just a column of numbers and I want to do an integral with the above (that's not too important for the problem I'm having). I'm a bit confused as to how I would change the scott/silverman method in scipy to allow a bit of over/undersmoothing.

Body:
You appear to want to tweak the set_bandwidth parameter. That link contains simple example code, which I reduce here to the most basic elements:

kde = stats.gaussian_kde(c)
kde.set_bandwidth(bw_method=.3)
P = kde(c)

So basically, the bandwidth is set via the kde.set_bandwidth(bw_method=X) call, where X is usually a float or one of the methods silverman, scott. The full description actually states that bw_method:

can be ‘scott’, ‘silverman’, a scalar constant or a callable. If a scalar, this will be used directly as kde.factor. If a callable, it should take a gaussian_kde instance as only parameter and return a scalar.


问:
atoi in java using charAt
I know that one solution to do this is the following:

```<code> String tmp = "12345";
      int result = 0;
      for (int i =0; i < tmp.length(); i++){
          char digit = (char)(tmp.charAt(i) - '0');
          result += (digit * Math.pow(10, (tmp.length() - i - 1)));

      }

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

What I don't understand is why is:

```<code>char digit = (char)(tmp.charAt(i) - '0');
</code>```

How can this convert into a digit?

答:
I echo what Tom said.

If you are confused with the above implementation then you can refer the below simpler implementation.

```<code>private static int getDecValue(char hex) {
    int dec = 0;
    switch (hex) {
    case '0':
        dec = 0;
        break;
    case '1':
        dec = 1;
        break;
    case '2':
        dec = 2;
        break;
    case '3':
        dec = 3;
        break;
    case '4':
        dec = 4;
        break;
    case '5':
        dec = 5;
        break;
    case '6':
        dec = 6;
        break;
    case '7':
        dec = 7;
        break;
    case '8':
        dec = 8;
        break;
    case '9':
        dec = 9;
        break;
    default:
        // do nothing
    }
    return dec;
}

public static int atoi(String ascii) throws Exception {
    int integer = 0;
    for (int index = 0; index < ascii.length(); index++) {
        if (ascii.charAt(index) >= '0' && ascii.charAt(index) <= '9') {
            integer = (integer * 10) + getDecValue(ascii.charAt(index));
        } else {
            throw new Exception("Is not an Integer : " + ascii.charAt(index));
        }
    }
    return integer;
}
</code>```

Title: atoi in java using charAt

Body:
I know that one solution to do this is the following:

 String tmp = "12345";
      int result = 0;
      for (int i =0; i < tmp.length(); i++){
          char digit = (char)(tmp.charAt(i) - '0');
          result += (digit * Math.pow(10, (tmp.length() - i - 1)));

      }

      System.out.println(result);

What I don't understand is why is:

char digit = (char)(tmp.charAt(i) - '0');

How can this convert into a digit?

Body:
I echo what Tom said.

If you are confused with the above implementation then you can refer the below simpler implementation.

private static int getDecValue(char hex) {
    int dec = 0;
    switch (hex) {
    case '0':
        dec = 0;
        break;
    case '1':
        dec = 1;
        break;
    case '2':
        dec = 2;
        break;
    case '3':
        dec = 3;
        break;
    case '4':
        dec = 4;
        break;
    case '5':
        dec = 5;
        break;
    case '6':
        dec = 6;
        break;
    case '7':
        dec = 7;
        break;
    case '8':
        dec = 8;
        break;
    case '9':
        dec = 9;
        break;
    default:
        // do nothing
    }
    return dec;
}

public static int atoi(String ascii) throws Exception {
    int integer = 0;
    for (int index = 0; index < ascii.length(); index++) {
        if (ascii.charAt(index) >= '0' && ascii.charAt(index) <= '9') {
            integer = (integer * 10) + getDecValue(ascii.charAt(index));
        } else {
            throw new Exception("Is not an Integer : " + ascii.charAt(index));
        }
    }
    return integer;
}


问:
Datetime format in MSSQL
In my aplication I use a DateEdit control and show the date using this format dd/MM/yyyy so the date is save correctly when I use mssql-server 2014 (spanish) but whe I use mssql-server 2008 (english) the date is stored with this fomat MM/dd/yyyy so what I need to know is if there is a way to store the date with the format dd/MM/yyyy no matter the versión of mssql-server I use or the lenguage I use?

EDIT: to explain better this is the problem, this text 03/07/2017 is stored in the sqlserver 2014 as july 3 of 2017 and in the sqlserver 2008 is stored as march 7 of 2017.

答:
Check the defualt language on your MS SQL Server 2008, and if its possible, you can change to Spanish: How to change Date Format after installing SQL Server

Also, you can format your query output with the CONVERT function (@ZLK post the link) using the format 103: CONVERT (DATETIME,[YOURDATE],103)

Title: Datetime format in MSSQL


问:
Slice is not working in python interpreter in udacity
I wrote this function in a challange using python for udacity:

```<code>example_input="John is connected to Bryant, Debra, Walter.\
John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\
Bryant is connected to Olive, Ollie, Freda, Mercedes.\
Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man.\
Mercedes is connected to Walter, Robin, Bryant.\
Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures.\
Olive is connected to John, Ollie.\
Olive likes to play The Legend of Corgi, Starfleet Commander.\
Debra is connected to Walter, Levi, Jennie, Robin.\
Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords.\
Walter is connected to John, Levi, Bryant.\
Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man.\
Levi is connected to Ollie, John, Walter.\
Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma.\
Ollie is connected to Mercedes, Freda, Bryant.\
Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game.\
Jennie is connected to Levi, John, Freda, Robin.\
Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms.\
Robin is connected to Ollie.\
Robin likes to play Call of Arms, Dwarves and Swords.\
Freda is connected to Olive, John, Debra.\
Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures."def create_data_structure(string_input):
for x in string_input:
    if not ((ord(x)>60 and ord(x)<90) or x=="." or (ord(x)>97 and ord(x)<122)):
    string_input=string_input[:string_input.index(x)]+string_input[string_input.index(x):]
    network={}
    before=0
    string_input2=string_input
    while y < string_input.count('.')+1:
        network[y]=string_input2(0:before)
        string_input2=string_input2(:before-1)
        before=string_input2.find('.')
    return network,len(string_input),string_input
</code>```

When I run the code the editor gives an error
message saying that the slicing is not working.

```<code>Traceback (most recent call last):
  File "vm_main.py", line 33, in <module>
    import main
  File "/tmp/vmuser_igvmlwmdgu/main.py", line 2, in <module>
    import studentMain
  File "/tmp/vmuser_igvmlwmdgu/studentMain.py", line 103
    network[y]=string_input2(0:11)
                              ^
SyntaxError: invalid syntax
</code>```

Could someone please tell me what is going wrong?

答:
Syntax to slice the string/list/tuple in Python is [:] and not (:) i.e usage of brackets instead of parenthesis. Try:

```<code>string_input2[0:11]
</code>```

For example:

```<code>>>> my_string = 'StackOverflow'
>>> my_string[5:9]
'Over'
</code>```

Body:
I wrote this function in a challange using python for udacity:

example_input="John is connected to Bryant, Debra, Walter.\
John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\
Bryant is connected to Olive, Ollie, Freda, Mercedes.\
Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man.\
Mercedes is connected to Walter, Robin, Bryant.\
Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures.\
Olive is connected to John, Ollie.\
Olive likes to play The Legend of Corgi, Starfleet Commander.\
Debra is connected to Walter, Levi, Jennie, Robin.\
Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords.\
Walter is connected to John, Levi, Bryant.\
Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man.\
Levi is connected to Ollie, John, Walter.\
Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma.\
Ollie is connected to Mercedes, Freda, Bryant.\
Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game.\
Jennie is connected to Levi, John, Freda, Robin.\
Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms.\
Robin is connected to Ollie.\
Robin likes to play Call of Arms, Dwarves and Swords.\
Freda is connected to Olive, John, Debra.\
Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures."def create_data_structure(string_input):
for x in string_input:
    if not ((ord(x)>60 and ord(x)<90) or x=="." or (ord(x)>97 and ord(x)<122)):
    string_input=string_input[:string_input.index(x)]+string_input[string_input.index(x):]
    network={}
    before=0
    string_input2=string_input
    while y < string_input.count('.')+1:
        network[y]=string_input2(0:before)
        string_input2=string_input2(:before-1)
        before=string_input2.find('.')
    return network,len(string_input),string_input

When I run the code the editor gives an error
message saying that the slicing is not working.

Traceback (most recent call last):
  File "vm_main.py", line 33, in <module>
    import main
  File "/tmp/vmuser_igvmlwmdgu/main.py", line 2, in <module>
    import studentMain
  File "/tmp/vmuser_igvmlwmdgu/studentMain.py", line 103
    network[y]=string_input2(0:11)
                              ^
SyntaxError: invalid syntax

Could someone please tell me what is going wrong?

Body:
Syntax to slice the string/list/tuple in Python is [:] and not (:) i.e usage of brackets instead of parenthesis. Try:

string_input2[0:11]

For example:

>>> my_string = 'StackOverflow'
>>> my_string[5:9]
'Over'


问:
ForEach Loop, Execute Command for Each Randomly Named Image
I'm using Movie Maker Timeline Control in C# to try and randomize the order of pictures in Windows Movie Maker. I have the form set up, but I seem to encounter a problem with the importing of photos. My code needs to be able to import multiple randomly named images (ex: IMG_xxxx.JPG). I'm able to individually import a specifically named image, but when I try to use a foreach loop, it fails.

My code:

```<code>private void btnOpen_Click(object sender, EventArgs e)
        {

            openFolder.Description = "Open a folder containing pictures for the slideshow!";

            if (openFolder.ShowDialog() == DialogResult.OK)
            {
                // this code right here
                string folderPath = openFolder.SelectedPath;

                string[] fileArray = Directory.GetFiles(folderPath, "*.JPG");
                foreach (string file in fileArray)
                {
                    folderPath = folderPath + "\\" + file;
                    float duration = 4;
                    float startpos = 0;
                    timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), folderPath, startpos, (startpos + duration));
                    startpos = startpos + 4;
                }

                /* string image = "C:\\Users\\OSR\\Desktop\\jpgs\\img.JPG";
                float duration = 4;
                timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), image, 0, duration);
                */
            }
            else
            {
                MessageBox.Show("Next time, select a folder and click open!", "Selection Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
</code>```

Full code: https://pastebin.com/MrB928Ri

Program: http://imgur.com/a/bikxU

答:
You are destroying the folderPath in the loop:

```<code>var folderPath = openFolder.SelectedPath;

var fileArray = Directory.GetFiles(folderPath, "*.JPG");
float duration = 4;
float startpos = 0;
foreach (var file in fileArray) {
    var filePath = $@"{folderPath}\{file}";
    timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), filePath, startpos, (startpos + duration));
    startpos += 4;
}
</code>```

Body:
I'm using Movie Maker Timeline Control in C# to try and randomize the order of pictures in Windows Movie Maker. I have the form set up, but I seem to encounter a problem with the importing of photos. My code needs to be able to import multiple randomly named images (ex: IMG_xxxx.JPG). I'm able to individually import a specifically named image, but when I try to use a foreach loop, it fails.

My code:

private void btnOpen_Click(object sender, EventArgs e)
        {

            openFolder.Description = "Open a folder containing pictures for the slideshow!";

            if (openFolder.ShowDialog() == DialogResult.OK)
            {
                // this code right here
                string folderPath = openFolder.SelectedPath;

                string[] fileArray = Directory.GetFiles(folderPath, "*.JPG");
                foreach (string file in fileArray)
                {
                    folderPath = folderPath + "\\" + file;
                    float duration = 4;
                    float startpos = 0;
                    timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), folderPath, startpos, (startpos + duration));
                    startpos = startpos + 4;
                }

                /* string image = "C:\\Users\\OSR\\Desktop\\jpgs\\img.JPG";
                float duration = 4;
                timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), image, 0, duration);
                */
            }
            else
            {
                MessageBox.Show("Next time, select a folder and click open!", "Selection Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

Full code: https://pastebin.com/MrB928Ri

Program: http://imgur.com/a/bikxU

Body:
You are destroying the folderPath in the loop:

var folderPath = openFolder.SelectedPath;

var fileArray = Directory.GetFiles(folderPath, "*.JPG");
float duration = 4;
float startpos = 0;
foreach (var file in fileArray) {
    var filePath = $@"{folderPath}\{file}";
    timelineControl.AddImageClip(timelineControl.GetImageTrackIndex(), filePath, startpos, (startpos + duration));
    startpos += 4;
}


问:
How to set a function callback to a private function of a class?
I need to set function as a callback for a function that is provided by an API. Now the API provides an example that allowed me to write this code and it works:
In the header file:

```<code>#include <iostream>

int __stdcall newDataAvailable(SampleStruct datum);
class Interface:

public:

    Interface();

    // Connects to the local server. Returns false if it fails.
    bool connectToServer();

private:

};
</code>```

And in the implementation I have:

```<code>Interface::Interface()
{
    iV_SetSampleCallback(newDataAvailable);
}

bool Interface::connectToServer(){

// code to connect to server
}

int __stdcall newDataAvailable(SampleStruct datum){
    std::cout << "New DATA" << std::endl;
    return 0;
}
</code>```

So, so far so good. Now the problem comes when I want to make the function newDataAvailable part of the class. So I copy the header into the private area of the class declaraion, add an Interface:: in the implemetation cpp file and try agai.

However I do not know how to make the connection, as it fails to compile. This is what I've tried:

```<code>iV_SetSampleCallback(&newDataAvailable); // Gives me illegal & operation
iV_SetSampleCallback(Interface::newDataAvailable);  // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member
iV_SetSampleCallback(&Interface::newDataAvailable); // error: C2664: 'int iV_SetSampleCallback(pDLLSetSample)': cannot convert argument 1 from 'int (__stdcall Interface::* )(SampleStruct)' to 'pDLLSetSample'
iV_SetSampleCallback(newDataAvailable); // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member
</code>```

So what is the proper way to set the callback?

答:
This message:

```<code>iV_SetSampleCallback(&Interface::newDataAvailable); // error: C2664: 'int iV_SetSampleCallback(pDLLSetSample)': cannot convert argument 1 from 'int (__stdcall Interface::* )(SampleStruct)' to 'pDLLSetSample'
</code>```

Says the type is wrong. The syntax is, in fact, 'correct', you're just not doing what you think you were doing. What you were actually doing is pass a pointer to a member function which uses a Interface* as this type, but the API wants pointers to functions (that are not bound to particular object instances) which is why you get the type error instead.

Note that your type brings up this ask: CALLBACK macro (QT)
If that is the case for you as well, it looks like you are going to have to use a global variable (may be dressed up as a singleton) because of piss poor API design on 'their' part.

Body:
I need to set function as a callback for a function that is provided by an API. Now the API provides an example that allowed me to write this code and it works:
In the header file:

#include <iostream>

int __stdcall newDataAvailable(SampleStruct datum);
class Interface:

public:

    Interface();

    // Connects to the local server. Returns false if it fails.
    bool connectToServer();

private:

};

And in the implementation I have:

Interface::Interface()
{
    iV_SetSampleCallback(newDataAvailable);
}

bool Interface::connectToServer(){

// code to connect to server
}

int __stdcall newDataAvailable(SampleStruct datum){
    std::cout << "New DATA" << std::endl;
    return 0;
}

So, so far so good. Now the problem comes when I want to make the function newDataAvailable part of the class. So I copy the header into the private area of the class declaraion, add an Interface:: in the implemetation cpp file and try agai.

However I do not know how to make the connection, as it fails to compile. This is what I've tried:

iV_SetSampleCallback(&newDataAvailable); // Gives me illegal & operation
iV_SetSampleCallback(Interface::newDataAvailable);  // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member
iV_SetSampleCallback(&Interface::newDataAvailable); // error: C2664: 'int iV_SetSampleCallback(pDLLSetSample)': cannot convert argument 1 from 'int (__stdcall Interface::* )(SampleStruct)' to 'pDLLSetSample'
iV_SetSampleCallback(newDataAvailable); // error: C3867: 'Interface::newDataAvailable': non-standard syntax; use '&' to create a pointer to member

So what is the proper way to set the callback?

Body:
This message:

iV_SetSampleCallback(&Interface::newDataAvailable); // error: C2664: 'int iV_SetSampleCallback(pDLLSetSample)': cannot convert argument 1 from 'int (__stdcall Interface::* )(SampleStruct)' to 'pDLLSetSample'

Says the type is wrong. The syntax is, in fact, 'correct', you're just not doing what you think you were doing. What you were actually doing is pass a pointer to a member function which uses a Interface* as this type, but the API wants pointers to functions (that are not bound to particular object instances) which is why you get the type error instead.

Note that your type brings up this ask: CALLBACK macro (QT)
If that is the case for you as well, it looks like you are going to have to use a global variable (may be dressed up as a singleton) because of piss poor API design on 'their' part.


问:
Divide full list to k fold training and testing set?
I currently have a perl script which takes a full file list, and evenly divides the list into a train and test set. I now wants to do k-fold cross validation for which i need to perl script to be adjusted to do so.

But I seem to have a hard time coming up with an simple solution, given the current implementation.

```<code>#!/usr/bin/env perl

$full_list = $ARGV[0];
$test_list = $ARGV[1];
$train_list = $ARGV[2];

open FL, $full_list;
$nol = 0;
while ($l = <FL>)
{
    $nol++;
}
close FL;

$i = 0;
open FL, $full_list;
open TESTLIST, ">$test_list";
open TRAINLIST, ">$train_list";
while ($l = <FL>)
{
    chomp($l);
    $i++;
    if ($i <= $nol/2 )
    {
        print TRAINLIST "$l\n";
    }
    else
    {
        print TESTLIST "$l\n";
    }
}
</code>```

My simple attempt of making it possible to create a k folds is by introducing two new input parameters being part as argv[4] and k argv[3].  So a part of $nol is used to generate the test set and the rest will be the train set.

```<code>#!/usr/bin/env perl

$full_list = $ARGV[0];
$test_list = $ARGV[1];
$train_list = $ARGV[2];
$k = $ARGV[3]
$part_index_end = $ARGV[4]
$part_index_start = $ARGV[4]-1

print "Hi";

open FL, $full_list;
$nol = 0;
while ($l = <FL>)
{
    $nol++;
}
close FL;

$i = 0;
open FL, $full_list;
open TESTLIST, ">$test_list";
open TRAINLIST, ">$train_list";
while ($l = <FL>)
{
    chomp($l);
    $i++;
    if ($i <= ($nol/$k)*$part_index_end $$ $i => ($nol/$k)*$part_index_end )
    {
        print TESTLIST "$l\n";
    }
    else
    {
        print TRAINLIST "$l\n";
    }
}
</code>```

This though requires an other script that call this script with increasing part parameter, such that they also are placed correctly, and don't overwrite the same file.

The outcome of the script should be 3 sets of train/test list.

答:
the solution i ended up using was: </p>

```<code>/* cook your code below */
k=5
for (( j=1; j<k; j++ ))
do
    for (( i=1; i<k; i++ ))
    do

        if [ $i == $j ] && [ $j == $((k-1)) ]
        then
            s+="1"
            #echo "1"
        elif [ $i == $j ]
        then
            s+="1_"
            #echo "1"
        elif [ $i == $((k-1)) ]
        then
            s+="0"
            #echo "0"
        else
            s+="0_"
            #echo "0_"
        fi
    done
    echo $s
    s=""
done
</code>```

Body:
I currently have a perl script which takes a full file list, and evenly divides the list into a train and test set. I now wants to do k-fold cross validation for which i need to perl script to be adjusted to do so.

But I seem to have a hard time coming up with an simple solution, given the current implementation.

#!/usr/bin/env perl

$full_list = $ARGV[0];
$test_list = $ARGV[1];
$train_list = $ARGV[2];

open FL, $full_list;
$nol = 0;
while ($l = <FL>)
{
    $nol++;
}
close FL;

$i = 0;
open FL, $full_list;
open TESTLIST, ">$test_list";
open TRAINLIST, ">$train_list";
while ($l = <FL>)
{
    chomp($l);
    $i++;
    if ($i <= $nol/2 )
    {
        print TRAINLIST "$l\n";
    }
    else
    {
        print TESTLIST "$l\n";
    }
}

My simple attempt of making it possible to create a k folds is by introducing two new input parameters being part as argv[4] and k argv[3].  So a part of $nol is used to generate the test set and the rest will be the train set.

#!/usr/bin/env perl

$full_list = $ARGV[0];
$test_list = $ARGV[1];
$train_list = $ARGV[2];
$k = $ARGV[3]
$part_index_end = $ARGV[4]
$part_index_start = $ARGV[4]-1

print "Hi";

open FL, $full_list;
$nol = 0;
while ($l = <FL>)
{
    $nol++;
}
close FL;

$i = 0;
open FL, $full_list;
open TESTLIST, ">$test_list";
open TRAINLIST, ">$train_list";
while ($l = <FL>)
{
    chomp($l);
    $i++;
    if ($i <= ($nol/$k)*$part_index_end $$ $i => ($nol/$k)*$part_index_end )
    {
        print TESTLIST "$l\n";
    }
    else
    {
        print TRAINLIST "$l\n";
    }
}

This though requires an other script that call this script with increasing part parameter, such that they also are placed correctly, and don't overwrite the same file.

The outcome of the script should be 3 sets of train/test list.

Body:
the solution i ended up using was:

/* cook your code below */
k=5
for (( j=1; j<k; j++ ))
do
    for (( i=1; i<k; i++ ))
    do

        if [ $i == $j ] && [ $j == $((k-1)) ]
        then
            s+="1"
            #echo "1"
        elif [ $i == $j ]
        then
            s+="1_"
            #echo "1"
        elif [ $i == $((k-1)) ]
        then
            s+="0"
            #echo "0"
        else
            s+="0_"
            #echo "0_"
        fi
    done
    echo $s
    s=""
done


问:
Angular 2 : Define global constants for api endpoints
I am  new in Angular2. I would like to have a single class or a configuration file having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS).

The problem that I found is when I will deploy my api on a server in the client part I must change all endpoint called in string format so it will be wasted time if I have many endpoints to work with.

in this example I call a service with an endpoint in string format :

```<code>getData() {
    return this._http.get('http://localhost:8000/cartography')
      .map(function(res) {
        const jsonArray = res.json();
        const newJsonArr = [];
        for ( let i = 0; i < jsonArray.length; i++) {
          const object = {
            post_name : jsonArray[i].name,
            employment_name : jsonArray[i].employment.name,
            profession_name : jsonArray[i].employment.profession.name,
            family_name : jsonArray[i].employment.profession.family.name
          };
          newJsonArr.push(object);
        }
          return newJsonArr;
      });
  }
</code>```

so I'm looking for a way to define it as global var in a class or config file.
any help please ! thanks .

答:
If the question is really how to handle a different endpoint prefix at deployment than at development time ... then the answer is to use the HTML base tag in your index.html like this:

```<code><!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Acme Product Management</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <pm-root></pm-root>
</body>
</html>
</code>```

Then you can simply change this base tag before deploying. If you are using Angular CLI, there is even an option for that.

From the CLI docs:

```<code># Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
ng build --bh /myUrl/
</code>```

If you are really looking for more of a configuration file based approach, check this out: https://github.com/angular/angular/issues/9047#issuecomment-224075188

Body:
I am  new in Angular2. I would like to have a single class or a configuration file having all my API endpoints (allowing parameters and such in the different routes) that I could inject in all my services. What's the best way to do so in Angular2. I mean, should I define an @Injectable class as you would do when defining a service (and then add it to my services'PROVIDERS).

The problem that I found is when I will deploy my api on a server in the client part I must change all endpoint called in string format so it will be wasted time if I have many endpoints to work with.

in this example I call a service with an endpoint in string format :

getData() {
    return this._http.get('http://localhost:8000/cartography')
      .map(function(res) {
        const jsonArray = res.json();
        const newJsonArr = [];
        for ( let i = 0; i < jsonArray.length; i++) {
          const object = {
            post_name : jsonArray[i].name,
            employment_name : jsonArray[i].employment.name,
            profession_name : jsonArray[i].employment.profession.name,
            family_name : jsonArray[i].employment.profession.family.name
          };
          newJsonArr.push(object);
        }
          return newJsonArr;
      });
  }

so I'm looking for a way to define it as global var in a class or config file.
any help please ! thanks .

Body:
If the question is really how to handle a different endpoint prefix at deployment than at development time ... then the answer is to use the HTML base tag in your index.html like this:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Acme Product Management</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <pm-root></pm-root>
</body>
</html>

Then you can simply change this base tag before deploying. If you are using Angular CLI, there is even an option for that.

From the CLI docs:

# Sets base tag href to /myUrl/ in your index.html
ng build --base-href /myUrl/
ng build --bh /myUrl/

If you are really looking for more of a configuration file based approach, check this out: https://github.com/angular/angular/issues/9047#issuecomment-224075188