问:
Is possible to change a property inside a item and return the item itself?
I have a code like this on my app

var name = 'TesT';
var nameLowercase = name && name.toLowerCase (),
    namesToTest = ['asd', 'asd1', 'TesT'];

var findCorrectName = R.pipe(
    R.map(R.toLower),
    R.any(R.equals(nameLowercase))
);

var hasFoundName = findCorrectName (namesToTest);

return hasFoundName;
```

<p>But, now I need to do a search in a list of objects and the property 'name' must be put to lowercase. When found an object that matches my search, I need to get it. </p>

<p>I've read the documentation but I couldn't find a solution.</p>

<pre class="lang-js prettyprint-override"><code>var name = 'TesT';
var nameLowercase = name && name.toLowercase (),
namesToTest = [ { name : 'asd', otherProperties... },
                { name : 'asd1', otherProperties... },
                { name : 'TesT', otherProperties... }];

var findByCorrectName = R.pipe(
    R.map(
        R.pipe(R.prop('name'), R.toLower)),
        R.find(R.propEq('name', nameLowercase))
    );

var foundObject = findByCorrectName (namesToTest);

return foundObject;
</code>```

答:
I've found the function over, it was just I need.

var name = 'TesT',
    nameLowercase = name && name.toLowerCase(),
    namesToTest = [ { name : 'asd' },
                    { name : 'asd1' },
                    { name : 'TesT' }];

var findByCorrectName = R.pipe(
                          R.map(R.over(R.lensProp('name'), R.toLower)),
                          R.find(R.propEq('name', nameLowercase))
                        );

var hasFoundName = findByCorrectName (namesToTest);

return hasFoundName;
```

Body:
I have a code like this on my app

var name = 'TesT';
var nameLowercase = name && name.toLowerCase (),
    namesToTest = ['asd', 'asd1', 'TesT'];

var findCorrectName = R.pipe(
    R.map(R.toLower),
    R.any(R.equals(nameLowercase))
);

var hasFoundName = findCorrectName (namesToTest);

return hasFoundName;

But, now I need to do a search in a list of objects and the property 'name' must be put to lowercase. When found an object that matches my search, I need to get it.

I've read the documentation but I couldn't find a solution.

var name = 'TesT';
var nameLowercase = name && name.toLowercase (),
namesToTest = [ { name : 'asd', otherProperties... },
                { name : 'asd1', otherProperties... },
                { name : 'TesT', otherProperties... }];

var findByCorrectName = R.pipe(
    R.map(
        R.pipe(R.prop('name'), R.toLower)),
        R.find(R.propEq('name', nameLowercase))
    );

var foundObject = findByCorrectName (namesToTest);

return foundObject;


来源: stackexchange

问:
Fatal error: require_once(): Failed opening required 'Zend/Loader/Autoloader.php'
I have project zend framework in localhost work but when i upload in the 1&1 i have this Error:
Warning: require_once(/../library/Zend/Loader/Autoloader.php): failed to open stream: No such file or directory in /homepages/9/d675656264/htdocs/project/public/index.php on line 18

Here my index.php

```<code>define('APPLICATION_ENV', 'production');
// Define path to application directory
defined ( 'APPLICATION_PATH' ) || define ( 'APPLICATION_PATH', realpath ( dirname ( __FILE__ ) . '/application' ) );

// Define application environment
 defined ( 'APPLICATION_ENV' ) || define ( 'APPLICATION_ENV', (getenv ( 'APPLICATION_ENV' ) ? getenv ( 'APPLICATION_ENV' ) : 'production') );
 // Ensure library/ is on include_path

$rootPath = dirname(__FILE__);
set_include_path(
    PATH_SEPARATOR . $rootPath . DIRECTORY_SEPARATOR . '/../../library' .
    PATH_SEPARATOR . get_include_path());

// To enable autoloader, (this is a new way of using autoloader)
require_once  '/../library/Zend/Loader/Autoloader.php';
</code>```

答:
Try adding __DIR__ so it uses the full path

require  __DIR__.'/../library/Zend/Loader/Autoloader.php';

ContentLicense: CC BY-SA 3.0

Body:
I have project zend framework in localhost work but when i upload in the 1&1 i have this Error:
Warning: require_once(/../library/Zend/Loader/Autoloader.php): failed to open stream: No such file or directory in /homepages/9/d675656264/htdocs/project/public/index.php on line 18

Here my index.php

define('APPLICATION_ENV', 'production');
// Define path to application directory
defined ( 'APPLICATION_PATH' ) || define ( 'APPLICATION_PATH', realpath ( dirname ( __FILE__ ) . '/application' ) );

// Define application environment
 defined ( 'APPLICATION_ENV' ) || define ( 'APPLICATION_ENV', (getenv ( 'APPLICATION_ENV' ) ? getenv ( 'APPLICATION_ENV' ) : 'production') );
 // Ensure library/ is on include_path

$rootPath = dirname(__FILE__);
set_include_path(
    PATH_SEPARATOR . $rootPath . DIRECTORY_SEPARATOR . '/../../library' .
    PATH_SEPARATOR . get_include_path());

// To enable autoloader, (this is a new way of using autoloader)
require_once  '/../library/Zend/Loader/Autoloader.php';


问:
PHP: black image when cropping using php
i set up a scritp that upload an jpeg and then crop it in a thumbnail, but some users experiences a black image, and honestly i dont know what they are uploading, maybe a jpeg with a compresison format not compatible with php libraries??

this is my simple code...eveything works fine when i try with my photos so i  cant undestand why some users have a black image as resulting thumbnail...

```<code>$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h, $w, $h);
imagejpeg($dst_r, $output_filename, $jpeg_quality);
</code>```

UPDATE: i found out the bug: basically it happens when a user try to upload an image that has a filename that ontains spaces %20... so there is something wrong in the way i'm passing the filname from javascriptajax call to a script in php...aargg..so dumb

答:
Sometimes you get black when the crop is trying to move the image to a place outside of the image.

```<code>_________
|       |
|       | ____
|  0_o  | |  |
|   |   | |__|
|_______|
</code>```

Check that the width, height, and x/y offsets are correct numbers inside the image and that the math isn't moving them to be ouside the image area.

ContentLicense: CC BY-SA 2.5

Body:
i set up a scritp that upload an jpeg and then crop it in a thumbnail, but some users experiences a black image, and honestly i dont know what they are uploading, maybe a jpeg with a compresison format not compatible with php libraries??

this is my simple code...eveything works fine when i try with my photos so i  cant undestand why some users have a black image as resulting thumbnail...

$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h, $w, $h);
imagejpeg($dst_r, $output_filename, $jpeg_quality);

UPDATE: i found out the bug: basically it happens when a user try to upload an image that has a filename that ontains spaces %20... so there is something wrong in the way i'm passing the filname from javascriptajax call to a script in php...aargg..so dumb

Body:
Sometimes you get black when the crop is trying to move the image to a place outside of the image.

_________
|       |
|       | ____
|  0_o  | |  |
|   |   | |__|
|_______|

Check that the width, height, and x/y offsets are correct numbers inside the image and that the math isn't moving them to be ouside the image area.


问:
Do the following make use of some design patterns?
Given

```<code>class ClassA
{
    void MethodA(ClassB ObjB) {...}
}
</code>```

do the following make use of some design patterns:

```<code>class ClassC: ClassB
{
    void MethodC(ClassA ObjA) {ObjA.MethodA(this);}
}
</code>```

and

```<code>class ClassD
{
    ClassB _objB;
    void MethodC(ClassA ObjA) {ObjA.MethodA(this._objB);}
}
</code>```

?

For example

```<code>Class MyData
{
    int data;
    void Write(BinaryWriter writer){writer.Write(data);};
}
</code>```

Thanks.

答:
It looks like a light version of the Visitor design pattern:

```<code>  using System;
  using System.Text;

  interface IExpressionVisitor
  {
    void Visit(Literal literal);
    void Visit(Addition addition);
  }

  interface IExpression
  {
    void Accept(IExpressionVisitor visitor);
  }

  class Literal : IExpression
  {
    internal double Value { get; set; }

    public Literal(double value)
    {
      this.Value = value;
    }
    public void Accept(IExpressionVisitor visitor)
    {
      visitor.Visit(this);
    }
  }
</code>```

extracted from https://en.wikipedia.org/wiki/Visitor_pattern

Body:
Given

class ClassA
{
    void MethodA(ClassB ObjB) {...}
}

do the following make use of some design patterns:

class ClassC: ClassB
{
    void MethodC(ClassA ObjA) {ObjA.MethodA(this);}
}

and

class ClassD
{
    ClassB _objB;
    void MethodC(ClassA ObjA) {ObjA.MethodA(this._objB);}
}

?

For example

Class MyData
{
    int data;
    void Write(BinaryWriter writer){writer.Write(data);};
}

Thanks.

Body:
It looks like a light version of the Visitor design pattern:

  using System;
  using System.Text;

  interface IExpressionVisitor
  {
    void Visit(Literal literal);
    void Visit(Addition addition);
  }

  interface IExpression
  {
    void Accept(IExpressionVisitor visitor);
  }

  class Literal : IExpression
  {
    internal double Value { get; set; }

    public Literal(double value)
    {
      this.Value = value;
    }
    public void Accept(IExpressionVisitor visitor)
    {
      visitor.Visit(this);
    }
  }

extracted from https://en.wikipedia.org/wiki/Visitor_pattern


问:
How to debug my simple Excel VBA macro?
I'm just trying to check the latest Date cell, which is in Column A, against the current date. If the difference is 30 days, I write a new row.

When I execute, it says I can't call CheckAttendance on Sheet("Occurences"). But why?

```<code>    Option Explicit

    Public LastCell As Long
    Public today As Date

    Function CheckAttendance()

        Dim DaysSinceOcc As Integer

        'returns last occupied row
        LastCell = Cells(Rows.Count, 1).End(xlUp).Row

        'gets current date
        today = Date

        'subtracts last cell in specified column from today's date.
        DaysSinceOcc = today - Cells(LastCell, 1).Value

        'writes what I want written in the cells I want it written in.
        If DaysSinceOcc > 29 Then
            Cells(LastCell, 1).Offset(1, 1) = "winback"
            Cells(LastCell, 1).Offset(1, 2) = -0.5
            Cells(LastCell, 1).Offset(1, 4) = "Earned back 0.5 pts for 30 days perfect attendance (AutoGenerated)"
            Cells(LastCell, 1).Offset(1, 5) = "AUTO"
            Cells(LastCell, 1).Offset(1, 0) = today
        Else

        End If

    End Function

    Sub Attendance()

        Sheets("Occurences").CheckAttendance
        'yes Occurences is suppose to be spelled like that (don't ask)

    End Sub
</code>```

edit: there are probably multiple problems with this. I fixed a lot of things, but then got stuck.

答:
It seems that you want to parametrize your CheckAttendance routine so that it can be called on different worksheets. To do that, make it a Sub that takes a worksheet as parameter. Moreover

qualify you cells and ranges in the code

dim your variables and use Option Explicit

```<code>Option Explicit

Sub CheckAttendance(ws As Worksheet)
    Dim DaysSinceOcc As Long, lastRow As Long, today As Long
    lastRow = ws.Cells(ws.Rows.count, 1).End(xlUp).row

    'gets current date
    today = Date

    'subtracts last cell in specified column from today's date.
    DaysSinceOcc = today - ws.Cells(lastRow, 1).Value2

    'writes what I want written in the cells I want it written in.
    If DaysSinceOcc > 29 Then
        ws.Cells(lastRow + 1, 1) = today
        ws.Cells(lastRow + 1, 2) = "winback"
        ws.Cells(lastRow + 1, 3) = -0.5
        ws.Cells(lastRow + 1, 5) = "Earned back 0.5 pts for 30 days perfect attendance (AutoGenerated)"
        ws.Cells(lastRow + 1, 6) = "AUTO"
    End If
End Sub

Sub Attendance()
    CheckAttendance Sheets("Occurences") ' <-- this is how you call it on any worksheet
End Sub
</code>```

Title: How to debug my simple Excel VBA macro?

Body:
I'm just trying to check the latest Date cell, which is in Column A, against the current date. If the difference is 30 days, I write a new row.

When I execute, it says I can't call CheckAttendance on Sheet("Occurences"). But why?

    Option Explicit

    Public LastCell As Long
    Public today As Date

    Function CheckAttendance()

        Dim DaysSinceOcc As Integer

        'returns last occupied row
        LastCell = Cells(Rows.Count, 1).End(xlUp).Row

        'gets current date
        today = Date

        'subtracts last cell in specified column from today's date.
        DaysSinceOcc = today - Cells(LastCell, 1).Value

        'writes what I want written in the cells I want it written in.
        If DaysSinceOcc > 29 Then
            Cells(LastCell, 1).Offset(1, 1) = "winback"
            Cells(LastCell, 1).Offset(1, 2) = -0.5
            Cells(LastCell, 1).Offset(1, 4) = "Earned back 0.5 pts for 30 days perfect attendance (AutoGenerated)"
            Cells(LastCell, 1).Offset(1, 5) = "AUTO"
            Cells(LastCell, 1).Offset(1, 0) = today
        Else

        End If

    End Function

    Sub Attendance()

        Sheets("Occurences").CheckAttendance
        'yes Occurences is suppose to be spelled like that (don't ask)

    End Sub

edit: there are probably multiple problems with this. I fixed a lot of things, but then got stuck.

Body:
It seems that you want to parametrize your CheckAttendance routine so that it can be called on different worksheets. To do that, make it a Sub that takes a worksheet as parameter. Moreover

qualify you cells and ranges in the code

dim your variables and use Option Explicit

Option Explicit

Sub CheckAttendance(ws As Worksheet)
    Dim DaysSinceOcc As Long, lastRow As Long, today As Long
    lastRow = ws.Cells(ws.Rows.count, 1).End(xlUp).row

    'gets current date
    today = Date

    'subtracts last cell in specified column from today's date.
    DaysSinceOcc = today - ws.Cells(lastRow, 1).Value2

    'writes what I want written in the cells I want it written in.
    If DaysSinceOcc > 29 Then
        ws.Cells(lastRow + 1, 1) = today
        ws.Cells(lastRow + 1, 2) = "winback"
        ws.Cells(lastRow + 1, 3) = -0.5
        ws.Cells(lastRow + 1, 5) = "Earned back 0.5 pts for 30 days perfect attendance (AutoGenerated)"
        ws.Cells(lastRow + 1, 6) = "AUTO"
    End If
End Sub

Sub Attendance()
    CheckAttendance Sheets("Occurences") ' <-- this is how you call it on any worksheet
End Sub


问:
Update float array from C++ native plugin
I am seeing a pretty bizarre issue while trying to pass an array from C++ to C#. I am using Marshal.Copy (specifically: https://msdn.microsoft.com/en-us/library/a53bd6cz(v=vs.110).aspx).

Problem: float array from C++ to C# is yielding a few NaN's in the resulting array.
(Note: I am working in the context of the Unity game engine)

Code

Example C++ code:

```<code>extern "C" bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API getSomeFloats(float** points, int* count) {
        std::vector<float> results;
        std::vector<SOME_TYPE> key_points = <SOME_POINTS>

        for (auto iter = key_points.begin(); iter < key_points.end(); iter++) {
            results.push_back(static_cast<float>(iter->pt.x));
            results.push_back(static_cast<float>(iter->pt.y));
        }

        *points = results.data();
        *count = results.size();

        //<Print results to csv here>

        return true;
}
</code>```

Example C# code:

```<code>[DllImport("NativePlugin")]
private static extern bool getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

private static float[] getFloatArrayFromNative() {
        IntPtr ptrResultItems = IntPtr.Zero;
        int resultItemsLength = 0;
        bool success = getSomeFloats (ref ptrResultItems, ref resultItemsLength);
        float[] resultItems = null;
        if (success) {
            // Load the results into a managed array.
            resultItems = new float[resultItemsLength];
            Marshal.Copy (ptrResultItems
                , resultItems
                , 0
                , resultItemsLength);

            // <PRINT out resultItems to csv here>

            return resultItems;
        } else {
            Debug.Log ("Something went wrong getting some floats");
            return new float[] { -1, -2 };
        }
    }
</code>```

Example Ouput:
Take the following example:
C++ output (print_out.csv):

123, 456, 789

C# output (print_out_cs.csv):

123, NaN, 789

I'm completely stumped on this one. I just don't understand why only some (roughly 7/100) floats are returning NaN. Does anyone have any advice/insight that might help?

Thanks!

答:
Found few problems in your code:

1. std::vector<float> results; is declared on the stack. It will be gone by the time the function has returned.  Declare it as a pointer

```<code>std::vector<float> *results = new std::vector<float>(10);
</code>```

but make sure to also declare a function that will free it on the C++ side.

2.The function parameter do not match.

Your C++:

```<code>getSomeFloats(float** points, int* count, CameraPose* pose)
</code>```

Your C#:

```<code>getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);
</code>```

You either have to remove CameraPose* pose from the C++ side or add IntPtr pose to the C# side.

3. The use of UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API.

You don't need that. This is used when you want to use Unity's built in functions such as GL.IssuePluginEvent. You are not using it in this case.

This should do it:

```<code>#define DLLExport __declspec(dllexport)

extern "C"
{
    DLLExport void fillArrayNative(float* data, int count, int* outValue)
    {
    }
}
</code>```

4.C# has a garbage collector that moves variables around in the memory. You must pin C# array if you want to modify it from C++ side. You only need to pin C# array. Another option is to allocate the array on C++ side, return it to C# copy it to a temporary variable on the C# side then delete it on the C++ side.

5.Copy the result back to the array instead of assigning it.

Recommended method:

There are just many ways to do this and some of them are extremely slow. If you want to use Marshal.Copy, you have to allocate the array on the C++ side or else you will run into some undefined behavior.

The fastest and the most efficient way to do this is to allocate the array on the C# side as a global variable. Pass the array and its length to the native side. Also pass a third parameter which C++ can use to tell C# the amount of index that has been updated or written to.

This is much more better than creating new array, copying it to C# variable then destroying it each time the function is called.

This is what you should be using:

C++:

```<code>#define DLLExport __declspec(dllexport)

extern "C"
{
    DLLExport void fillArrayNative(float* data, int count, int* outValue)
    {
        std::vector<float> results;
        for (int i = 0; i < count; i++)
        {
            //Fill the array
            data[i] = results[i];
        }
        *outValue = results.size();
    }
}
</code>```

You can also use:  std::copy ( data, data+count, results.begin() ); instead of loop to copy the data too.

C#:

```<code>[DllImport("NativePlugin", CallingConvention = CallingConvention.Cdecl)]
private static extern void fillArrayNative(IntPtr data, int count, out int outValue);

public unsafe void getFillArrayNative(float[] outArray, int count, out int outValue)
{
    //Pin Memory
    fixed (float* p = outArray)
    {
        fillArrayNative((IntPtr)p, count, out outValue);
    }
}
</code>```

Usage:

```<code>const int arraySize = 44500;
float[] arrayToFill = new float[arraySize];

void Start()
{
    int length = arrayToFill.Length;
    int filledAmount = 0;
    getFillArrayNative(arrayToFill, length, out filledAmount);

    //You can then loop through it with with the returned filledAmount
    for (int i = 0; i < filledAmount; i++)
    {
        //Do something with arrayToFill[i]
    }
}
</code>```

This is just an example and it is faster than all other methods I've used before. Avoid doing it the way you are currently doing it with Marshal.Copy. If you still want to do it your way or use Marshal.Copy then here is the appropriate way to do it which requires allocation, copying data and de-allocating memory in each call.

ContentLicense: CC BY-SA 4.0

Body:
I am seeing a pretty bizarre issue while trying to pass an array from C++ to C#. I am using Marshal.Copy (specifically: https://msdn.microsoft.com/en-us/library/a53bd6cz(v=vs.110).aspx).

Problem: float array from C++ to C# is yielding a few NaN's in the resulting array.
(Note: I am working in the context of the Unity game engine)

Code

Example C++ code:

extern "C" bool UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API getSomeFloats(float** points, int* count) {
        std::vector<float> results;
        std::vector<SOME_TYPE> key_points = <SOME_POINTS>

        for (auto iter = key_points.begin(); iter < key_points.end(); iter++) {
            results.push_back(static_cast<float>(iter->pt.x));
            results.push_back(static_cast<float>(iter->pt.y));
        }

        *points = results.data();
        *count = results.size();

        //<Print results to csv here>

        return true;
}

Example C# code:

[DllImport("NativePlugin")]
private static extern bool getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

private static float[] getFloatArrayFromNative() {
        IntPtr ptrResultItems = IntPtr.Zero;
        int resultItemsLength = 0;
        bool success = getSomeFloats (ref ptrResultItems, ref resultItemsLength);
        float[] resultItems = null;
        if (success) {
            // Load the results into a managed array.
            resultItems = new float[resultItemsLength];
            Marshal.Copy (ptrResultItems
                , resultItems
                , 0
                , resultItemsLength);

            // <PRINT out resultItems to csv here>

            return resultItems;
        } else {
            Debug.Log ("Something went wrong getting some floats");
            return new float[] { -1, -2 };
        }
    }

Example Ouput:
Take the following example:
C++ output (print_out.csv):

123, 456, 789

C# output (print_out_cs.csv):

123, NaN, 789

I'm completely stumped on this one. I just don't understand why only some (roughly 7/100) floats are returning NaN. Does anyone have any advice/insight that might help?

Thanks!

Body:
Found few problems in your code:

1. std::vector<float> results; is declared on the stack. It will be gone by the time the function has returned.  Declare it as a pointer

std::vector<float> *results = new std::vector<float>(10);

but make sure to also declare a function that will free it on the C++ side.

2.The function parameter do not match.

Your C++:

getSomeFloats(float** points, int* count, CameraPose* pose)

Your C#:

getSomeFloats (ref IntPtr ptrResultItems, ref int resultItemsLength);

You either have to remove CameraPose* pose from the C++ side or add IntPtr pose to the C# side.

3. The use of UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API.

You don't need that. This is used when you want to use Unity's built in functions such as GL.IssuePluginEvent. You are not using it in this case.

This should do it:

#define DLLExport __declspec(dllexport)

extern "C"
{
    DLLExport void fillArrayNative(float* data, int count, int* outValue)
    {
    }
}

4.C# has a garbage collector that moves variables around in the memory. You must pin C# array if you want to modify it from C++ side. You only need to pin C# array. Another option is to allocate the array on C++ side, return it to C# copy it to a temporary variable on the C# side then delete it on the C++ side.

5.Copy the result back to the array instead of assigning it.

Recommended method:

There are just many ways to do this and some of them are extremely slow. If you want to use Marshal.Copy, you have to allocate the array on the C++ side or else you will run into some undefined behavior.

The fastest and the most efficient way to do this is to allocate the array on the C# side as a global variable. Pass the array and its length to the native side. Also pass a third parameter which C++ can use to tell C# the amount of index that has been updated or written to.

This is much more better than creating new array, copying it to C# variable then destroying it each time the function is called.

This is what you should be using:

C++:

#define DLLExport __declspec(dllexport)

extern "C"
{
    DLLExport void fillArrayNative(float* data, int count, int* outValue)
    {
        std::vector<float> results;
        for (int i = 0; i < count; i++)
        {
            //Fill the array
            data[i] = results[i];
        }
        *outValue = results.size();
    }
}

You can also use:  std::copy ( data, data+count, results.begin() ); instead of loop to copy the data too.

C#:

[DllImport("NativePlugin", CallingConvention = CallingConvention.Cdecl)]
private static extern void fillArrayNative(IntPtr data, int count, out int outValue);

public unsafe void getFillArrayNative(float[] outArray, int count, out int outValue)
{
    //Pin Memory
    fixed (float* p = outArray)
    {
        fillArrayNative((IntPtr)p, count, out outValue);
    }
}

Usage:

const int arraySize = 44500;
float[] arrayToFill = new float[arraySize];

void Start()
{
    int length = arrayToFill.Length;
    int filledAmount = 0;
    getFillArrayNative(arrayToFill, length, out filledAmount);

    //You can then loop through it with with the returned filledAmount
    for (int i = 0; i < filledAmount; i++)
    {
        //Do something with arrayToFill[i]
    }
}

This is just an example and it is faster than all other methods I've used before. Avoid doing it the way you are currently doing it with Marshal.Copy. If you still want to do it your way or use Marshal.Copy then here is the appropriate way to do it which requires allocation, copying data and de-allocating memory in each call.


问:
PyYAML interprets string as timestamp
It looks as though PyYAML interprets the string 10:01 as a duration in seconds:

```<code>import yaml
>>> yaml.load("time: 10:01")
{'time': 601}
</code>```

The official documentation does not reflect that: PyYAML documentation

Any suggestion how to read 10:01 as a string?

答:
If you wish to monkeypatch the pyyaml library so it does not have this behavior (since there is no neat way to do this), for a resolver of your choice, the code below works. The problem is that the regex that is used for int includes some code to match timestamps even though it looks like there's no spec for this behavior, it was just deemed as a "good practice" for strings like 30:00 or 40:11:11:11:11 to be treated as integers.

```<code>import yaml
import re

def partition_list(somelist, predicate):
    truelist = []
    falselist = []
    for item in somelist:
        if predicate(item):
            truelist.append(item)
        else:
            falselist.append(item)
    return truelist, falselist

@classmethod
def init_implicit_resolvers(cls):
    """
    creates own copy of yaml_implicit_resolvers from superclass
    code taken from add_implicit_resolvers; this should be refactored elsewhere
    """
    if not 'yaml_implicit_resolvers' in cls.__dict__:
        implicit_resolvers = {}
        for key in cls.yaml_implicit_resolvers:
            implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
        cls.yaml_implicit_resolvers = implicit_resolvers

@classmethod
def remove_implicit_resolver(cls, tag, verbose=False):
    cls.init_implicit_resolvers()
    removed = {}
    for key in cls.yaml_implicit_resolvers:
        v = cls.yaml_implicit_resolvers[key]
        vremoved, v2 = partition_list(v, lambda x: x[0] == tag)
        if vremoved:
            cls.yaml_implicit_resolvers[key] = v2
            removed[key] = vremoved
    return removed

@classmethod
def _monkeypatch_fix_int_no_timestamp(cls):
    bad = '|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+'
    for key in cls.yaml_implicit_resolvers:
        v = cls.yaml_implicit_resolvers[key]
        vcopy = v[:]
        n = 0
        for k in xrange(len(v)):
            if v[k][0] == 'tag:yaml.org,2002:int' and bad in v[k][1].pattern:
                n += 1
                p = v[k][1]
                p2 = re.compile(p.pattern.replace(bad,''), p.flags)
                vcopy[k] = (v[k][0], p2)
        if n > 0:
            cls.yaml_implicit_resolvers[key] = vcopy

yaml.resolver.Resolver.init_implicit_resolvers = init_implicit_resolvers
yaml.resolver.Resolver.remove_implicit_resolver = remove_implicit_resolver
yaml.resolver.Resolver._monkeypatch_fix_int_no_timestamp = _monkeypatch_fix_int_no_timestamp
</code>```

Then if you do this:

```<code>class MyResolver(yaml.resolver.Resolver):
    pass

t1 = MyResolver.remove_implicit_resolver('tag:yaml.org,2002:timestamp')
MyResolver._monkeypatch_fix_int_no_timestamp()

class MyLoader(yaml.SafeLoader, MyResolver):
    pass

text = '''
a: 3
b: 30:00
c: 30z
d: 40:11:11:11
'''

print yaml.safe_load(text)
print yaml.load(text, Loader=MyLoader)
</code>```

then it prints

```<code>{'a': 3, 'c': '30z', 'b': 1800, 'd': 8680271}
{'a': 3, 'c': '30z', 'b': '30:00', 'd': '40:11:11:11'}
</code>```

showing that the default yaml behavior has been left unchanged but your private loader class handles these strings sanely.

Title: PyYAML interprets string as timestamp

Body:
It looks as though PyYAML interprets the string 10:01 as a duration in seconds:

import yaml
>>> yaml.load("time: 10:01")
{'time': 601}

The official documentation does not reflect that: PyYAML documentation

Any suggestion how to read 10:01 as a string?

Body:
If you wish to monkeypatch the pyyaml library so it does not have this behavior (since there is no neat way to do this), for a resolver of your choice, the code below works. The problem is that the regex that is used for int includes some code to match timestamps even though it looks like there's no spec for this behavior, it was just deemed as a "good practice" for strings like 30:00 or 40:11:11:11:11 to be treated as integers.

import yaml
import re

def partition_list(somelist, predicate):
    truelist = []
    falselist = []
    for item in somelist:
        if predicate(item):
            truelist.append(item)
        else:
            falselist.append(item)
    return truelist, falselist

@classmethod
def init_implicit_resolvers(cls):
    """
    creates own copy of yaml_implicit_resolvers from superclass
    code taken from add_implicit_resolvers; this should be refactored elsewhere
    """
    if not 'yaml_implicit_resolvers' in cls.__dict__:
        implicit_resolvers = {}
        for key in cls.yaml_implicit_resolvers:
            implicit_resolvers[key] = cls.yaml_implicit_resolvers[key][:]
        cls.yaml_implicit_resolvers = implicit_resolvers

@classmethod
def remove_implicit_resolver(cls, tag, verbose=False):
    cls.init_implicit_resolvers()
    removed = {}
    for key in cls.yaml_implicit_resolvers:
        v = cls.yaml_implicit_resolvers[key]
        vremoved, v2 = partition_list(v, lambda x: x[0] == tag)
        if vremoved:
            cls.yaml_implicit_resolvers[key] = v2
            removed[key] = vremoved
    return removed

@classmethod
def _monkeypatch_fix_int_no_timestamp(cls):
    bad = '|[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+'
    for key in cls.yaml_implicit_resolvers:
        v = cls.yaml_implicit_resolvers[key]
        vcopy = v[:]
        n = 0
        for k in xrange(len(v)):
            if v[k][0] == 'tag:yaml.org,2002:int' and bad in v[k][1].pattern:
                n += 1
                p = v[k][1]
                p2 = re.compile(p.pattern.replace(bad,''), p.flags)
                vcopy[k] = (v[k][0], p2)
        if n > 0:
            cls.yaml_implicit_resolvers[key] = vcopy

yaml.resolver.Resolver.init_implicit_resolvers = init_implicit_resolvers
yaml.resolver.Resolver.remove_implicit_resolver = remove_implicit_resolver
yaml.resolver.Resolver._monkeypatch_fix_int_no_timestamp = _monkeypatch_fix_int_no_timestamp

Then if you do this:

class MyResolver(yaml.resolver.Resolver):
    pass

t1 = MyResolver.remove_implicit_resolver('tag:yaml.org,2002:timestamp')
MyResolver._monkeypatch_fix_int_no_timestamp()

class MyLoader(yaml.SafeLoader, MyResolver):
    pass

text = '''
a: 3
b: 30:00
c: 30z
d: 40:11:11:11
'''

print yaml.safe_load(text)
print yaml.load(text, Loader=MyLoader)

then it prints

{'a': 3, 'c': '30z', 'b': 1800, 'd': 8680271}
{'a': 3, 'c': '30z', 'b': '30:00', 'd': '40:11:11:11'}

showing that the default yaml behavior has been left unchanged but your private loader class handles these strings sanely.


问:
Vulkan renderpasses - Using an attachment as a texture
From the spec, under VkFramebufferCreateInfo:

Image subresources used as attachments must not be used via any non-attachment usage for the duration of a render pass instance.

Does this mean using an attached image as a texture in a subsequent pass is not allowed?

This is confusing, since the application must update subpassInput descriptors manually, which seems to imply:

it is the only descriptor that may be updated with an attached image during a renderpass instance

or the real meaning of that passage is to restrict the scope to just "rendering" as opposed to resource transfer, etc...

答:
Input attachments are attachments, and therefore using them is not a "non-attachment use". Just because they happen to also involve a descriptor does not mean that they're not still attachments.

Does this mean using an attached image as a texture in a subsequent pass is not allowed?

If by "as a texture", you mean by binding it to a non-input attachment descriptor, then yes, that is not allowed in the same render pass instance where that image subresource is being used as an attachment.

Input attachments of course are not "textures"; they're attachments.


问:
Iframe tag not showing content in html
I am attempting to have a website inside my website using the iframe tag like this:

```<code><iframe height="100%" width="100%" src="http://www.example.com/">
    <p>Your browser does not support the iframe element</p>
</iframe>
</code>```

Unfortunately, this just shows a box or border. I would like it to show "example.com" inside my website.

Thanks in advance.

答:
Works for me.

https://jsfiddle.net/1a7y6n37/

Tested with:

```<code><iframe height="100%" width="100%" src="https://www.w3schools.com">
    <p>Your browser does not support the iframe element</p>
</iframe>
</code>```

Title: Iframe tag not showing content in html

Body:
I am attempting to have a website inside my website using the iframe tag like this:

Your browser does not support the iframe element

Unfortunately, this just shows a box or border. I would like it to show "example.com" inside my website.

Thanks in advance.

Body:
Works for me.

https://jsfiddle.net/1a7y6n37/

Tested with:

<iframe height="100%" width="100%" src="https://www.w3schools.com">
    <p>Your browser does not support the iframe element</p>
</iframe>


问:
Applying an ellipsis to multiline text
Is there a solution to add ellipsis on last line inside a div with a fluid height (20%)?

I found the -webkit-line-clamp function in CSS, but in my case the line number will be depending on window size.

p {
    width:100%;
    height:20%;
    background:red;
    position:absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.</p></code>```

I have this JSFiddle to illustrate the issue.
https://jsfiddle.net/96knodm6/

答:
To bad CSS doesn't support cross-browser multiline clamping, only webkit seems to be pushing it.

You could try and use a simple Javascript ellipsis library like Ellipsity on github the source code is very clean and small so if you do need to make any additional changes it should be quite easy.

https://github.com/Xela101/Ellipsity

Title: Applying an ellipsis to multiline text

Body:
Is there a solution to add ellipsis on last line inside a div with a fluid height (20%)?

I found the -webkit-line-clamp function in CSS, but in my case the line number will be depending on window size.

p {
    width:100%;
    height:20%;
    background:red;
    position:absolute;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendreritLorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed dui felis. Vivamus vitae pharetra nisl, eget fringilla elit. Ut nec est sapien. Aliquam dignissim velit sed nunc imperdiet cursus. Proin arcu diam, tempus ac vehicula a, dictum quis nibh. Maecenas vitae quam ac mi venenatis vulputate. Suspendisse fermentum suscipit eros, ac ultricies leo sagittis quis. Nunc sollicitudin lorem eget eros eleifend facilisis. Quisque bibendum sem at bibendum suscipit. Nam id tellus mi. Mauris vestibulum, eros ac ultrices lacinia, justo est faucibus ipsum, sed sollicitudin sapien odio sed est. In massa ipsum, bibendum quis lorem et, volutpat ultricies nisi. Maecenas scelerisque sodales ipsum a hendrerit.

I have this JSFiddle to illustrate the issue.
https://jsfiddle.net/96knodm6/


问:
How to improve this tcp socket communication?
I'm trying to implement a micro-benchmark for tcp socket communication though a loop of a send and receive messages. However, I've got a high latency compared to the standards latency of TCP socket in some diagrams.
How can I improve my code ?

Server Side

```<code>    DataOutputStream output = new DataOutputStream(this.clientSocket.getOutputStream());
    DataInputStream input = new DataInputStream(this.clientSocket.getInputStream());
    int j = 0;
    while (j < loop) {
        output.write(bytes);
        input.read(new byte[input.readInt()] );
        j++;
    }
</code>```

Client Side

```<code>    DataOutputStream output = new DataOutputStream(socket.getOutputStream());
    DataInputStream input = new DataInputStream(socket.getInputStream());
    final long startTime = System.nanoTime();
    int j = 0;
    while (j < loop) {
         input.read(new byte[input.readInt()]);
         output.write(bytes);
    j++;
    }

    final long endTime = System.nanoTime();
    final double difference = (endTime - startTime) / 1e6;
    LOGGER.info("Latency:"+ difference/loop);
</code>```

答:
Your code isn't even correct, so the results so far are meaningless. Quite possibly your senders are getting stuck because the application protocol isn't correctly implemented.

Nowhere do you actually write an int, yet both sides:

read one int and

assume it is a length word for the following message, which they then

can fail to read completely because they are ignoring the result of read().

A correct version of the same thing must start with somebody, apparently the server, writing the initial int.

You are also using unbuffered I/O, which is pretty expensive in the readInt() and writeInt() cases.

You are also creating tons of garbage at both ends unnecessarily.

Server:

```<code>DataOutputStream output = new DataOutputStream(ne w BufferedOutputStream(this.clientSocket.getOutputStream()));
DataInputStream input = new DataInputStream(new ByufferedInputStream(this.clientSocket.getInputStream()));
byte[] message - new byte[8192]; // or whatever
int msgLen = message.length;
while (j < loop)
{
    output.writeInt(msgLen);
    output.write(message);
    output.flush();
    int replyLen = input.readInt();
    input.readFully(message, 0, replyLen); // assuming replyLen <= msgLen
    j++;
}
</code>```

Client (after constructing the data streams the same way and using the same message and msgLen variables:

```<code>while (j < loop) {
    mgLen = input.readInt();
    input.readFully(message, 0, msgLen); // same assumption as above
    output.writeInt(msgLen);
    output.write(message, 0, msgLen);
    output.flush();
    j++;
}
</code>```

E&OE

Body:
I'm trying to implement a micro-benchmark for tcp socket communication though a loop of a send and receive messages. However, I've got a high latency compared to the standards latency of TCP socket in some diagrams.
How can I improve my code ?

Server Side

    DataOutputStream output = new DataOutputStream(this.clientSocket.getOutputStream());
    DataInputStream input = new DataInputStream(this.clientSocket.getInputStream());
    int j = 0;
    while (j < loop) {
        output.write(bytes);
        input.read(new byte[input.readInt()] );
        j++;
    }

Client Side

    DataOutputStream output = new DataOutputStream(socket.getOutputStream());
    DataInputStream input = new DataInputStream(socket.getInputStream());
    final long startTime = System.nanoTime();
    int j = 0;
    while (j < loop) {
         input.read(new byte[input.readInt()]);
         output.write(bytes);
    j++;
    }

    final long endTime = System.nanoTime();
    final double difference = (endTime - startTime) / 1e6;
    LOGGER.info("Latency:"+ difference/loop);

Body:
Your code isn't even correct, so the results so far are meaningless. Quite possibly your senders are getting stuck because the application protocol isn't correctly implemented.

Nowhere do you actually write an int, yet both sides:

read one int and

assume it is a length word for the following message, which they then

can fail to read completely because they are ignoring the result of read().

A correct version of the same thing must start with somebody, apparently the server, writing the initial int.

You are also using unbuffered I/O, which is pretty expensive in the readInt() and writeInt() cases.

You are also creating tons of garbage at both ends unnecessarily.

Server:

DataOutputStream output = new DataOutputStream(ne w BufferedOutputStream(this.clientSocket.getOutputStream()));
DataInputStream input = new DataInputStream(new ByufferedInputStream(this.clientSocket.getInputStream()));
byte[] message - new byte[8192]; // or whatever
int msgLen = message.length;
while (j < loop)
{
    output.writeInt(msgLen);
    output.write(message);
    output.flush();
    int replyLen = input.readInt();
    input.readFully(message, 0, replyLen); // assuming replyLen <= msgLen
    j++;
}

Client (after constructing the data streams the same way and using the same message and msgLen variables:

while (j < loop) {
    mgLen = input.readInt();
    input.readFully(message, 0, msgLen); // same assumption as above
    output.writeInt(msgLen);
    output.write(message, 0, msgLen);
    output.flush();
    j++;
}

E&OE


问:
Docker swarm - log to rsyslog container
I have a docker swarm with 6 services that I want to have logging to one central logging container.
I have this working in my dev environment (non swarm) - see the docker-compose file below.

When I try to transition the configuration from the dev env to my swarm prod env, it fails.

first I raise the log service:

```<code>docker service create --replicas 1 \
--name logserver \
--network phototankswarm \
--constraint=node.hostname==pi2 \
-p localhost:5514:514 \
kaninfod/pt-syslog
</code>```

This runs up nicely.

Then one of the services (e.g a redis):

```<code>docker service create --replicas 1 \
--name redis \
--network phototankswarm \
--constraint=node.hostname==pi1 \
--log-driver=syslog \
--log-opt syslog-facility="daemon" \
--log-opt tag="rails" \
--log-opt syslog-address="tcp://localhost:5514" \
-p 6379:6379 \
armhf/redis
</code>```

And this fails with:

```<code>starting container failed: Failed to initialize logging driver: dial tcp [::1]:5514: getsockopt: connection refused
</code>```

I had problems with the syslog-address when setting up the dev env...I find it strange that I have to use the localhost rather than the docker dns name of the log container...but en dev it works with localhost.

This is the compose file I use for my dev env:

```<code>version: '3'

services:
  nginx:
    image: nginx
    depends_on:
      - api
      - syslog
    ports:
      - "80:8080"

    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "nginx"
        syslog-address: "tcp://localhost:5514"
    networks:
      - phototankswarm
    env_file: .env.dev
    volumes:
      - ./frontend/nginx/conf.d:/etc/nginx/conf.d
      - ./frontend/public:/www

  db:
    image: mysql
    env_file: .env.dev
    depends_on:
      - syslog
    networks:
      - phototankswarm
    ports:
      - "3306:3306"
    volumes:
      - ./sql/data:/var/lib/mysql
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "mysql"
        syslog-address: "tcp://localhost:5514"

  redis:
    image: redis
    depends_on:
      - syslog
    networks:
      - phototankswarm
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "redis"
        syslog-address: "tcp://localhost:5514"

  api:
    image: pt-rails
    env_file: .env.dev
    networks:
      - phototankswarm
    command: >
      sh -c '
      bundle exec sidekiq -d && bundle exec rails s -p 3000 -b 0.0.0.0
      '
    volumes:
      - /Users/martinhinge/Pictures/docker/phototank:/media/phototank
      - ./backend:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - syslog
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "rails"
        syslog-address: "tcp://localhost:5514"

  syslog:
    image: syslog
    ports:
      - "localhost:5514:514"
    networks:
      - phototankswarm
    volumes:
      - /tmp:/var/log/syslog

networks:
  phototankswarm:
</code>```

EDIT

running $ docker run -it --rm --net container:dac082edcd6f hypriot/rpi-alpine-scratch netstat -lnt yields:

```<code>Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.11:35314        0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:514             0.0.0.0:*               LISTEN
tcp        0      0 :::514                  :::*                    LISTEN
</code>```

答:
Change:

```<code>--log-opt syslog-address="tcp://localhost:5514" \
</code>```

to:

```<code>--log-opt syslog-address="tcp://logserver:514" \
</code>```

Networking between containers will use DNS based discovery as long as they are running on the same network. Localhost inside a container is a separate namespace from the localhost on the docker host outside the container, so the container will not see ports published on the docker host with the loopback address. You may be able to connect to your docker host by it's hostname instead of localhost. However, container-to-container networking is more portable.

The only reason I can think that this would work in dev with localhost is if your service is using the host network mode, rather than being connected to the overlay network.

Title: Docker swarm - log to rsyslog container

Body:
I have a docker swarm with 6 services that I want to have logging to one central logging container.
I have this working in my dev environment (non swarm) - see the docker-compose file below.

When I try to transition the configuration from the dev env to my swarm prod env, it fails.

first I raise the log service:

docker service create --replicas 1 \
--name logserver \
--network phototankswarm \
--constraint=node.hostname==pi2 \
-p localhost:5514:514 \
kaninfod/pt-syslog

This runs up nicely.

Then one of the services (e.g a redis):

docker service create --replicas 1 \
--name redis \
--network phototankswarm \
--constraint=node.hostname==pi1 \
--log-driver=syslog \
--log-opt syslog-facility="daemon" \
--log-opt tag="rails" \
--log-opt syslog-address="tcp://localhost:5514" \
-p 6379:6379 \
armhf/redis

And this fails with:

starting container failed: Failed to initialize logging driver: dial tcp [::1]:5514: getsockopt: connection refused

I had problems with the syslog-address when setting up the dev env...I find it strange that I have to use the localhost rather than the docker dns name of the log container...but en dev it works with localhost.

This is the compose file I use for my dev env:

version: '3'

services:
  nginx:
    image: nginx
    depends_on:
      - api
      - syslog
    ports:
      - "80:8080"

    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "nginx"
        syslog-address: "tcp://localhost:5514"
    networks:
      - phototankswarm
    env_file: .env.dev
    volumes:
      - ./frontend/nginx/conf.d:/etc/nginx/conf.d
      - ./frontend/public:/www

  db:
    image: mysql
    env_file: .env.dev
    depends_on:
      - syslog
    networks:
      - phototankswarm
    ports:
      - "3306:3306"
    volumes:
      - ./sql/data:/var/lib/mysql
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "mysql"
        syslog-address: "tcp://localhost:5514"

  redis:
    image: redis
    depends_on:
      - syslog
    networks:
      - phototankswarm
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "redis"
        syslog-address: "tcp://localhost:5514"

  api:
    image: pt-rails
    env_file: .env.dev
    networks:
      - phototankswarm
    command: >
      sh -c '
      bundle exec sidekiq -d && bundle exec rails s -p 3000 -b 0.0.0.0
      '
    volumes:
      - /Users/martinhinge/Pictures/docker/phototank:/media/phototank
      - ./backend:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - db
      - redis
      - syslog
    logging:
      driver: syslog
      options:
        syslog-facility: "daemon"
        tag: "rails"
        syslog-address: "tcp://localhost:5514"

  syslog:
    image: syslog
    ports:
      - "localhost:5514:514"
    networks:
      - phototankswarm
    volumes:
      - /tmp:/var/log/syslog

networks:
  phototankswarm:

EDIT

running $ docker run -it --rm --net container:dac082edcd6f hypriot/rpi-alpine-scratch netstat -lnt yields:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.11:35314        0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:514             0.0.0.0:*               LISTEN
tcp        0      0 :::514                  :::*                    LISTEN

Body:
Change:

--log-opt syslog-address="tcp://localhost:5514" \

to:

--log-opt syslog-address="tcp://logserver:514" \

Networking between containers will use DNS based discovery as long as they are running on the same network. Localhost inside a container is a separate namespace from the localhost on the docker host outside the container, so the container will not see ports published on the docker host with the loopback address. You may be able to connect to your docker host by it's hostname instead of localhost. However, container-to-container networking is more portable.

The only reason I can think that this would work in dev with localhost is if your service is using the host network mode, rather than being connected to the overlay network.


问:
How to add an observer in Objective-C and fire a Notification in Swift 3
I have a notification observer in an Objective C file and I want to fire a notification in a Swift 3 file. Since in Objective C the notification name is a NSString but in Swift 3 it's Notification.Name, how can I get the Obj-C observer to catch the Swift fire?

Swift Trigger

```<code>NotificationCenter.default.post(name: .notificationName, object: nil, userInfo: nil)

extension Notification.Name {
    static let notificationName = Notification.Name("Test")
}
</code>```

Obj-C Observer

```<code>[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(displayError:)
                                      name:"Test"
                                      object:nil];
</code>```

答:
You would trigger the notification like this:</p>

```<code>NotificationCenter.default.post(
    name: Notification.Name(rawValue: "SomeNotification"),
    object: nil,
    userInfo: nil
)
</code>```

Body:
I have a notification observer in an Objective C file and I want to fire a notification in a Swift 3 file. Since in Objective C the notification name is a NSString but in Swift 3 it's Notification.Name, how can I get the Obj-C observer to catch the Swift fire?

Swift Trigger

NotificationCenter.default.post(name: .notificationName, object: nil, userInfo: nil)

extension Notification.Name {
    static let notificationName = Notification.Name("Test")
}

Obj-C Observer

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(displayError:)
                                      name:"Test"
                                      object:nil];

Body:
You would trigger the notification like this:

NotificationCenter.default.post(
    name: Notification.Name(rawValue: "SomeNotification"),
    object: nil,
    userInfo: nil
)


问:
jQuery attribute change, run again
Hi there,

I'm having an issue with jQuery. I have an element, which contents I replace. However, I also replace the data-action attribute with another value. However, when I click on the element again, it still runs the code with the previous data-action attribute value. Is there a way to force jQuery to use the new one? Is this what I want even possible?

I Tried .data(), but with the same result.

jQuery

```<code>$('#selector li').click(function() {
    var action = $(this).data("action");
    var item = $(".item").data("id");
    $.ajax({
        type: "POST",
        data: "ticket=" + item,
        url: "/run/" + action,
        success: function(data) {
            var jsonObj = jQuery.parseJSON(data);

            if (jsonObj.valid == 'true') {
                if (action == 'pick') {
                    $('li[data-action=pick]').html('Release').attr('data-action', 'release');
                } else if (action == 'release') {
                    $('li[data-action=release]').html('Pick').attr('data-action', 'pick');
                }
            }
        }
    });
});
</code>```

HTML

```<code> <li data-action="pick">Pick</li>
</code>```

Edit: I just think my previous comment was a bit unclear. I Want to change the attribute, which it does. However, when I click the element again, it still recognizes the previous attribute, and not the new one, thus not running the correct action.

答:
As I pointed on comment:

try to use .data('action' , 'release') instead of .attr('data-action',
  'release') and sure same for 'pick'

You can take a look at This Answer  specially the part of don't intermix .data and .attr() calls. Use one or the other.

And while you'll use .html sure you'll need to Event binding on dynamically created elements?

```<code>$(document).on('click','#selector li',function(){
   // code here
});
</code>```

Title: jQuery attribute change, run again

Body:
Hi there,

I'm having an issue with jQuery. I have an element, which contents I replace. However, I also replace the data-action attribute with another value. However, when I click on the element again, it still runs the code with the previous data-action attribute value. Is there a way to force jQuery to use the new one? Is this what I want even possible?

I Tried .data(), but with the same result.

jQuery

$('#selector li').click(function() {
    var action = $(this).data("action");
    var item = $(".item").data("id");
    $.ajax({
        type: "POST",
        data: "ticket=" + item,
        url: "/run/" + action,
        success: function(data) {
            var jsonObj = jQuery.parseJSON(data);

            if (jsonObj.valid == 'true') {
                if (action == 'pick') {
                    $('li[data-action=pick]').html('Release').attr('data-action', 'release');
                } else if (action == 'release') {
                    $('li[data-action=release]').html('Pick').attr('data-action', 'pick');
                }
            }
        }
    });
});

HTML

Pick

Edit: I just think my previous comment was a bit unclear. I Want to change the attribute, which it does. However, when I click the element again, it still recognizes the previous attribute, and not the new one, thus not running the correct action.

Body:
As I pointed on comment:

try to use .data('action' , 'release') instead of .attr('data-action',
  'release') and sure same for 'pick'

You can take a look at This Answer  specially the part of don't intermix .data and .attr() calls. Use one or the other.

And while you'll use .html sure you'll need to Event binding on dynamically created elements?

$(document).on('click','#selector li',function(){
   // code here
});


问:
runtime error 5981 on Office/excel 2010 fresh installation
I've created macro in excel 2013 where I point some data from excel to Word (via word template).
in excel 2013 everything works perfectly, but now I have to run this excel also in older company PC where is installed only M$ Office 2010/win7 - fresh installation.

```<code>Set objDoc = objWord.Documents.Add(Template:=ThisWorkbook.Sheets("Data").Range("O1").Value & ThisWorkbook.Sheets("Data").Range("G2").Value)
</code>```

in this excel 2010 I get run-time error  5981 (application-defined or object-defined error).

in cell "O1" is file folder where are this excel + word templates saved
cell "G2" contain info which template should be used (according to dropdown selection).

update: I've checked this on other PC with office 2010 and it works. Probably some add-in/library  is not working correctly, but idk how to check it.

答:
The error is because when you open the word template the view is protected.
Solution: disable protected view in microsotf word
Go to options, trusted center, protected view disable</p>

Body:
I've created macro in excel 2013 where I point some data from excel to Word (via word template).
in excel 2013 everything works perfectly, but now I have to run this excel also in older company PC where is installed only M$ Office 2010/win7 - fresh installation.

Set objDoc = objWord.Documents.Add(Template:=ThisWorkbook.Sheets("Data").Range("O1").Value & ThisWorkbook.Sheets("Data").Range("G2").Value)

in this excel 2010 I get run-time error  5981 (application-defined or object-defined error).

in cell "O1" is file folder where are this excel + word templates saved
cell "G2" contain info which template should be used (according to dropdown selection).

update: I've checked this on other PC with office 2010 and it works. Probably some add-in/library  is not working correctly, but idk how to check it.


问:
How to create a multidimensional array with variable length
I'd like to create a matrix (same height and width) with a variable size, meaning that height and width depend on a variable. Now I know how to reserve store with malloc/calloc, but I can't figure out how to use malloc to create a two-dimensional array.
Or is there a different way to solve my problem?
Thanks in advance!</p>

答:
I can't figure out how to use malloc to create a two-dimensional array.

```<code>// Example of a 2D array.  malloc() cannot create this.
int TwoD[height][width];
</code>```

malloc() can allocate memory for an int, an array, etc.  It can not create an array.  The result of malloc() is a pointer.  So start with a pointer to a 2D array.

```<code>// C99, C11
int (*a)[height][width];
</code>```

Allocate memory for a

```<code>a = malloc(sizeof *a);
assert(a); // Insure NULL was not retuned.
</code>```

Use the memory

```<code>(*a)[0][0] = 1;
(*a)[0][1] = 2;
// ...
(*a)[height-1][width-1] = height*width;
</code>```

Free when done

```<code>free(a);
</code>```

Body:
I can't figure out how to use malloc to create a two-dimensional array.

// Example of a 2D array.  malloc() cannot create this.
int TwoD[height][width];

malloc() can allocate memory for an int, an array, etc.  It can not create an array.  The result of malloc() is a pointer.  So start with a pointer to a 2D array.

// C99, C11
int (*a)[height][width];

Allocate memory for a

a = malloc(sizeof *a);
assert(a); // Insure NULL was not retuned.

Use the memory

(*a)[0][0] = 1;
(*a)[0][1] = 2;
// ...
(*a)[height-1][width-1] = height*width;

Free when done

free(a);


答:
```<code>$('[data-action="pick"]').attr('data-action','release');
</code>```

Doesn't work as you expect, At this point the data value has already been parsed into the jQuery data object from the node attribute.

To modify the data object you must use

```<code>$('[data-action="pick"]').data('action','release');
</code>```

Note that the node attribute will remain unchanged if you wish to select it by the new selector in  the future then apply both methods.

```<code> $('[data-action="pick"]').attr('data-action','release').data('action','release');
</code>```

That will then allow you to select it with $('[data-action="release"]')

See related: how would I store a javascript object as data attribute and edit it

Title: jQuery attribute change, run again

Body:
$('[data-action="pick"]').attr('data-action','release');

Doesn't work as you expect, At this point the data value has already been parsed into the jQuery data object from the node attribute.

To modify the data object you must use

$('[data-action="pick"]').data('action','release');

Note that the node attribute will remain unchanged if you wish to select it by the new selector in  the future then apply both methods.

 $('[data-action="pick"]').attr('data-action','release').data('action','release');

That will then allow you to select it with $('[data-action="release"]')

See related: how would I store a javascript object as data attribute and edit it


问:
Why when a jquery draggable element is removed, I get a wrong count?
I have encountered an unexpected behaviour that occurs when a jquery draggable element is removed. If I do not set a setTimeout then the count of the remaining elements is wrong.

Could someone explain me why I need this delay ?

```<code>$("#mytable tr").draggable({ helper: "clone"});

$('#trash').droppable({
    tolerance: "pointer",
    drop: function(event, ui) {
        ui.draggable.remove();

        alert($('#mytable tr').length);
        // --> this gives a wrong number of rows

        //setTimeout(function(){alert($('#mytable tr').length);},0);
        // --> this gives the right number despite the 0 delay
    }
});
</code>```

http://jsfiddle.net/PBrockmann/ewgevoc5/

答:
Your alert is counting the clone that the draggable item creates when you drag it with your mouse (if you inspect the DOM tree, you can see the new
 element is created as a child of the
 element).

By calling the setTimeout function, it essentially moves the alert to the end of the call stack, which allows the jQuery code to clean up the clone before the alert is called.

Body:
I have encountered an unexpected behaviour that occurs when a jquery draggable element is removed. If I do not set a setTimeout then the count of the remaining elements is wrong.

Could someone explain me why I need this delay ?

$("#mytable tr").draggable({ helper: "clone"});

$('#trash').droppable({
    tolerance: "pointer",
    drop: function(event, ui) {
        ui.draggable.remove();

        alert($('#mytable tr').length);
        // --> this gives a wrong number of rows

        //setTimeout(function(){alert($('#mytable tr').length);},0);
        // --> this gives the right number despite the 0 delay
    }
});

http://jsfiddle.net/PBrockmann/ewgevoc5/

Body:
Your alert is counting the clone that the draggable item creates when you drag it with your mouse (if you inspect the DOM tree, you can see the new <tr> element is created as a child of the <table> element).

By calling the setTimeout function, it essentially moves the alert to the end of the call stack, which allows the jQuery code to clean up the clone before the alert is called.


问:
What is the difference between TPC-C, TPC-E and TPC-H benchmark?
I am getting confused with different types of TPC benchmarks. What are the major differences between TPC-C, TPC-E and TPC-H benchmark? </p>

答:
TPC-C (circa 1992) models an 'old school' OLTP application that looks like a wholesale distributor with a small number of warehouses full of inventory servicing a larger number of retail locations.  In this context it measures 'transactions per minute' (tpmC).  It assumes old-school IT architectures where DRAM is very scarce and as such it relies heavily on disk IO.

TPC-E is a modern OLTP application that models a stock brokerage and uses a much more sophisticated simulated world driven by fluctuating stock prices and emulates a chaotic 'outside world' of customers placing market orders, limit orders and stop-limit orders.  TPC-E assumes modern IT architecture where DRAM and compute resources are more plentiful and therefore it does not rely as much on storage performance.

TPC-H is an OLAP workload that measures query analytics in a 'data warehouse' context.

In a nutshell, TPC-E is good for OLTP, TPC-H is for OLAP and TPC-C is basically obsolete.


问:
Iterative solving for unknowns in a fluids problem
I am a Mechanical engineer with a computer scientist question. This is an example of what the equations I'm working with are like:

x = √((y-z)×2/r)

  z = f×(L/D)×(x/2g)

  f = something crazy with x in it

  etc…(there are more equations with x in it)

The situation is this:

I need r to find x, but I need x to find z. I also need x to find f which is a part of finding z. So I guess a value for x, and then I use that value to find r and f. Then I go back and use the value I found for r and f to find x. I keep doing this until the guess and the calculated are the same.

My question is:

How do I get the computer to do this? I've been using mathcad, but an example in another language like C++ is fine.

答:
The very first thing you should do faced with iterative algorithms is write down on paper the sequence that will result from your idea:

Eg.:

```<code> x_0 = ..., f_0 = ..., r_0 = ...
 x_1 = ..., f_1 = ..., r_1 = ...

 ...

 x_n = ..., f_n = ..., r_n = ...
</code>```

Now, you have an idea of what you should implement (even if you don't know how). If you don't manage to find a closed form expression for one of the x_i, r_i or whatever_i, you will need to solve one dimensional equations numerically. This will imply more work.

Now, for the implementation part, if you never wrote a program, you should seriously ask someone live who can help you (or hire an intern and have him write the code). We cannot help you beginning from scratch with, eg. C programming, but we are willing to help you with specific problems which should arise when you write the program.

Please note that your algorithm is not guaranteed to converge, even if you strongly think there is a unique solution. Solving non linear equations is a difficult subject.

Body:
The very first thing you should do faced with iterative algorithms is write down on paper the sequence that will result from your idea:

Eg.:

 x_0 = ..., f_0 = ..., r_0 = ...
 x_1 = ..., f_1 = ..., r_1 = ...

 ...

 x_n = ..., f_n = ..., r_n = ...

Now, you have an idea of what you should implement (even if you don't know how). If you don't manage to find a closed form expression for one of the x_i, r_i or whatever_i, you will need to solve one dimensional equations numerically. This will imply more work.

Now, for the implementation part, if you never wrote a program, you should seriously ask someone live who can help you (or hire an intern and have him write the code). We cannot help you beginning from scratch with, eg. C programming, but we are willing to help you with specific problems which should arise when you write the program.

Please note that your algorithm is not guaranteed to converge, even if you strongly think there is a unique solution. Solving non linear equations is a difficult subject.


问:
Not equal <> != operator on NULL
Could someone please explain the following behavior in SQL?</p>

```<code>SELECT * FROM MyTable WHERE MyColumn != NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn <> NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn IS NOT NULL (568 Results)
</code>```

答:
We use

```<code>SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';
</code>```

to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string.  To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.

Title: Not equal <> != operator on NULL

Body:
Could someone please explain the following behavior in SQL?

SELECT * FROM MyTable WHERE MyColumn != NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn <> NULL (0 Results)
SELECT * FROM MyTable WHERE MyColumn IS NOT NULL (568 Results)

Body:
We use

SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';

to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string.  To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.


问:
JsDoc Namespace
I'm editing a js file with JsDoc to get a clean documentation.
My structure is quite simple:

```<code>/**
 * Finds an object
 * @param {string} prop - Property
*/

Array.prototype.findObject = function _findObj(prop, val){
    // blablabla
}

function myfunc(plep){
    // does something
}

/**
 * Workshop Namespace
 * @namespace
*/

var Workshop = {};

/**
 * Does something great
 * @param {*} plep - My super param!
*/
Workshop.doIt = myfunc;

/**
 * It works!
 * @param {string} fly - my flying param
*/
Workshop.flyNow = function _flyN (fly){
    // fly!
}
</code>```

However,

Documentation for first function is not displayed.

Workshop namespace IS created

Workshop.doIt is documented only by its description, arguments are not

Workshop.flyNow is well documented

Does anyone know why?

Thanks!

答:
Here's why:

1.

First function is not documented because it does not belong to any recognisable namespace. To fix this issue, you could create a virtual namespace as follows:

/**
 * @namespace Array
 */

And you can improve the documentation of the function as follows:

```<code>/**
 * Finds an object.
 *
 * @param {string} prop Property name.
 * @param {string|number|function|object} val Value.
 *
 * @function findObject
 * @memberof Array#
 */
Array.prototype.findObject = function _findObj ( prop, val ) {
    // blablabla
}
</code>```

With the outcome below

3.

Arguments weren't documented because the JSDoc parser does not recognise Workshop.doIt( ... ) as a function. That can be fixed with the @function or @method tag:

/**
 * Does something great
 * @param {*} plep - My super param!
 *
 * @method
 */
Workshop.doIt = myfunc;

And the result look like this:

Title: JsDoc Namespace

Body:
I'm editing a js file with JsDoc to get a clean documentation.
My structure is quite simple:

/**
 * Finds an object
 * @param {string} prop - Property
*/

Array.prototype.findObject = function _findObj(prop, val){
    // blablabla
}

function myfunc(plep){
    // does something
}

/**
 * Workshop Namespace
 * @namespace
*/

var Workshop = {};

/**
 * Does something great
 * @param {*} plep - My super param!
*/
Workshop.doIt = myfunc;

/**
 * It works!
 * @param {string} fly - my flying param
*/
Workshop.flyNow = function _flyN (fly){
    // fly!
}

However,

Documentation for first function is not displayed.

Workshop namespace IS created

Workshop.doIt is documented only by its description, arguments are not

Workshop.flyNow is well documented

Does anyone know why?

Thanks!

Body:
Here's why:

1.

First function is not documented because it does not belong to any recognisable namespace. To fix this issue, you could create a virtual namespace as follows:

/**
 * @namespace Array
 */

And you can improve the documentation of the function as follows:

/**
 * Finds an object.
 *
 * @param {string} prop Property name.
 * @param {string|number|function|object} val Value.
 *
 * @function findObject
 * @memberof Array#
 */
Array.prototype.findObject = function _findObj ( prop, val ) {
    // blablabla
}

With the outcome below

3.

Arguments weren't documented because the JSDoc parser does not recognise Workshop.doIt( ... ) as a function. That can be fixed with the @function or @method tag:

/**
 * Does something great
 * @param {*} plep - My super param!
 *
 * @method
 */
Workshop.doIt = myfunc;

And the result look like this: