问:
Why does my batch script output incorrect syntax error message when folder name has spaces?
When running this script the following error message is output:

The syntax of command is incorrect

Folder is on a server and folder name has spaces.

```<code>@echo off

for  %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do (
if not exist
"\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\CSV\%%~nI.csv.completed"
xcopy "\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\%%~nxI" "\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\CSV"/D
)
</code>```

答:
Single line solution:

```<code>@for %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do @if not exist "%%~dpICSV\%%~nxI.completed" %SystemRoot%\System32\xcopy.exe "%%I" "%%~dpICSV\" /C /D /Q /Y >nul 2>&1
</code>```

Multi-line solution:

```<code>@echo off
for %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do (
    if not exist "%%~dpICSV\%%~nxI.completed" (
        %SystemRoot%\System32\xcopy.exe "%%I" "%%~dpICSV\" /C /D /Q /Y >nul 2>&1
    )
)
</code>```

Important here is the backslash at end of destination folder path because this is a clear indication for XCOPY that the target specifies a directory and not a file name. Otherwise XCOPY used here to copy a single file would prompt the user if target specifies a directory or file and waits for the input of the user. For details see batch file asks for file or folder.

For testing purposes with additional debugging information and without suppressing any standard or error output:

```<code>@echo off
for %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do (
    echo CSV file is:  %%I
    if not exist "%%~dpICSV\%%~nxI.completed" (
        echo Not existing: %%~dpICSV\%%~nxI.completed
        %SystemRoot%\System32\xcopy.exe "%%I" "%%~dpICSV\" /C /D /Y
    ) else (
        echo Existing is:  %%~dpICSV\%%~nxI.completed
    )
)
pause
</code>```

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

if /?

xcopy /?

Read also the Microsoft article about Using Command Redirection Operators.

Body:
When running this script the following error message is output:

The syntax of command is incorrect

Folder is on a server and folder name has spaces.

@echo off

for  %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do (
if not exist
"\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\CSV\%%~nI.csv.completed"
xcopy "\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\%%~nxI" "\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\CSV"/D
)

Body:
Single line solution:

@for %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do @if not exist "%%~dpICSV\%%~nxI.completed" %SystemRoot%\System32\xcopy.exe "%%I" "%%~dpICSV\" /C /D /Q /Y >nul 2>&1

Multi-line solution:

@echo off
for %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do (
    if not exist "%%~dpICSV\%%~nxI.completed" (
        %SystemRoot%\System32\xcopy.exe "%%I" "%%~dpICSV\" /C /D /Q /Y >nul 2>&1
    )
)

Important here is the backslash at end of destination folder path because this is a clear indication for XCOPY that the target specifies a directory and not a file name. Otherwise XCOPY used here to copy a single file would prompt the user if target specifies a directory or file and waits for the input of the user. For details see batch file asks for file or folder.

For testing purposes with additional debugging information and without suppressing any standard or error output:

@echo off
for %%I in ("\\path31vm\file transfers\Data Files\Inbound\VMs\su\Reg\new\*.csv") do (
    echo CSV file is:  %%I
    if not exist "%%~dpICSV\%%~nxI.completed" (
        echo Not existing: %%~dpICSV\%%~nxI.completed
        %SystemRoot%\System32\xcopy.exe "%%I" "%%~dpICSV\" /C /D /Y
    ) else (
        echo Existing is:  %%~dpICSV\%%~nxI.completed
    )
)
pause

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

echo /?

for /?

if /?

xcopy /?

Read also the Microsoft article about Using Command Redirection Operators.


来源: stackexchange

问:
copy dynamic ranges from excel to word vba
I have a sheet of data and the range vary each week meaning last used row and last used column vary. I hope to copy 3 ranges at a time and paste it as picture into word using vba. This is part of a larger codes so that is why I am hoping to achieve it by writing vba.

The reason behind 3 ranges at a time is because of the picture size fits best in word. Headers are merged in row 2 and 3. I am showing you 4 ranges but sometimes I get 2 ranges and sometimes 6 ranges. i.e. 3 ranges or below should just be one picture and from 4-6 ranges will mean I have 2 pictures in word.

Right now when I run my codes, nothing is pasted in word.

```<code>Sub Table()

    Dim wdapp As Word.Application
    Set wdapp = New Word.Application

    With wdapp
        .Visible = True
        .Activate
        .Documents.Add
    End With

    With ThisWorkbook.Worksheets("Table")
        Dim a, b, c, RR As Range
  '1
        Set a = .Cells.Find("Header1", LookIn:=xlValues)

        If Not a Is Nothing Then
            Dim firstAddress As String
            firstAddress = a.Address
            Do
' 2
  Set b = .Cells.Find("Header1", a, LookIn:=xlValues)
' 3
  Set c = .Cells.Find("Header1", b, LookIn:=xlValues)
'Union
Set RR = Union(Range(a.End(xlDown).End(xlDown), a.Resize(, 7)), Range(b.End(xlDown).End(xlDown), b.Resize(, 7)), Range(c.End(xlDown).End(xlDown), a.Resize(, 20)))
    RR.CopyPicture Appearance:=xlScreen, Format:=xlPicture
                wdapp.Selection.Paste
                Set a = .UsedRange.FindNext(a)
                If a Is Nothing Then Exit Do
            Loop While a.Address <> firstAddress

        End If
    End With

End Sub
</code>```

答:
There are a few problems here:

Nested Withs are normally a bad plan, and seem to be quite haphazard in this example

Find doesn't like looking in rows that contain part of merged cells, so it's best to just use find on the whole sheet

.End(xlDown) from a merged cell just selects the next used cell beolw it, not the whole block, so we need to apply this twice

Your loop condition will produce an error if d is Nothing, as it still tries to check its address. Check for Nothing first and break out of the loop if needed

All told, this should work I believe:

```<code>Option Explicit

Sub Table()

    Dim wdapp As Word.Application
    Set wdapp = New Word.Application

    With wdapp
        .Visible = True
        .Activate
        .Documents.Add
    End With

    With ThisWorkbook.Worksheets("Table")
        Dim d As Range
        Set d = .Cells.Find("Header1", LookIn:=xlValues)
        If Not d Is Nothing Then
            Dim firstAddress As String
            firstAddress = d.Address
            Do
                .Range(d, d.End(xlDown).End(xlDown).End(xlToRight)).CopyPicture Appearance:=xlScreen, Format:=xlPicture
                wdapp.Selection.Paste
                Set d = .UsedRange.FindNext(d)
                If d Is Nothing Then Exit Do
            Loop While d.Address <> firstAddress
        End If
    End With

End Sub
</code>```

For the specific case of wanting to paste the first three blocks as one picture, and the fourth as a separate picture, you can replace the do loop with:

```<code>    .Range(d, d.End(xlDown).End(xlDown).End(xlToRight).End(xlToRight).End(xlToRight).End(xlToRight).End(xlToRight)).CopyPicture Appearance:=xlScreen, Format:=xlPicture
    wdapp.Selection.Paste
    Dim i As Long
    For i = 1 To 3
        Set d = .UsedRange.FindNext(d)
    Next i
    .Range(d, d.End(xlDown).End(xlDown).End(xlToRight)).CopyPicture Appearance:=xlScreen, Format:=xlPicture
    wdapp.Selection.Paste
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a sheet of data and the range vary each week meaning last used row and last used column vary. I hope to copy 3 ranges at a time and paste it as picture into word using vba. This is part of a larger codes so that is why I am hoping to achieve it by writing vba.

The reason behind 3 ranges at a time is because of the picture size fits best in word. Headers are merged in row 2 and 3. I am showing you 4 ranges but sometimes I get 2 ranges and sometimes 6 ranges. i.e. 3 ranges or below should just be one picture and from 4-6 ranges will mean I have 2 pictures in word.

Right now when I run my codes, nothing is pasted in word.

Sub Table()

    Dim wdapp As Word.Application
    Set wdapp = New Word.Application

    With wdapp
        .Visible = True
        .Activate
        .Documents.Add
    End With

    With ThisWorkbook.Worksheets("Table")
        Dim a, b, c, RR As Range
  '1
        Set a = .Cells.Find("Header1", LookIn:=xlValues)

        If Not a Is Nothing Then
            Dim firstAddress As String
            firstAddress = a.Address
            Do
' 2
  Set b = .Cells.Find("Header1", a, LookIn:=xlValues)
' 3
  Set c = .Cells.Find("Header1", b, LookIn:=xlValues)
'Union
Set RR = Union(Range(a.End(xlDown).End(xlDown), a.Resize(, 7)), Range(b.End(xlDown).End(xlDown), b.Resize(, 7)), Range(c.End(xlDown).End(xlDown), a.Resize(, 20)))
    RR.CopyPicture Appearance:=xlScreen, Format:=xlPicture
                wdapp.Selection.Paste
                Set a = .UsedRange.FindNext(a)
                If a Is Nothing Then Exit Do
            Loop While a.Address <> firstAddress

        End If
    End With

End Sub

Body:
There are a few problems here:

Nested Withs are normally a bad plan, and seem to be quite haphazard in this example

Find doesn't like looking in rows that contain part of merged cells, so it's best to just use find on the whole sheet

.End(xlDown) from a merged cell just selects the next used cell beolw it, not the whole block, so we need to apply this twice

Your loop condition will produce an error if d is Nothing, as it still tries to check its address. Check for Nothing first and break out of the loop if needed

All told, this should work I believe:

Option Explicit

Sub Table()

    Dim wdapp As Word.Application
    Set wdapp = New Word.Application

    With wdapp
        .Visible = True
        .Activate
        .Documents.Add
    End With

    With ThisWorkbook.Worksheets("Table")
        Dim d As Range
        Set d = .Cells.Find("Header1", LookIn:=xlValues)
        If Not d Is Nothing Then
            Dim firstAddress As String
            firstAddress = d.Address
            Do
                .Range(d, d.End(xlDown).End(xlDown).End(xlToRight)).CopyPicture Appearance:=xlScreen, Format:=xlPicture
                wdapp.Selection.Paste
                Set d = .UsedRange.FindNext(d)
                If d Is Nothing Then Exit Do
            Loop While d.Address <> firstAddress
        End If
    End With

End Sub

For the specific case of wanting to paste the first three blocks as one picture, and the fourth as a separate picture, you can replace the do loop with:

    .Range(d, d.End(xlDown).End(xlDown).End(xlToRight).End(xlToRight).End(xlToRight).End(xlToRight).End(xlToRight)).CopyPicture Appearance:=xlScreen, Format:=xlPicture
    wdapp.Selection.Paste
    Dim i As Long
    For i = 1 To 3
        Set d = .UsedRange.FindNext(d)
    Next i
    .Range(d, d.End(xlDown).End(xlDown).End(xlToRight)).CopyPicture Appearance:=xlScreen, Format:=xlPicture
    wdapp.Selection.Paste


问:
which is the best way to check that an array is empty
I am trying to know if an array is empty, as I am still learning to use php I would like to know which is the best way .. now I am doing it this way:</p>

```<code>if (sizeof($myarray) == 0) { }
</code>```

答:
I'd say empty() is the best way:

empty — Determine whether a variable is empty

```<code>if (empty($myarray)) {}
</code>```

Body:
I am trying to know if an array is empty, as I am still learning to use php I would like to know which is the best way .. now I am doing it this way:

if (sizeof($myarray) == 0) { }

Body:
I'd say empty() is the best way:

empty — Determine whether a variable is empty

if (empty($myarray)) {}


问:
Why no Array.prototype.flatMap in javascript?
flatMap is incredibly useful on collections, but javascript does not provide one while having Array.prototype.map. Why?

Is there any way to emulate flatMap in javascript in both easy and efficient way w/o defining flatMap manually?

答:
One fairly concise approach is to make use of the Array#concat.apply:

const flatMap = (arr, f) => [].concat.apply([], arr.map(f))

console.log(flatMap([1, 2, 3], el => [el, el * el]));```


问:
split byte array into even and odd byte array and store in file
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

```<code>        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }
</code>```

In FOR loop i have tried array.length, even.length nothing is working.

答:
If you are just looking for a solution and not necessarily how to fix your code, then the easiest thing is to just use LINQ.

```<code>byte[] array = new byte[]
{
    55, 56, 57, 58, 89, 90, 91, 92
};
var even = array.Where((b, i) => i % 2 == 0);
var odd = array.Except(even);
</code>```

If you need even and odd to be byte[] then just add .ToArray() to each line.

If you want to interleave these values back together then here is an extension method for that (remove static and this if you just want a normal method). I borrowed and modified this question's accepted answer to make it interleave even when one collection is larger than the other.

```<code>public static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
    using (var firstEnumerator = first.GetEnumerator())
    using (var secondEnumerator = second.GetEnumerator())
    {
        var firstMoved = firstEnumerator.MoveNext();
        var secondMoved = secondEnumerator.MoveNext();

        while (firstMoved || secondMoved)
        {
            if (firstMoved)
                yield return firstEnumerator.Current;
            if (secondMoved)
                yield return secondEnumerator.Current;

            firstMoved = firstEnumerator.MoveNext();
            secondMoved = secondEnumerator.MoveNext();
        }
    }
}
</code>```

Body:
I am reading a .pst (File Structure) file byte by byte in a byte array, now i want to break the data into two parts like in even and odd, and store it in 2 other files one for even and one for odd  . Below is the code that i am stuck at

        byte[] array = File.ReadAllBytes("PST_Sample.pst");
        for (int index = 0; index < even.Length; index++)
        {

            //Console.WriteLine(index + " : " + array[index]);
            if ((array[index] % 2) == 0)
            {
                even[index] = array[index];
            }
            else
            {
                odd[index] = array[index];
            }
        }

In FOR loop i have tried array.length, even.length nothing is working.

Body:
If you are just looking for a solution and not necessarily how to fix your code, then the easiest thing is to just use LINQ.

byte[] array = new byte[]
{
    55, 56, 57, 58, 89, 90, 91, 92
};
var even = array.Where((b, i) => i % 2 == 0);
var odd = array.Except(even);

If you need even and odd to be byte[] then just add .ToArray() to each line.

If you want to interleave these values back together then here is an extension method for that (remove static and this if you just want a normal method). I borrowed and modified this question's accepted answer to make it interleave even when one collection is larger than the other.

public static IEnumerable<T> Interleave<T>(this IEnumerable<T> first, IEnumerable<T> second)
{
    using (var firstEnumerator = first.GetEnumerator())
    using (var secondEnumerator = second.GetEnumerator())
    {
        var firstMoved = firstEnumerator.MoveNext();
        var secondMoved = secondEnumerator.MoveNext();

        while (firstMoved || secondMoved)
        {
            if (firstMoved)
                yield return firstEnumerator.Current;
            if (secondMoved)
                yield return secondEnumerator.Current;

            firstMoved = firstEnumerator.MoveNext();
            secondMoved = secondEnumerator.MoveNext();
        }
    }
}


问:
Is it possible remove home button from actionbar
On my main activity, where there is no way to go back, I'd like to remove the app "home" button in the actionbar.

I think it is confusing for the user, who still can quit the app with the OS back button.

Browsing stackoverflow, I saw a whole lot of people asking this, and not a single answer worked for me. Here is the list :

Removing left arrow from the actionbar in android?

To remove the back arrow button from Action Bar

Remove default home/up button in action mode

how to hide up button in actionbar

How to remove v7 toolbar back button

Setting HomeAsUpEnabled(true) but hide back button actionbar

The answers were usually redondant and could be summarized to following :

```<code>ActionBar supportActionBar = getSupportActionBar(); //I target some low API
if(supportActionBar != null) {
    supportActionBar.setDisplayShowHomeEnabled(false);
    supportActionBar.setDisplayHomeAsUpEnabled(false);
    supportActionBar.setHomeButtonEnabled(false);
    supportActionBar.setHomeAsUpIndicator(null);
}
</code>```

I tried every combination of those and nothing worked, whether I try with the default ActionBar or with an XML-declared compat-v7 ToolBar with setSupportActionBar().

I also couldn't see any question adapted for the now recommanded App Bar, and an answer with it would be even greater.

Here is my activity manifest :

```<code><activity
    android:name=".activity.WelcomeActivity"
    android:logo="@drawable/ic_launcher"
    android:label="@string/long_app_name"
    android:launchMode="singleTop"/>
</code>```

So, is it even possible to remove this annoying useless arrow nowadays ?

答:
Create a new style in styles.xml:

```<code> <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
</code>```

Set this style to your activity in Manifest file. To add the Toolbar, add this to your layout file:

```<code><android.support.v7.widget.Toolbar
        android:background="@color/colorPrimary"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.Toolbar>
</code>```

and then in your Java class:

```<code>Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
</code>```

This will remove the top left arrow.

Body:
On my main activity, where there is no way to go back, I'd like to remove the app "home" button in the actionbar.

I think it is confusing for the user, who still can quit the app with the OS back button.

Browsing stackoverflow, I saw a whole lot of people asking this, and not a single answer worked for me. Here is the list :

Removing left arrow from the actionbar in android?

To remove the back arrow button from Action Bar

Remove default home/up button in action mode

how to hide up button in actionbar

How to remove v7 toolbar back button

Setting HomeAsUpEnabled(true) but hide back button actionbar

The answers were usually redondant and could be summarized to following :

ActionBar supportActionBar = getSupportActionBar(); //I target some low API
if(supportActionBar != null) {
    supportActionBar.setDisplayShowHomeEnabled(false);
    supportActionBar.setDisplayHomeAsUpEnabled(false);
    supportActionBar.setHomeButtonEnabled(false);
    supportActionBar.setHomeAsUpIndicator(null);
}

I tried every combination of those and nothing worked, whether I try with the default ActionBar or with an XML-declared compat-v7 ToolBar with setSupportActionBar().

I also couldn't see any question adapted for the now recommanded App Bar, and an answer with it would be even greater.

Here is my activity manifest :

<activity
    android:name=".activity.WelcomeActivity"
    android:logo="@drawable/ic_launcher"
    android:label="@string/long_app_name"
    android:launchMode="singleTop"/>

So, is it even possible to remove this annoying useless arrow nowadays ?

Body:
Create a new style in styles.xml:

 <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

Set this style to your activity in Manifest file. To add the Toolbar, add this to your layout file:

<android.support.v7.widget.Toolbar
        android:background="@color/colorPrimary"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.Toolbar>

and then in your Java class:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

This will remove the top left arrow.


问:
javascript - what is the effect of applying prototype to functions that are not constructors?
So, I know how to apply the prototype property to modify constructors that will effectively affect instances. Theoretically, the prototype should work on a normal function as well (though not necessarily have an effect if it's not a prototype of a certain instance). So I tried the code (createNewFunction is a normal function that's not a constructor)(full code is at the end)

```<code>createNewPerson.prototype.xx = (function() { //alerts hello
            alert("hello");
        })();
</code>```

I'm wondering what this actually does as to how xx is appended to the function. Is it stored as variable xx that is equal to the anon function? Or is stored as this.xx = function? How will this compare to storing the following code:

```<code>createNewPerson.xx = (function() { //alerts hello
        alert("hello");
    })();
</code>```

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

```<code>createNewPerson.mm = 3;
</code>```

Full code for reference:

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //does nothing when i tested it

createNewPerson.xx = (function() { //alerts hello
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //alerts hello
  alert("hello");
})();
var salva = createNewPerson('Salva');```

答:
It seems like you may be looking for js constructor syntax; not just property assignment to a function.

//function with a property
function foo(){

}
foo.prop = true;
alert(foo.prop);

//maybe you want a constructor?
function constructor(id) {
    this.id = id;
}
var thing = new constructor(32);
alert(thing.id);```

Body:
So, I know how to apply the prototype property to modify constructors that will effectively affect instances. Theoretically, the prototype should work on a normal function as well (though not necessarily have an effect if it's not a prototype of a certain instance). So I tried the code (createNewFunction is a normal function that's not a constructor)(full code is at the end)

createNewPerson.prototype.xx = (function() { //alerts hello
            alert("hello");
        })();

I'm wondering what this actually does as to how xx is appended to the function. Is it stored as variable xx that is equal to the anon function? Or is stored as this.xx = function? How will this compare to storing the following code:

createNewPerson.xx = (function() { //alerts hello
        alert("hello");
    })();

This also makes me wonder as to how this this line will be stored(As in if it will be stored as var mm = 3, or it won't append at all?):

createNewPerson.mm = 3;

Full code for reference:

function createNewPerson(name) {
  var obj = {};
  obj.name = name;
  obj.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
  return obj;
}

createNewPerson.mm = 3; //does nothing when i tested it

createNewPerson.xx = (function() { //alerts hello
  alert("hello");
})();
createNewPerson.prototype.xx = (function() { //alerts hello
  alert("hello");
})();
var salva = createNewPerson('Salva');


问:
webpage only visible locally
```<code>en1 (local machine):  192.168.1.5 /24
vboxnet0: 192.168.99.1 /24
docker-machine ip: 192.168.99.100
docker daemon: tcp://192.168.99.100:2376
docker0 (bridge): 172.17.0.1
</code>```

then i run the container:

```<code>docker run -p 5000:5000 friendlyhello &
container's ip: 172.17.0.2/16
</code>```

But I can only see the webpage running at 192.168.99.100:5000, and only on my local machine, not from any other machine connected to the LAN.  Additionally, the web-app friendlyhello is using the microframework Flask to serve pages.

How can I view the webapp from a browser on another machine on the LAN or Internet?

答:
Your container is running inside the VM created by docker-machine and although you've published port 5000 for your container, the ports on your docker-machine are not directly accesible from the rest of the LAN. You must forward port 5000 (or any other port that you prefer) in your localhost to port 5000 in the VM in order to get the traffic from the rest of the LAN.

As suggested in this answered question you should use something like this:

```<code>docker-machine ssh default -L 5000:localhost:5000
</code>```

Title: webpage only visible locally

Body:
en1 (local machine):  192.168.1.5 /24
vboxnet0: 192.168.99.1 /24
docker-machine ip: 192.168.99.100
docker daemon: tcp://192.168.99.100:2376
docker0 (bridge): 172.17.0.1

then i run the container:

docker run -p 5000:5000 friendlyhello &
container's ip: 172.17.0.2/16

But I can only see the webpage running at 192.168.99.100:5000, and only on my local machine, not from any other machine connected to the LAN.  Additionally, the web-app friendlyhello is using the microframework Flask to serve pages.

How can I view the webapp from a browser on another machine on the LAN or Internet?

Body:
Your container is running inside the VM created by docker-machine and although you've published port 5000 for your container, the ports on your docker-machine are not directly accesible from the rest of the LAN. You must forward port 5000 (or any other port that you prefer) in your localhost to port 5000 in the VM in order to get the traffic from the rest of the LAN.

As suggested in this answered question you should use something like this:

docker-machine ssh default -L 5000:localhost:5000


问:
Removing substrings with static part ending with a special char
I am at wit's end as to why this does not work. I tested it on node trying to remove all instances of RADAL followed with any non-whitespace characters ending with ^ with a space.

```<code>txt = "RADALL^follow up blah blah- Pt continues on ~RADALL4^ test it now";
txt = txt.replace(/RADAL.\^/g, " ");
</code>```

It returns:

```<code> follow up blah blah- Pt continues on ~RADALL4^ test it now
</code>```

I have also looped while txt.search("RADAL") > -1 followed by the txt.replace(...)

It still only removes the first and loops forever since the second is not removed.

Any help would be greatly appreciated!

答:
Your regex matches RADAL, then any char other than a line break char (with .), and then a ^ char (with \^).

The string you match against contains RADALL, a 6-letter word, the . matches the last L and as there is no ^ after the second L, the second expected match does not occur.

According to your specs, the string you need to match is RADAL, then any 1 or more chars other than whitespace, and then a caret, thus, you need to use

```<code>/RADAL\S*\^/g
</code>```

See the regex demo.

JS demo:

txt = "RADALL^follow up blah blah- Pt continues on ~RADALL4^ test it now";
txt = txt.replace(/RADAL\S*\^/g, " ");
console.log(txt); // =>  follow up blah blah- Pt continues on ~  test it now```

Body:
I am at wit's end as to why this does not work. I tested it on node trying to remove all instances of RADAL followed with any non-whitespace characters ending with ^ with a space.

txt = "RADALL^follow up blah blah- Pt continues on ~RADALL4^ test it now";
txt = txt.replace(/RADAL.\^/g, " ");

It returns:

 follow up blah blah- Pt continues on ~RADALL4^ test it now

I have also looped while txt.search("RADAL") > -1 followed by the txt.replace(...)

It still only removes the first and loops forever since the second is not removed.

Any help would be greatly appreciated!

Body:
Your regex matches RADAL, then any char other than a line break char (with .), and then a ^ char (with \^).

The string you match against contains RADALL, a 6-letter word, the . matches the last L and as there is no ^ after the second L, the second expected match does not occur.

According to your specs, the string you need to match is RADAL, then any 1 or more chars other than whitespace, and then a caret, thus, you need to use

/RADAL\S*\^/g

See the regex demo.

JS demo:

txt = "RADALL^follow up blah blah- Pt continues on ~RADALL4^ test it now";
txt = txt.replace(/RADAL\S*\^/g, " ");
console.log(txt); // =>  follow up blah blah- Pt continues on ~  test it now


问:
Python Unit Testing using Doctest not working as expected
I have created a python module to generate weather data(Latitude, Longitude, Elevation and other details) by taking particular location as input.

Updated it as per standards and "pycodestyle" package for checking PEP8 standards does not throw any error or warnings.

My Code is given below :

```<code>def fetch_location_info(input_list, err_file):

    # URL which gives us Latitude, Longitude values
    LatLong_URL = (
     'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
     )

    # URL which gives us Elevation values
    Elevation_URL = (
     'https://maps.googleapis.com/maps/api/elevation/json?locations='
     )

    # Initializing Error Logs with relevant title for writing error records
    err_line_header = "Logging Location Data Errors"
    print(err_line_header, file=err_file)

    # Insert a new line in the error file after the Error Header
    print("\n", file=err_file)

    # Fetch and Extract Location details from google maps
    input_info = []

    for location in input_list:
        temp_info = {'Location': location}
        latlong_response = requests.get(LatLong_URL + location).json()

        if latlong_response.get('results'):
            for latlong_results in latlong_response.get('results'):
                latlong = (
                    latlong_results
                    .get('geometry', '0')
                    .get('location', '0')
                    )

                temp_info['Latitude'] = latlong.get('lat', '0')
                temp_info['Longitude'] = latlong.get('lng', '0')

                elevation_response = requests.get(
                    Elevation_URL
                    + str(temp_info['Latitude'])
                    + ','
                    + str(temp_info['Longitude'])
                    ).json()

                if elevation_response.get('results'):
                    for elevation_results in elevation_response.get('results'):
                        temp_info['Elevation'] = (
                            elevation_results.get('elevation', '0'))

                        input_info.append(temp_info)
                        break
                else:
                    print("Elevation_URL is not fetching values for {}"
                          .format(location),
                          file=err_file
                          )
                break
        else:
            print("LatLong_URL is not fetching values for {}"
                  .format(location),
                  file=err_file
                  )

    print("\n", file=err_file)
    return input_info
</code>```

Now as a next step, I am trying to do Unit Testing using doctest. I chose to keep the test cases in a separate file. So I created the following .txt file and kept in the same directory as the code.

```<code>This is a doctest based regression suite for Test_Weather.py
Each '>>' line is run as if in a python shell, and counts as a test.
The next line, if not '>>' is the expected output of the previous line.
If anything doesn't match exactly (including trailing spaces), the test fails.

>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
print(input_info)
</code>```

As seen above, the expected condition should return the contents of the list / dataframe / variable that is created within the function being tested. For a try I just tried to print the contents of the list but my unit test output throws error like below since the expected value and got value is not matching :

PS C:\Users\JKC> python -m doctest testcases.txt
    **********************************************************************  File "testcases.txt", line 7, in testcases.txt Failed example:
        fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))

Expected:

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

Got:

```<code>[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151. 2092955, 'Elevation': 24.5399284362793}]
</code>```

So here as you can see that the Test Case worked fine but since I am not able to print the contents of the list, it is failing the test case.

My question is How can I display the contents of list in the expected section of the unit test case ?

If I am not wrong, do I need to literally mention the output value in the expected section of the unit test case ?

Any inputs will be helpful

答:
You need to have the doctest look exactly as if you ran it at the Python REPL:</p>

```<code>>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151.2092955, 'Elevation': 24.5399284362793}]
</code>```

Body:
I have created a python module to generate weather data(Latitude, Longitude, Elevation and other details) by taking particular location as input.

Updated it as per standards and "pycodestyle" package for checking PEP8 standards does not throw any error or warnings.

My Code is given below :

def fetch_location_info(input_list, err_file):

    # URL which gives us Latitude, Longitude values
    LatLong_URL = (
     'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
     )

    # URL which gives us Elevation values
    Elevation_URL = (
     'https://maps.googleapis.com/maps/api/elevation/json?locations='
     )

    # Initializing Error Logs with relevant title for writing error records
    err_line_header = "Logging Location Data Errors"
    print(err_line_header, file=err_file)

    # Insert a new line in the error file after the Error Header
    print("\n", file=err_file)

    # Fetch and Extract Location details from google maps
    input_info = []

    for location in input_list:
        temp_info = {'Location': location}
        latlong_response = requests.get(LatLong_URL + location).json()

        if latlong_response.get('results'):
            for latlong_results in latlong_response.get('results'):
                latlong = (
                    latlong_results
                    .get('geometry', '0')
                    .get('location', '0')
                    )

                temp_info['Latitude'] = latlong.get('lat', '0')
                temp_info['Longitude'] = latlong.get('lng', '0')

                elevation_response = requests.get(
                    Elevation_URL
                    + str(temp_info['Latitude'])
                    + ','
                    + str(temp_info['Longitude'])
                    ).json()

                if elevation_response.get('results'):
                    for elevation_results in elevation_response.get('results'):
                        temp_info['Elevation'] = (
                            elevation_results.get('elevation', '0'))

                        input_info.append(temp_info)
                        break
                else:
                    print("Elevation_URL is not fetching values for {}"
                          .format(location),
                          file=err_file
                          )
                break
        else:
            print("LatLong_URL is not fetching values for {}"
                  .format(location),
                  file=err_file
                  )

    print("\n", file=err_file)
    return input_info

Now as a next step, I am trying to do Unit Testing using doctest. I chose to keep the test cases in a separate file. So I created the following .txt file and kept in the same directory as the code.

This is a doctest based regression suite for Test_Weather.py
Each '>>' line is run as if in a python shell, and counts as a test.
The next line, if not '>>' is the expected output of the previous line.
If anything doesn't match exactly (including trailing spaces), the test fails.

>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
print(input_info)

As seen above, the expected condition should return the contents of the list / dataframe / variable that is created within the function being tested. For a try I just tried to print the contents of the list but my unit test output throws error like below since the expected value and got value is not matching :

PS C:\Users\JKC> python -m doctest testcases.txt
    **********************************************************************  File "testcases.txt", line 7, in testcases.txt Failed example:
        fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))

Expected:

print(input_info)

Got:

[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151. 2092955, 'Elevation': 24.5399284362793}]

So here as you can see that the Test Case worked fine but since I am not able to print the contents of the list, it is failing the test case.

My question is How can I display the contents of list in the expected section of the unit test case ?

If I am not wrong, do I need to literally mention the output value in the expected section of the unit test case ?

Any inputs will be helpful

Body:
You need to have the doctest look exactly as if you ran it at the Python REPL:

>>> from Test_Weather import fetch_location_info
>>> fetch_location_info(["Sydney,Australia"], open('data/error_log.txt', 'w'))
[{'Location': 'Sydney,Australia', 'Latitude': -33.8688197, 'Longitude': 151.2092955, 'Elevation': 24.5399284362793}]


问:
How can I exit a ruby program on strg-c if a SystemExit exception is being catched
The code which I can not interrupt by using strg-c (Ctrl-C) :

```<code>orig_std_out = STDOUT.clone
orig_std_err = STDERR.clone
STDOUT.reopen('/dev/null', 'w')
STDERR.reopen('/dev/null', 'w')

name = cookbook_name(File.join(path, 'Metadata.rb'))
error = 0

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit
  error = 1
end
.
.
.
</code>```

In my understanding this behaviour would be reasonable if I would rescue Exception, but in this case I am basically catching siblings which only share their parent exception Exception.

I have already tried to rescue the exception Interrupt and SignalException explicitly.

EDIT1: In the hope of clarifying my question I added the following code which i tried:

```<code>begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit => e
  msg1 = e.message
  error = 1
rescue Interrupt
  msg2 = "interrupted"
end
</code>```

In both cases - SystemExit thrown by Knife.run and thrown by Ctrl-C - e.message returns "exit". This does not only mean, that Ctrl-C throws a SystemExit whereas I am expecting it to throw an Interrupt, but also that the error message is the same.
I guess that I have got a major misunderstanding in how ruby works there, since I am not very familiar with ruby.

EDIT2: Further testing revealed that some Ctrl-C interrupts are rescued by rescue Interrupt. Is it possible that the command ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"]), which takes about 3-5 seconds to run, creates some kind of subprocess which responds to a Ctrl-C, but always closes with a SystemExit and that rescue Interruptonly works when it is interrupted just the moment this subprocess is not running? If this is the case, how am I going to be able to Interrupt the whole program?

EDIT3: I initially wanted to attach all the methods which get called on calling Knife.run, however, this would have been too many LoC, although I think my guess that a subcommand is executed was right. The chef gem code can be found here. Thus, the following excerpt is only the part which is the problematic one in my opinion:

```<code> rescue Exception => e
  raise if raise_exception || Chef::Config[:verbosity] == 2
  humanize_exception(e)
  exit 100
end
</code>```

Which leads to the question: How can I catch a Ctrl-C which is already rescued by a subcommand?

答:
I have done gem install chef. Now I try another solution, replacing only run_with_pretty_exceptions, but don't know which require to put in the script. I did this :

```<code>require 'chef'
$:.unshift('Users/b/.rvm/gems/ruby-2.3.3/gems/chef-13-6-4/lib')
require 'chef/knife'
</code>```

But then :

```<code>$ ruby chef_knife.rb
WARNING: No knife configuration file found
ERROR: Error connecting to https://supermarket.chef.io/api/v1/cookbooks/xyz, retry 1/5
...
</code>```

So, without the whole infrastructure, I can't test the following solution. The idea is that in Ruby you can reopen an existing class and replace a method defined elsewhere. I have to leave you check it :

```<code># necessary require of chef and knife ...

class Chef::Knife # reopen the Knife class and replace this method
    def run_with_pretty_exceptions(raise_exception = false)
      unless respond_to?(:run)
        ui.error "You need to add a #run method to your knife command before you can use it"
      end
      enforce_path_sanity
      maybe_setup_fips
      Chef::LocalMode.with_server_connectivity do
        run
      end
    rescue Exception => e
      raise if e.class == Interrupt # <---------- added ********************
      raise if raise_exception || Chef::Config[:verbosity] == 2
      humanize_exception(e)
      exit 100
    end
end

name = cookbook_name(File.join(path, 'Metadata.rb'))
error = 0

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit => e
  puts "in rescue SystemExit e=#{e.inspect}"
  error = 1
rescue Interrupt
  puts 'in rescue Interrupt'
end
</code>```

raise if e.class == Interrupt will re-raise Interrupt if it is one.

Normally I run ruby -w to display diagnostics, which would be like this :

```<code>$ ruby -w ck.rb
ck.rb:9: warning: method redefined; discarding old run_with_pretty_exceptions
ck.rb:4: warning: previous definition of run_with_pretty_exceptions was here
</code>```

Unfortunately there are so many uninitialized variables and circular require warnings in this gem that this option produces un unmanageable output.

The drawback of this solution is that you have to keep a documentation track of this change, and in case of Chef's release change, somebody has to verify if the code of run_with_pretty_exceptions has changed.

Please give me a feedback.

=====  UPDATE  =====

There is a less intrusive solution, which consists in defining an exit method in Chef::Knife.

When you see exit 100, i.e. a message without receiver, the implicit receiver is self, it is equivalent to self.exit 100. In our case, self is the object created by instance = subcommand_class.new(args), and which is the receiver in instance.run_with_pretty_exceptions.

When a message is sent to an object, the message search mechanism starts looking in the class of this object. If there is no method with this name in the class, the search mechanism looks in included modules, then the superclass, etc until it reaches Object, the default superclass of Chef::Knife. Here it finds Object#exit and executes it.

After defining an exit method in Chef::Knife, the message search mechanism, when it encounters exit 100 with an instance of Chef::Knife as implicit receiver, will first find this local method and execute it. By previously aliasing the original Object#exit, it is still possible to call the original Ruby method which initiates the termination of the Ruby script. This way the local exit method can decide either to call the original Object#exit or take other action.

Following is a complete example which demonstrates how it works.

```<code># ***** Emulation of the gem *****

class Chef end

class Chef::Knife
    def self.run(x)
        puts 'in original run'
        self.new.run_with_pretty_exceptions
    end

    def run_with_pretty_exceptions
        print 'Press Ctrl_C > '
        gets
        rescue Exception => e
            puts
            puts "in run_with_pretty...'s Exception e=#{e.inspect} #{e.class}"
            raise if false # if raise_exception || Chef::Config[:verbosity] == 2
#            humanize_exception(e)
            puts "now $!=#{$!.inspect}"
            puts "about to exit,                     self=#{self}"
            exit 100
    end
end

# ***** End of gem emulation *****

#----------------------------------------------------------------------

# ***** This is what you put into your script. *****

class Chef::Knife # reopen the Knife class and define one's own exit
    alias_method :object_exit, :exit

    def exit(p)
        puts "in my own exit with parameter #{p}, self=#{self}"
        puts "$!=#{$!.inspect}"

        if Interrupt === $!
            puts 'then about to raise Interrupt'
            raise # re-raise Interrupt
        else
            puts 'else about to call Object#exit'
            object_exit(p)
        end
    end
end

begin
  ::Chef::Knife.run([])
rescue SystemExit => e
  puts "in script's rescue SystemExit e=#{e.inspect}"
rescue Interrupt
  puts "in script's rescue Interrupt"
end
</code>```

Execution. First test with Ctrl-C :

```<code>$ ruby -w simul_chef.rb
in original run
Press Ctrl_C > ^C
in run_with_pretty...'s Exception e=Interrupt Interrupt
now $!=Interrupt
about to exit,                     self=#<Chef::Knife:0x007fb2361c7038>
in my own exit with parameter 100, self=#<Chef::Knife:0x007fb2361c7038>
$!=Interrupt
then about to raise Interrupt
in script's rescue Interrupt
</code>```

Second test with a hard interrupt.

In one terminal window :

```<code>$ ruby -w simul_chef.rb
in original run
Press Ctrl_C >
</code>```

In another terminal window :

```<code>$ ps -ef
  UID   PID  PPID   C STIME   TTY           TIME CMD
    0     1     0   0 Fri01PM ??         0:52.65 /sbin/launchd
...
    0   363   282   0 Fri01PM ttys000    0:00.02 login -pfl b /bin/bash -c exec -la bash /bin/bash
  501   364   363   0 Fri01PM ttys000    0:00.95 -bash
  501  3175   364   0  9:51PM ttys000    0:00.06 ruby -w simul_chef.rb
...
$ kill 3175
</code>```

Back in the first terminal :

```<code>in run_with_pretty...'s Exception e=#<SignalException: SIGTERM> SignalException
now $!=#<SignalException: SIGTERM>
about to exit,                     self=#<Chef::Knife:0x007fc5a79d70a0>
in my own exit with parameter 100, self=#<Chef::Knife:0x007fc5a79d70a0>
$!=#<SignalException: SIGTERM>
else about to call Object#exit
in script's rescue SystemExit e=#<SystemExit: exit>
</code>```

Considering the code you originally posted, all you have to do is inserting at the beginning, but after the necessary require :

```<code>class Chef::Knife # reopen the Knife class and define one's own exit
    alias_method :object_exit, :exit

    def exit(p)
        if Interrupt === $!
            raise # re-raise Interrupt
        else
            object_exit(p)
        end
    end
end
</code>```

So there is no need to touch the original gem.

Body:
The code which I can not interrupt by using strg-c (Ctrl-C) :

orig_std_out = STDOUT.clone
orig_std_err = STDERR.clone
STDOUT.reopen('/dev/null', 'w')
STDERR.reopen('/dev/null', 'w')

name = cookbook_name(File.join(path, 'Metadata.rb'))
error = 0

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit
  error = 1
end
.
.
.

In my understanding this behaviour would be reasonable if I would rescue Exception, but in this case I am basically catching siblings which only share their parent exception Exception.

I have already tried to rescue the exception Interrupt and SignalException explicitly.

EDIT1: In the hope of clarifying my question I added the following code which i tried:

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit => e
  msg1 = e.message
  error = 1
rescue Interrupt
  msg2 = "interrupted"
end

In both cases - SystemExit thrown by Knife.run and thrown by Ctrl-C - e.message returns "exit". This does not only mean, that Ctrl-C throws a SystemExit whereas I am expecting it to throw an Interrupt, but also that the error message is the same.
I guess that I have got a major misunderstanding in how ruby works there, since I am not very familiar with ruby.

EDIT2: Further testing revealed that some Ctrl-C interrupts are rescued by rescue Interrupt. Is it possible that the command ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"]), which takes about 3-5 seconds to run, creates some kind of subprocess which responds to a Ctrl-C, but always closes with a SystemExit and that rescue Interruptonly works when it is interrupted just the moment this subprocess is not running? If this is the case, how am I going to be able to Interrupt the whole program?

EDIT3: I initially wanted to attach all the methods which get called on calling Knife.run, however, this would have been too many LoC, although I think my guess that a subcommand is executed was right. The chef gem code can be found here. Thus, the following excerpt is only the part which is the problematic one in my opinion:

 rescue Exception => e
  raise if raise_exception || Chef::Config[:verbosity] == 2
  humanize_exception(e)
  exit 100
end

Which leads to the question: How can I catch a Ctrl-C which is already rescued by a subcommand?

Body:
I have done gem install chef. Now I try another solution, replacing only run_with_pretty_exceptions, but don't know which require to put in the script. I did this :

require 'chef'
$:.unshift('Users/b/.rvm/gems/ruby-2.3.3/gems/chef-13-6-4/lib')
require 'chef/knife'

But then :

$ ruby chef_knife.rb
WARNING: No knife configuration file found
ERROR: Error connecting to https://supermarket.chef.io/api/v1/cookbooks/xyz, retry 1/5
...

So, without the whole infrastructure, I can't test the following solution. The idea is that in Ruby you can reopen an existing class and replace a method defined elsewhere. I have to leave you check it :

# necessary require of chef and knife ...

class Chef::Knife # reopen the Knife class and replace this method
    def run_with_pretty_exceptions(raise_exception = false)
      unless respond_to?(:run)
        ui.error "You need to add a #run method to your knife command before you can use it"
      end
      enforce_path_sanity
      maybe_setup_fips
      Chef::LocalMode.with_server_connectivity do
        run
      end
    rescue Exception => e
      raise if e.class == Interrupt # <---------- added ********************
      raise if raise_exception || Chef::Config[:verbosity] == 2
      humanize_exception(e)
      exit 100
    end
end

name = cookbook_name(File.join(path, 'Metadata.rb'))
error = 0

begin
  ::Chef::Knife.run(['cookbook', 'site', 'show', "#{name}"])
rescue SystemExit => e
  puts "in rescue SystemExit e=#{e.inspect}"
  error = 1
rescue Interrupt
  puts 'in rescue Interrupt'
end

raise if e.class == Interrupt will re-raise Interrupt if it is one.

Normally I run ruby -w to display diagnostics, which would be like this :

$ ruby -w ck.rb
ck.rb:9: warning: method redefined; discarding old run_with_pretty_exceptions
ck.rb:4: warning: previous definition of run_with_pretty_exceptions was here

Unfortunately there are so many uninitialized variables and circular require warnings in this gem that this option produces un unmanageable output.

The drawback of this solution is that you have to keep a documentation track of this change, and in case of Chef's release change, somebody has to verify if the code of run_with_pretty_exceptions has changed.

Please give me a feedback.

=====  UPDATE  =====

There is a less intrusive solution, which consists in defining an exit method in Chef::Knife.

When you see exit 100, i.e. a message without receiver, the implicit receiver is self, it is equivalent to self.exit 100. In our case, self is the object created by instance = subcommand_class.new(args), and which is the receiver in instance.run_with_pretty_exceptions.

When a message is sent to an object, the message search mechanism starts looking in the class of this object. If there is no method with this name in the class, the search mechanism looks in included modules, then the superclass, etc until it reaches Object, the default superclass of Chef::Knife. Here it finds Object#exit and executes it.

After defining an exit method in Chef::Knife, the message search mechanism, when it encounters exit 100 with an instance of Chef::Knife as implicit receiver, will first find this local method and execute it. By previously aliasing the original Object#exit, it is still possible to call the original Ruby method which initiates the termination of the Ruby script. This way the local exit method can decide either to call the original Object#exit or take other action.

Following is a complete example which demonstrates how it works.

# ***** Emulation of the gem *****

class Chef end

class Chef::Knife
    def self.run(x)
        puts 'in original run'
        self.new.run_with_pretty_exceptions
    end

    def run_with_pretty_exceptions
        print 'Press Ctrl_C > '
        gets
        rescue Exception => e
            puts
            puts "in run_with_pretty...'s Exception e=#{e.inspect} #{e.class}"
            raise if false # if raise_exception || Chef::Config[:verbosity] == 2
#            humanize_exception(e)
            puts "now $!=#{$!.inspect}"
            puts "about to exit,                     self=#{self}"
            exit 100
    end
end

# ***** End of gem emulation *****

#----------------------------------------------------------------------

# ***** This is what you put into your script. *****

class Chef::Knife # reopen the Knife class and define one's own exit
    alias_method :object_exit, :exit

    def exit(p)
        puts "in my own exit with parameter #{p}, self=#{self}"
        puts "$!=#{$!.inspect}"

        if Interrupt === $!
            puts 'then about to raise Interrupt'
            raise # re-raise Interrupt
        else
            puts 'else about to call Object#exit'
            object_exit(p)
        end
    end
end

begin
  ::Chef::Knife.run([])
rescue SystemExit => e
  puts "in script's rescue SystemExit e=#{e.inspect}"
rescue Interrupt
  puts "in script's rescue Interrupt"
end

Execution. First test with Ctrl-C :

$ ruby -w simul_chef.rb
in original run
Press Ctrl_C > ^C
in run_with_pretty...'s Exception e=Interrupt Interrupt
now $!=Interrupt
about to exit,                     self=#<Chef::Knife:0x007fb2361c7038>
in my own exit with parameter 100, self=#<Chef::Knife:0x007fb2361c7038>
$!=Interrupt
then about to raise Interrupt
in script's rescue Interrupt

Second test with a hard interrupt.

In one terminal window :

$ ruby -w simul_chef.rb
in original run
Press Ctrl_C >

In another terminal window :

$ ps -ef
  UID   PID  PPID   C STIME   TTY           TIME CMD
    0     1     0   0 Fri01PM ??         0:52.65 /sbin/launchd
...
    0   363   282   0 Fri01PM ttys000    0:00.02 login -pfl b /bin/bash -c exec -la bash /bin/bash
  501   364   363   0 Fri01PM ttys000    0:00.95 -bash
  501  3175   364   0  9:51PM ttys000    0:00.06 ruby -w simul_chef.rb
...
$ kill 3175

Back in the first terminal :

in run_with_pretty...'s Exception e=#<SignalException: SIGTERM> SignalException
now $!=#<SignalException: SIGTERM>
about to exit,                     self=#<Chef::Knife:0x007fc5a79d70a0>
in my own exit with parameter 100, self=#<Chef::Knife:0x007fc5a79d70a0>
$!=#<SignalException: SIGTERM>
else about to call Object#exit
in script's rescue SystemExit e=#<SystemExit: exit>

Considering the code you originally posted, all you have to do is inserting at the beginning, but after the necessary require :

class Chef::Knife # reopen the Knife class and define one's own exit
    alias_method :object_exit, :exit

    def exit(p)
        if Interrupt === $!
            raise # re-raise Interrupt
        else
            object_exit(p)
        end
    end
end

So there is no need to touch the original gem.


问:
DynamoDB partition key choice for notes app
I want to create a DynamoDB table that allows me to save notes from users.

The attributes I have:

user_id

note_id (uuid)

type

text

The main queries I will need:

Get all notes of a certain user

Get a specific note

Get all notes of a certain type (the less used query)

I know that in terms of performance and DynamoDB partitions note_id would be the right choice because they are unique and would be distributed equally over the partitions but on the other hand is much harder to get all notes of a user without scanning all items or using a GSI. And if they are unique I suppose it doesn't make any sense to have a sort key.

The other option would be to use user_id as partition key and note_id as sort key, but if I have certain users that are a much larger number of notes than others wouldn't that impact my performance?

Is it better to have a partition key unique (like note_id) to scale well with DynamoDB partitions and use GSIs to create my queries or to use instead a partition key for my main query (user_id)?

Thanks

答:
I see this as 2 tables. User and notes with a GSI on the notes table. Not sure how else you could do it. Using userId as primary key and note_id as sort key requires that you can only retrieve elements when you know both the user_id and the note_id. With DynamoDB if your not scanning you have to satisfy all the elements in the primary key, so both the partition and and sort if there is one. Below is how I would do this.

Get all notes of a certain user

When a user creates a note I would add this to the users table in the users notes attribute. When you want to get all of a users notes then retrieve the user and access the array/list of note_ids stored there.

```<code>{ userId: xxx,
  notes: [ note_id_1,note_id_2,note_id_3]
}
</code>```

Get a specific note

A notes table with node_id as the primary key would make that easy.

```<code>{
noteId: XXXX,
note: "sfsfsfsfsfsf",
type: "standard_note"
}
</code>```

Get all notes of a certain type (the less used query)
I would use a GSI on the notes table for this with the attributes of "note_type" and note_id projected onto it.

Update

You can pull this off with one table and a GSI (See the two answers below for how) but I would not do it. Your data model is so simple why make it more complicated than users and notes.

Body:
I see this as 2 tables. User and notes with a GSI on the notes table. Not sure how else you could do it. Using userId as primary key and note_id as sort key requires that you can only retrieve elements when you know both the user_id and the note_id. With DynamoDB if your not scanning you have to satisfy all the elements in the primary key, so both the partition and and sort if there is one. Below is how I would do this.

Get all notes of a certain user

When a user creates a note I would add this to the users table in the users notes attribute. When you want to get all of a users notes then retrieve the user and access the array/list of note_ids stored there.

{ userId: xxx,
  notes: [ note_id_1,note_id_2,note_id_3]
}

Get a specific note

A notes table with node_id as the primary key would make that easy.

{
noteId: XXXX,
note: "sfsfsfsfsfsf",
type: "standard_note"
}

Get all notes of a certain type (the less used query)
I would use a GSI on the notes table for this with the attributes of "note_type" and note_id projected onto it.

Update

You can pull this off with one table and a GSI (See the two answers below for how) but I would not do it. Your data model is so simple why make it more complicated than users and notes.


问:
How do I convert an Array of Arrays to a DataFrame, in Julia?
I have a map call that results in a row of computed values, therefore I have an Array of rows that are Array of Any, like this

```<code>12-element Array{Array{Any,1},1}:
 Any[2015-09-01T00:00:00, 2016-09-01T00:00:00, 98, 53.1]
 Any[2015-10-01T00:00:00, 2016-10-01T00:00:00, 92, 58.7]
 Any[2015-11-01T00:00:00, 2016-11-01T00:00:00, 130, 64.6]
 Any[2015-12-01T00:00:00, 2016-12-01T00:00:00, 135, 67.4]
 Any[2016-01-01T00:00:00, 2017-01-01T00:00:00, 206, 59.2]
 Any[2016-02-01T00:00:00, 2017-02-01T00:00:00, 246, 54.1]
 Any[2016-03-01T00:00:00, 2017-03-01T00:00:00, 254, 53.9]
 Any[2016-04-01T00:00:00, 2017-04-01T00:00:00, 268, 65.7]
 Any[2016-05-01T00:00:00, 2017-05-01T00:00:00, 265, 61.5]
 Any[2016-06-01T00:00:00, 2017-06-01T00:00:00, 303, 52.8]
 Any[2016-07-01T00:00:00, 2017-07-01T00:00:00, 301, 59.1]
 Any[2016-08-01T00:00:00, 2017-08-01T00:00:00, 273, 54.6]
</code>```

Is there an easy way of turning this into a DataFrame, with column names and so on? If there isn't an easy way, I'm open to harder ways :) I can think of having to re-run map four times to extract the columns and build the DataFrame from those, but that sounds like a lot of code for such a seemingly mundane operation…

EDIT I can "transpose" rows to columns like this

```<code>map(x -> map(y -> y[x], r), collect(1:4)
</code>```

where r is the table above, so I suppose a solution would be to provide column names to the DataFrame constructor. My temporary solution is therefore

```<code>DataFrame(map(x -> map(y -> y[x], r), collect(1:4)), [:a, :b, :c, :d])
</code>```

Body:
I have a map call that results in a row of computed values, therefore I have an Array of rows that are Array of Any, like this

12-element Array{Array{Any,1},1}:
 Any[2015-09-01T00:00:00, 2016-09-01T00:00:00, 98, 53.1]
 Any[2015-10-01T00:00:00, 2016-10-01T00:00:00, 92, 58.7]
 Any[2015-11-01T00:00:00, 2016-11-01T00:00:00, 130, 64.6]
 Any[2015-12-01T00:00:00, 2016-12-01T00:00:00, 135, 67.4]
 Any[2016-01-01T00:00:00, 2017-01-01T00:00:00, 206, 59.2]
 Any[2016-02-01T00:00:00, 2017-02-01T00:00:00, 246, 54.1]
 Any[2016-03-01T00:00:00, 2017-03-01T00:00:00, 254, 53.9]
 Any[2016-04-01T00:00:00, 2017-04-01T00:00:00, 268, 65.7]
 Any[2016-05-01T00:00:00, 2017-05-01T00:00:00, 265, 61.5]
 Any[2016-06-01T00:00:00, 2017-06-01T00:00:00, 303, 52.8]
 Any[2016-07-01T00:00:00, 2017-07-01T00:00:00, 301, 59.1]
 Any[2016-08-01T00:00:00, 2017-08-01T00:00:00, 273, 54.6]

Is there an easy way of turning this into a DataFrame, with column names and so on? If there isn't an easy way, I'm open to harder ways :) I can think of having to re-run map four times to extract the columns and build the DataFrame from those, but that sounds like a lot of code for such a seemingly mundane operation…

EDIT I can "transpose" rows to columns like this

map(x -> map(y -> y[x], r), collect(1:4)

where r is the table above, so I suppose a solution would be to provide column names to the DataFrame constructor. My temporary solution is therefore

DataFrame(map(x -> map(y -> y[x], r), collect(1:4)), [:a, :b, :c, :d])

Body:
julia> df
12-element Array{Array{Any,1},1}:
 Any["2015-09-01T00:00:00", "2016-09-01T00:00:00", 98, 53.1]
 Any["2015-10-01T00:00:00", "2016-10-01T00:00:00", 92, 58.7]
 Any["2015-11-01T00:00:00", "2016-11-01T00:00:00", 130, 64.6]
 Any["2015-12-01T00:00:00", "2016-12-01T00:00:00", 135, 67.4]
 Any["2016-01-01T00:00:00", "2017-01-01T00:00:00", 206, 59.2]
 Any["2016-02-01T00:00:00", "2017-02-01T00:00:00", 246, 54.1]
 Any["2016-03-01T00:00:00", "2017-03-01T00:00:00", 254, 53.9]
 Any["2016-04-01T00:00:00", "2017-04-01T00:00:00", 268, 65.7]
 Any["2016-05-01T00:00:00", "2017-05-01T00:00:00", 265, 61.5]
 Any["2016-06-01T00:00:00", "2017-06-01T00:00:00", 303, 52.8]
 Any["2016-07-01T00:00:00", "2017-07-01T00:00:00", 301, 59.1]
 Any["2016-08-01T00:00:00", "2017-08-01T00:00:00", 273, 54.6]

julia> DataFrame(permutedims(Array(DataFrame(map(data,df))), [2, 1]))
12×4 DataFrames.DataFrame
│ Row │ x1                    │ x2                    │ x3  │ x4   │
├─────┼───────────────────────┼───────────────────────┼─────┼──────┤
│ 1   │ "2015-09-01T00:00:00" │ "2016-09-01T00:00:00" │ 98  │ 53.1 │
│ 2   │ "2015-10-01T00:00:00" │ "2016-10-01T00:00:00" │ 92  │ 58.7 │
│ 3   │ "2015-11-01T00:00:00" │ "2016-11-01T00:00:00" │ 130 │ 64.6 │
│ 4   │ "2015-12-01T00:00:00" │ "2016-12-01T00:00:00" │ 135 │ 67.4 │
│ 5   │ "2016-01-01T00:00:00" │ "2017-01-01T00:00:00" │ 206 │ 59.2 │
│ 6   │ "2016-02-01T00:00:00" │ "2017-02-01T00:00:00" │ 246 │ 54.1 │
│ 7   │ "2016-03-01T00:00:00" │ "2017-03-01T00:00:00" │ 254 │ 53.9 │
│ 8   │ "2016-04-01T00:00:00" │ "2017-04-01T00:00:00" │ 268 │ 65.7 │
│ 9   │ "2016-05-01T00:00:00" │ "2017-05-01T00:00:00" │ 265 │ 61.5 │
│ 10  │ "2016-06-01T00:00:00" │ "2017-06-01T00:00:00" │ 303 │ 52.8 │
│ 11  │ "2016-07-01T00:00:00" │ "2017-07-01T00:00:00" │ 301 │ 59.1 │
│ 12  │ "2016-08-01T00:00:00" │ "2017-08-01T00:00:00" │ 273 │ 54.6 │

I think your solution is much better... !


问:
System.Runtime.Serialization.Json nuget package error on .NetStandard
I've posted an issue on .NetStandard repository but they just didn't care for 12 days for now.. So, I wanted to try Stackoverflow. Here is the link of my issue.

I've started to use .NetCore version=1.0.0-preview2-003121 with Visual Studio 2015. My project.json file is below:

```<code>{
  "version": "1.0.0-*",
  "frameworks": {
    "netstandard2.0": {
      "dependencies": {
        "System.Runtime.Serialization.Xml": "4.3.0",
        "System.Runtime.Serialization.Json": "4.3.0"
      }
    }
  }
}
</code>```

My code file is below:

```<code>using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace NetCoreTests
{
    public class Class1
    {
        public Class1()
        {
            XmlObjectSerializer ser = new DataContractJsonSerializer(typeof(int));
        }
    }
}
</code>```

And this is the error I get when I try to build the solution:

```<code>CS0029  Cannot implicitly convert type 'System.Runtime.Serialization.Json.DataContractJsonSerializer'
to 'System.Runtime.Serialization.XmlObjectSerializer'   NetCoreTests..NETStandard,Version=v2.0
</code>```

Looks like DataContractJsonSerializer class in System.Runtime.Serialization.Json nuget package doesn't inherit XmlObjectSerializer class in System.Runtime.Serialization.Xml nuget package. I can see that in general there's no dependency between these 2 nuget packages; however, if you check 4 and later versions of .Net Framework DataContractJsonSerializer always inherits from XmlObjectSerializer because as far as I know every DataContractSerializer inherits from XmlObjectSerializer. Even in this repository this inheritance exists:
https://github.com/dotnet/standard/blob/master/netstandard/ref/System.Runtime.Serialization.cs#L332

What can you advice for me about this situation? Am I doin something wrong?

答:
Don't use the VS 2015 based preview tooling for .NET Core / .NET Standard to try to build for .NET Standard 2.0.

If you use VS 2017 / .NET Core SDK 2.0.0+ then you get the correct reference assemblies to build (which are pulled from the NETStandard.Library 2.0.0 NuGet package - the System.* packages are trimmed out by msbuild logic if they are referenced).

Your code sample works using a new .NET Standard 2.0 project using tooling that actually supports .NET Standard 2.0 (VS 2017, CLI 2.0.0).

Note that in .NET Standard < 2.0, the DataContractJsonSerializer did not inherit from XmlObjectSerializer - which is the one you are getting via the referenced NuGet package (since you are missing the tooling that trims out this package and adds correct .NET Standard reference assemblies).

Body:
I've posted an issue on .NetStandard repository but they just didn't care for 12 days for now.. So, I wanted to try Stackoverflow. Here is the link of my issue.

I've started to use .NetCore version=1.0.0-preview2-003121 with Visual Studio 2015. My project.json file is below:

{
  "version": "1.0.0-*",
  "frameworks": {
    "netstandard2.0": {
      "dependencies": {
        "System.Runtime.Serialization.Xml": "4.3.0",
        "System.Runtime.Serialization.Json": "4.3.0"
      }
    }
  }
}

My code file is below:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace NetCoreTests
{
    public class Class1
    {
        public Class1()
        {
            XmlObjectSerializer ser = new DataContractJsonSerializer(typeof(int));
        }
    }
}

And this is the error I get when I try to build the solution:

CS0029  Cannot implicitly convert type 'System.Runtime.Serialization.Json.DataContractJsonSerializer'
to 'System.Runtime.Serialization.XmlObjectSerializer'   NetCoreTests..NETStandard,Version=v2.0

Looks like DataContractJsonSerializer class in System.Runtime.Serialization.Json nuget package doesn't inherit XmlObjectSerializer class in System.Runtime.Serialization.Xml nuget package. I can see that in general there's no dependency between these 2 nuget packages; however, if you check 4 and later versions of .Net Framework DataContractJsonSerializer always inherits from XmlObjectSerializer because as far as I know every DataContractSerializer inherits from XmlObjectSerializer. Even in this repository this inheritance exists:
https://github.com/dotnet/standard/blob/master/netstandard/ref/System.Runtime.Serialization.cs#L332

What can you advice for me about this situation? Am I doin something wrong?


问:
Does `+=` operator always create a new string object?
If pool memory already has an object with similar content, then if we try to create the same object with different reference variable then only a new reference variable is created, NO NEW OBJECT IS CREATED.eg;

```<code>String s7="1";
String s8 ="1";
System.out.print(s7==s8);  //True
</code>```

Here only one object is created.
But in the following example

```<code>public class JavaApplication1 {
    public static void main(String[] args) {
        String s1 = "1", s2 = "2", s4 = s1 + s2, s5 = "12";
        final String s3 = s1 + s2;
        s1 += s2;
        System.out.print((s1 == s3) + "" + (s1 == s5) + "" + "" (s3 == s5));
    }
}
</code>```

Output is false false false
Even is s3 is declared as an final expression!, why?

答:
If pool memory already has an object with similar content, then if we try to create the same object with different reference variable then only a new reference variable is created, NO NEW OBJECT IS CREATED.eg;

That is actually not true in the general case. What you are describing is called String interning. An interned String will always be reference-equal to any other interned String with the same content - that's basically the guarantee of intern. (From the docs on String.intern: It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.). If I were to create 2 Strings from a constant byte array, then even as they share the content, those will be different objects.

The JLS further specifies that:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Hence why you get equality of String literals, and anything that is a value of [a] constant expression.

So, what is this constant expression? Well, again, according to the JLS, those are literals, Simple names (§6.5.6.1) that refer to constant variables, various non-String stuffs, and expressions with +, but only as long as both operands of + are themselves constant expressions (The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).). So this means that, unless your Strings on both sides of + are literals, final strings with the value being a constant expression or fulfill one of the other conditions (like a cast from a primitive constant), a new object will be created.

Body:
If pool memory already has an object with similar content, then if we try to create the same object with different reference variable then only a new reference variable is created, NO NEW OBJECT IS CREATED.eg;

String s7="1";
String s8 ="1";
System.out.print(s7==s8);  //True

Here only one object is created.
But in the following example

public class JavaApplication1 {
    public static void main(String[] args) {
        String s1 = "1", s2 = "2", s4 = s1 + s2, s5 = "12";
        final String s3 = s1 + s2;
        s1 += s2;
        System.out.print((s1 == s3) + "" + (s1 == s5) + "" + "" (s3 == s5));
    }
}

Output is false false false
Even is s3 is declared as an final expression!, why?


答:
If you know that the variable exists, then

```<code>if (!$myarray) { }
</code>```

is probably the simplest, amount-of-code-wise. (Empty arrays evaluate as false.) If you're not sure whether or not it exists, then

```<code>if (empty($myarray)) { }
</code>```

will avoid undefined variable notices as well.

Counting it is unnecessary work if all you need is to see whether or not it's empty.

Title: which is the best way to check that an array is empty

Body:
I am trying to know if an array is empty, as I am still learning to use php I would like to know which is the best way .. now I am doing it this way:

if (sizeof($myarray) == 0) { }

Body:
If you know that the variable exists, then

if (!$myarray) { }

is probably the simplest, amount-of-code-wise. (Empty arrays evaluate as false.) If you're not sure whether or not it exists, then

if (empty($myarray)) { }

will avoid undefined variable notices as well.

Counting it is unnecessary work if all you need is to see whether or not it's empty.


问:
How to upload files to specific folder multer-ftp on remote server?
Using this code I try send files on remote server:

```<code>var upload = multer({
    storage: new ftpStorage({
        basepath: '/uploads/',

        ftp: {
            host: 'samplehost.com',
            secure: false, // enables FTPS/FTP with TLS
            user: 'login',
            password: 'password'
        }
    })
});
</code>```

but always save file in root directory, not in uploads, how can I fix this?

答:
Instead of multer-ftp, Uploading Files to remote server using multer-sftp is easy and flexible way. also we can upload the files to remote server with scp, ssh techniques in node js.

Working Code:

```<code>exports.newFileUpload =  function(req , res , next){

   // sftp settings
    var storage = sftpStorage({
      sftp: {
        host: 'hostname',
        port: 22,
        username: 'username',
        password: 'password'

      },
      destination: function (req, file, cb) {
        cb(null, 'images/') // designation folder in host
      },
      filename: function (req, file, cb) {
        // file name settings
        cb(null, file.fieldname + '-' + Date.now())
      }
    })

    var upload = multer({ storage: storage }).array('file');

    upload(req,res,function(err){
        logger.debug(JSON.stringify(req.body));
              logger.debug(JSON.stringify(req.files));
          if(err){
               logger.debug("Error Occured", JSON.stringify(err));
               res.json({error_code:1,err_desc:err});
          } else{
               logger.debug("Files uploaded successfully");
              res.json({error_code:0,err_desc:null});
          }
      });
}
</code>```

Note: When using 'multer-sftp' port no 22 is open in remote server.

Official Documentation multer-sftp

Hope it helps !

Body:
Using this code I try send files on remote server:

var upload = multer({
    storage: new ftpStorage({
        basepath: '/uploads/',

        ftp: {
            host: 'samplehost.com',
            secure: false, // enables FTPS/FTP with TLS
            user: 'login',
            password: 'password'
        }
    })
});

but always save file in root directory, not in uploads, how can I fix this?

Body:
Instead of multer-ftp, Uploading Files to remote server using multer-sftp is easy and flexible way. also we can upload the files to remote server with scp, ssh techniques in node js.

Working Code:

exports.newFileUpload =  function(req , res , next){

   // sftp settings
    var storage = sftpStorage({
      sftp: {
        host: 'hostname',
        port: 22,
        username: 'username',
        password: 'password'

      },
      destination: function (req, file, cb) {
        cb(null, 'images/') // designation folder in host
      },
      filename: function (req, file, cb) {
        // file name settings
        cb(null, file.fieldname + '-' + Date.now())
      }
    })

    var upload = multer({ storage: storage }).array('file');

    upload(req,res,function(err){
        logger.debug(JSON.stringify(req.body));
              logger.debug(JSON.stringify(req.files));
          if(err){
               logger.debug("Error Occured", JSON.stringify(err));
               res.json({error_code:1,err_desc:err});
          } else{
               logger.debug("Files uploaded successfully");
              res.json({error_code:0,err_desc:null});
          }
      });
}

Note: When using 'multer-sftp' port no 22 is open in remote server.

Official Documentation multer-sftp

Hope it helps !


问:
Haskell arbitrary typeclass instance return type
From the Haskell Book chapter on Monoids, I am writing quickcheck tests for

```<code>semigroupAssoc :: (Eq m, S.Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c =
    (a S.<> (b S.<> c)) == ((a S.<> b) S.<> c)

type IdentAssoc = Identity String -> Identity String -> Identity String -> Bool
</code>```

, invoking with

```<code>quickCheck (semigroupAssoc :: IdentAssoc)
</code>```

Here is the arbitrary typeclass instance

```<code>instance (Arbitrary a) => Arbitrary (Identity a) where
    arbitrary = do
        a <- Test.QuickCheck.arbitrary
        return (Identity a)
</code>```

My question is that in my arbitrary instance, I can return either (Identity a) or just a.  (Identity a) is correct, but just a gives no compiler error and causes an infinite loop when run. Why is this?

答:
If you write it as:

```<code>instance Arbitrary a => Arbitrary (Identity a) where
    <b>arbitrary</b> = do
        x <- <b>arbitrary</b>
        return x</code>```

(I renamed a to x to cause less confusion).

Then Haskell will do the type plumbing, and it will derive that, since you write return x, x must have type Identity a. And we are lucky, since there exists an arbitrary :: Arbitrary a => Gen a, the one we just defined (put in boldface here).

So that means that we have constructed an infinite loop. For instance in Java, it would look like:

```<code>public int foo(int x) {
    return foo(x);
}
</code>```

Of course we can define such a function, and it is correct if we check the types. But there is of course no progress, since we keep calling the same function that will again call that function and again, and again,...

If you however write:

```<code>instance Arbitrary a => Arbitrary (Identity a) where
    <b>arbitrary</b> = do
        x <- arbitrary
        return <b>Identity</b> x</code>```

Haskell will derive that x has type a. And we are again lucky, since we have defined that Arbitrary a should hold, some somewhere there is an arbitrary :: Arbitrary a => Gen a function, but it is a different one (that's why I did not write it in boldface here), and that one will generate the value that we wrap in the Identity constructor.

Note that in the first example, we do not even have to add the Arbitrary a constraint: indeed:

```<code>instance Arbitrary (Identity a) where
    <b>arbitrary</b> = do
        x <- <b>arbitrary</b>
        return x</code>```

this compiles just fine, since we never generate an arbitrary a.

Body:
From the Haskell Book chapter on Monoids, I am writing quickcheck tests for

semigroupAssoc :: (Eq m, S.Semigroup m) => m -> m -> m -> Bool
semigroupAssoc a b c =
    (a S.<> (b S.<> c)) == ((a S.<> b) S.<> c)

type IdentAssoc = Identity String -> Identity String -> Identity String -> Bool

, invoking with

quickCheck (semigroupAssoc :: IdentAssoc)

Here is the arbitrary typeclass instance

instance (Arbitrary a) => Arbitrary (Identity a) where
    arbitrary = do
        a <- Test.QuickCheck.arbitrary
        return (Identity a)

My question is that in my arbitrary instance, I can return either (Identity a) or just a.  (Identity a) is correct, but just a gives no compiler error and causes an infinite loop when run. Why is this?

Body:
If you write it as:

instance Arbitrary a => Arbitrary (Identity a) where
    arbitrary = do
        x <- arbitrary
        return x

(I renamed a to x to cause less confusion).

Then Haskell will do the type plumbing, and it will derive that, since you write return x, x must have type Identity a. And we are lucky, since there exists an arbitrary :: Arbitrary a => Gen a, the one we just defined (put in boldface here).

So that means that we have constructed an infinite loop. For instance in Java, it would look like:

public int foo(int x) {
    return foo(x);
}

Of course we can define such a function, and it is correct if we check the types. But there is of course no progress, since we keep calling the same function that will again call that function and again, and again,...

If you however write:

instance Arbitrary a => Arbitrary (Identity a) where
    arbitrary = do
        x <- arbitrary
        return Identity x

Haskell will derive that x has type a. And we are again lucky, since we have defined that Arbitrary a should hold, some somewhere there is an arbitrary :: Arbitrary a => Gen a function, but it is a different one (that's why I did not write it in boldface here), and that one will generate the value that we wrap in the Identity constructor.

Note that in the first example, we do not even have to add the Arbitrary a constraint: indeed:

instance Arbitrary (Identity a) where
    arbitrary = do
        x <- arbitrary
        return x

this compiles just fine, since we never generate an arbitrary a.


问:
Cannot get spring email to work
I am trying to implement a spring email service for which I implemented the GOOF design pattern. I created an interface Email service as follows.

public interface EmailService {

```<code>public void sendFeedbackEmail(FeedbackPojo feedbackPojo);

public void sendGenericEmailMessage(SimpleMailMessage message);
</code>```

}

Then I created an abstract class which extends this interface and implements one of it's overridden methods which is sendFeedbackEmail(FeedBackPojo feedbackpojo) The implementation of this abstract class is as follows.

```<code>public abstract class AbstractEmailService implements EmailService {

@Value("@{default.to.address}")
private String defaultToAddress ;

protected SimpleMailMessage preparedSimpleMailMessageFromFeedbackPojo(FeedbackPojo feedback){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(defaultToAddress);
    message.setFrom(feedback.getEmail());
    message.setSubject("[Subscriber]: Feedback Received from"+ feedback.getFirstName()+" "+feedback.getLastName()+"!");
    message.setText(feedback.getFeedback());

    return message;
}

@Override
public void sendFeedbackEmail(FeedbackPojo feedbackPojo) {
    sendGenericEmailMessage(preparedSimpleMailMessageFromFeedbackPojo(feedbackPojo));
}
</code>```

}

Then I created a class MockEmailService with the implementation of second method of the EmailService interface which is sendGenericEmail(SimpleMailMessage message) as follows

public class MockEmailService extends AbstractEmailService{

```<code>private static final Logger log =
LoggerFactory.getLogger(MockEmailService.class);

@Override
public void sendGenericEmailMessage(SimpleMailMessage message) {
    System.out.println(message.toString());
}
</code>```

}

Then I am creating an Autowired object of emailService in my controller class and simulating my emailservice as follows

```<code>@Controller
</code>```

public class ContactController {

```<code>private static final org.slf4j.Logger log = LoggerFactory.getLogger(ContactController.class);
public static final String FEEDBACK_MODEL_KEY="feedback";
private static final String CONTACT_US_VIEW_NAME="contact/contact";

@Autowired
private EmailService emailService;

@RequestMapping(value = "/contact",method = RequestMethod.GET)
public String getContact(ModelMap model){
    FeedbackPojo feedbackPojo = new FeedbackPojo();
    model.addAttribute(ContactController.FEEDBACK_MODEL_KEY,feedbackPojo);
    return ContactController.CONTACT_US_VIEW_NAME;
}

@RequestMapping(value = "/contact",method = RequestMethod.POST)
public String postContact(@ModelAttribute(FEEDBACK_MODEL_KEY) FeedbackPojo feedback){
    log.debug("Feedback content {}",feedback);
    emailService.sendFeedbackEmail(feedback);
    return ContactController.CONTACT_US_VIEW_NAME;
}
</code>```

}

However, when I try to run my application the application terminates and the error I receive is as follows

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.subscriptionservice.backend.service.EmailService com.subscriptionservice.web.controllers.ContactController.emailService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.subscriptionservice.backend.service.EmailService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Can someone please point out the issue in my implementation. Thanks.

答:
No qualifying bean of type
  [com.subscriptionservice.backend.service.EmailService] found for
  dependency

As far as I see, you haven't introduced an instance of your interface EmailService into the collection of Spring-managed beans.

Try annotating (stereotyping) the MockEmailService with @Service.

Also...

Make sure you have component-scan defined somewhere in a manner that will include the package where MockEmailService resides.

Do you intend that the MockEmailService will permanently implement the contract of EmailService in your application?  (Based on the name, I wouldn't guess so.)  If MockEmailService is intended only for certain circumstances -- such as non-production deployments or testing -- you may need a more flexible system for defining or wiring your beans.  There are many options, such as Spring Profiles.

Title: Cannot get spring email to work

Body:
I am trying to implement a spring email service for which I implemented the GOOF design pattern. I created an interface Email service as follows.

public interface EmailService {

public void sendFeedbackEmail(FeedbackPojo feedbackPojo);

public void sendGenericEmailMessage(SimpleMailMessage message);

}

Then I created an abstract class which extends this interface and implements one of it's overridden methods which is sendFeedbackEmail(FeedBackPojo feedbackpojo) The implementation of this abstract class is as follows.

public abstract class AbstractEmailService implements EmailService {

@Value("@{default.to.address}")
private String defaultToAddress ;

protected SimpleMailMessage preparedSimpleMailMessageFromFeedbackPojo(FeedbackPojo feedback){
    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(defaultToAddress);
    message.setFrom(feedback.getEmail());
    message.setSubject("[Subscriber]: Feedback Received from"+ feedback.getFirstName()+" "+feedback.getLastName()+"!");
    message.setText(feedback.getFeedback());

    return message;
}

@Override
public void sendFeedbackEmail(FeedbackPojo feedbackPojo) {
    sendGenericEmailMessage(preparedSimpleMailMessageFromFeedbackPojo(feedbackPojo));
}

}

Then I created a class MockEmailService with the implementation of second method of the EmailService interface which is sendGenericEmail(SimpleMailMessage message) as follows

public class MockEmailService extends AbstractEmailService{

private static final Logger log =
LoggerFactory.getLogger(MockEmailService.class);

@Override
public void sendGenericEmailMessage(SimpleMailMessage message) {
    System.out.println(message.toString());
}

}

Then I am creating an Autowired object of emailService in my controller class and simulating my emailservice as follows

@Controller

public class ContactController {

private static final org.slf4j.Logger log = LoggerFactory.getLogger(ContactController.class);
public static final String FEEDBACK_MODEL_KEY="feedback";
private static final String CONTACT_US_VIEW_NAME="contact/contact";

@Autowired
private EmailService emailService;

@RequestMapping(value = "/contact",method = RequestMethod.GET)
public String getContact(ModelMap model){
    FeedbackPojo feedbackPojo = new FeedbackPojo();
    model.addAttribute(ContactController.FEEDBACK_MODEL_KEY,feedbackPojo);
    return ContactController.CONTACT_US_VIEW_NAME;
}

@RequestMapping(value = "/contact",method = RequestMethod.POST)
public String postContact(@ModelAttribute(FEEDBACK_MODEL_KEY) FeedbackPojo feedback){
    log.debug("Feedback content {}",feedback);
    emailService.sendFeedbackEmail(feedback);
    return ContactController.CONTACT_US_VIEW_NAME;
}

}

However, when I try to run my application the application terminates and the error I receive is as follows

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contactController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.subscriptionservice.backend.service.EmailService com.subscriptionservice.web.controllers.ContactController.emailService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.subscriptionservice.backend.service.EmailService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Can someone please point out the issue in my implementation. Thanks.