问:
hough transform error in matlab and openCV?
I have been using the Hough transform in my application both using Matlab and OpenCV/labview and found that for some images, the hough transform gave an obviously wrong line fit (consistently)

Here are the test and overlayed images. The angle seem right, but the rho is off.

On the image below, you will see the top image tries to fit a line to the left side of the original image and the bottom image fits a line to the right side of the image.

In Matlab, I call the Hough function through

```<code>[H1D,theta1D,rho1D] = hough(img_1D_dilate,'ThetaResolution',0.2);
</code>```

in C++, i trimmed the OpenCV HoughLines function so I end up with only the part we are filling the accumulator. Note that because my theta resolution is 0.2, I have 900 angles to analyze. The tabSin and tabCos are defined prior to the function so that they are just a sin and cos of the angle.

Note that these routines generally work well, but just for specific cases it performs the way I have shown.

```<code>double start_angle = 60.0;
    double end_angle = 120.0;
    double num_theta = 180;
    int start_ang = num_theta * start_angle/180;
    int end_ang = num_theta * end_angle/180;
    int i,j,n,index;
        for (i = 0;i<numrows;i++)
        {
            for (j = 0;j<numcols;j++)
            {
                    if (img[i*numcols + j] == 100)
                {
                    for (n = 0;n<180;n++)
                    {
                        index = cvRound((j*tabCos[n] + i * tabSin[n])) + (numrho-1)/2;
                        accum[(n+1) * (numrho+2) + index+1]++;
                    }
                }
            }
        }
</code>```

TabCos and tabSin are defined in Labview with this code
int32 i;
float64 theta_prec;
float64 tabSin[180];
float64 tabCos[180];

theta_prec = 1/180*3.14159;
for (i = 0;i<180;i++)
{
tabSin[i] = sin(itheta_prec);
tabCos[i] = cos(itheta_prec);
}

any suggestions would be greatly appreciated

答:
I guess i'll put down the answer to this problem.

I was converting the rho and theta into m and b, then computing the values of x and y from the m and b. I believe this may have caused some precision error somewhere.

this error was fixed by obtaining x and y directly from rho and theta rather than going through m and b.

the function is

```<code>y = -cos(theta)/sin(theta)*x + rho/sin(theta);
</code>```

Body:
I have been using the Hough transform in my application both using Matlab and OpenCV/labview and found that for some images, the hough transform gave an obviously wrong line fit (consistently)

Here are the test and overlayed images. The angle seem right, but the rho is off.

On the image below, you will see the top image tries to fit a line to the left side of the original image and the bottom image fits a line to the right side of the image.

In Matlab, I call the Hough function through

[H1D,theta1D,rho1D] = hough(img_1D_dilate,'ThetaResolution',0.2);

in C++, i trimmed the OpenCV HoughLines function so I end up with only the part we are filling the accumulator. Note that because my theta resolution is 0.2, I have 900 angles to analyze. The tabSin and tabCos are defined prior to the function so that they are just a sin and cos of the angle.

Note that these routines generally work well, but just for specific cases it performs the way I have shown.

double start_angle = 60.0;
    double end_angle = 120.0;
    double num_theta = 180;
    int start_ang = num_theta * start_angle/180;
    int end_ang = num_theta * end_angle/180;
    int i,j,n,index;
        for (i = 0;i<numrows;i++)
        {
            for (j = 0;j<numcols;j++)
            {
                    if (img[i*numcols + j] == 100)
                {
                    for (n = 0;n<180;n++)
                    {
                        index = cvRound((j*tabCos[n] + i * tabSin[n])) + (numrho-1)/2;
                        accum[(n+1) * (numrho+2) + index+1]++;
                    }
                }
            }
        }

TabCos and tabSin are defined in Labview with this code
int32 i;
float64 theta_prec;
float64 tabSin[180];
float64 tabCos[180];

theta_prec = 1/180*3.14159;
for (i = 0;i<180;i++)
{
tabSin[i] = sin(itheta_prec);
tabCos[i] = cos(itheta_prec);
}

any suggestions would be greatly appreciated

Body:
I guess i'll put down the answer to this problem.

I was converting the rho and theta into m and b, then computing the values of x and y from the m and b. I believe this may have caused some precision error somewhere.

this error was fixed by obtaining x and y directly from rho and theta rather than going through m and b.

the function is

y = -cos(theta)/sin(theta)*x + rho/sin(theta);


来源: stackexchange

问:
Is it possible to make a transparent container with only html while keeping text opacity?
I would like to make my container background transparent while keeping the text/image opacity. Is it possible to do this using only html?
Here is my code:</p>

```<code><div class="container">
 <div class="well text-center" >
    <div class="col-md-10"></div>
    <div class="row">

        <div class="col-md-3">
            <a href="#"><img src="images/link/BDSlogo-vert-blue.png" alt="logo"></a>
        </div>
        <div class="col-md-3">
            <a href="#"><img src="images/link/skyjacker.png" alt="logo"></a>
        </div>
        <div class="col-md-3">
            <a href="#"><img src="images/link/magnaflow.png" alt="logo"></a>
        </div>
        <div class="col-md-3">
            <a href="#"><img src="images/link/jeep_poison_spyder_logo.jpeg" alt="logo"></a>
        </div>

    </div>
  </div>
</div>
</code>```

答:
I found my mistake. I needed to change .well {  background-color: transparent;  I'll post my css. Sorry to be vague I was in a bit of a hurry.

.well {

min-height: 20px;

  padding: 19px;

  margin-bottom: 20px;

  background-color: transparent;

  border: 1px solid #e3e3e3;

  border-radius: 4px;

  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);

          box-shadow: inset 0 1px 1px rgba(0, 0, 0, .05);

}

I originally used a color in my chop version of the page, and have now gone back to change all containers to transparent so that my containers would display only the background of my page while keeping the opacity of the text and images used within the containers. By changing the background-color: to transparent  I seem to have solved the problem, I suppose.

ContentLicense: CC BY-SA 3.0


问:
How to check if list contains all the same values?
I have a List[<DataType>] as input. I want to check if the list contains all the same values(not datatype).

Is there inbuilt method or intuitive way in Scala to do this instead of iterating over list and checking.

答: I just had to do this for an unrelated problem, so to improve on the above ever so slightly: lst.tail.forall(_ == lst.head). This avoids checking that the head of the list equals itself, which you already know is true.

ContentLicense: CC BY-SA 4.0


问:
Does an object of a subclass also allocate an object of the parent class?
```<code>Class A
{
    int X {get;set;}
}
Class B : A
{
    int Y {get;set;}
}

B myB;
</code>```

Say for the sake of argument that an object of type A is 4 bytes and an object of type B is 4 bytes.

B is allocated/initialized/constructed and its contents are stored on the heap.

Is the size of B 8 bytes with the pointers of both X and Y in tandem, or is it two objects of 4 bytes each?

Is it still resulting in two objects like the following situation?

```<code>Class A {}
Class B
{
    A myA;
}

B myB;
</code>```

Can I presume, if these situations result in different data, that inheritance uses less heap allocation than construction due to the additional contained object having its data allocated -- and that the heap allocates this data outside its containing object?

Can I conclude that construction is much less memory efficient than inheritance?

Clarification:
When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties? Does B store a pointer to A or does it directly store the properties of A? If it stores a pointer to an instance of A, that would make it the same in memory as if it had a property of type A instead.

Addition:
It was said that the data of B contains the data of A also in the first example. Are there two allocations or one allocation when allocating the memory of a subclassed object?

In the second example, you're allocating memory twice: once for the contained property object of type A and once again for the object class B, so I'm presuming that you have two distinct memory allocations and two distinct objects with a pointer to A inside B.

If a subclass only allocates memory once for the entire size of all its properties and all its inherited properties, and stores all that information inline, then wouldn't that make it a superior memory allocation approach than allocating multiple objects for one object?

答:
Assuming you are running .NET on x86 architecture, an empty object has an overhead of 8 bytes (and a minimum size of 12 bytes). This means a new object() would occupy 12 bytes in memory.

Considering the following class structure:

```<code>public class Parent // overhead 8 bytes
{
    int a, b, c, d; // int 4 bytes * 4 = 16 bytes
}

public class Child : Parent // inherits everything
{ }

var parent = new Parent(); // 24 bytes
var child = new Child(); // 24 bytes [NOTE: this is a SINGLE object of type Child, not two objects Parent+Child]
</code>```

They are objects of the same size because Child does not declare any other field.

The following class structure instead:

```<code>public class Composable // overhead 8 bytes
{
    int a, b, c, d; // int 4 bytes * 4 = 16 bytes
}

public class Composite // overhead 8 bytes
{
    Composable c = new Composable(); // 4 bytes (reference on the heap)
}

var composable = new Composable(); // 24 bytes
var composite = new Composite(); // 36 bytes (24 + 12) [NOTE: this creates TWO different objects, with one referencing the other]
</code>```

Will suffer of a slightly higher overhead for two reasons: the "empty object" overhead of a new object created and the reference allocated for the inner object on the stack.

Responding to your question: Yes, composition requires a slight more amount of memory then inheritance, but the numbers are really too small to be afraid of.

Regarding your other questions

When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties?

Yes they are, as clearly shown by the inheritance example: we have a single object containing all the fields of both its class and any inherited class.

It was said that the data of B contains the data of A also in the first example. Are there two allocations or one allocation when allocating the memory of a subclassed object?

One single allocation

In the second example, you're allocating memory twice: once for the contained property object of type A and once again for the object class B, so I'm presuming that you have two distinct memory allocations and two distinct objects with a pointer to A inside B.

You are almost correct, the second allocation happens only if you really create that object. In your example you are just declaring a field A myA: this takes 4 bytes of memory (in x86) and no more. It will occupy more memory when you create that object (e.g. A myA = new A())

If a subclass only allocates memory once for the entire size of all its properties and all its inherited properties, and stores all that information inline, then wouldn't that make it a superior memory allocation approach than allocating multiple objects for one object?

Composition vs Inheritance have different characteristic, I do not believe it has any real-world impact but yes, inheritance occupies slightly less memory then Composition.

Reference: OF MEMORY AND STRINGS by C#... err... I mean Jon Skeet.

Body:
Class A
{
    int X {get;set;}
}
Class B : A
{
    int Y {get;set;}
}

B myB;

Say for the sake of argument that an object of type A is 4 bytes and an object of type B is 4 bytes.

B is allocated/initialized/constructed and its contents are stored on the heap.

Is the size of B 8 bytes with the pointers of both X and Y in tandem, or is it two objects of 4 bytes each?

Is it still resulting in two objects like the following situation?

Class A {}
Class B
{
    A myA;
}

B myB;

Can I presume, if these situations result in different data, that inheritance uses less heap allocation than construction due to the additional contained object having its data allocated -- and that the heap allocates this data outside its containing object?

Can I conclude that construction is much less memory efficient than inheritance?

Clarification:
When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties? Does B store a pointer to A or does it directly store the properties of A? If it stores a pointer to an instance of A, that would make it the same in memory as if it had a property of type A instead.

Addition:
It was said that the data of B contains the data of A also in the first example. Are there two allocations or one allocation when allocating the memory of a subclassed object?

In the second example, you're allocating memory twice: once for the contained property object of type A and once again for the object class B, so I'm presuming that you have two distinct memory allocations and two distinct objects with a pointer to A inside B.

If a subclass only allocates memory once for the entire size of all its properties and all its inherited properties, and stores all that information inline, then wouldn't that make it a superior memory allocation approach than allocating multiple objects for one object?

Body:
Assuming you are running .NET on x86 architecture, an empty object has an overhead of 8 bytes (and a minimum size of 12 bytes). This means a new object() would occupy 12 bytes in memory.

Considering the following class structure:

public class Parent // overhead 8 bytes
{
    int a, b, c, d; // int 4 bytes * 4 = 16 bytes
}

public class Child : Parent // inherits everything
{ }

var parent = new Parent(); // 24 bytes
var child = new Child(); // 24 bytes [NOTE: this is a SINGLE object of type Child, not two objects Parent+Child]

They are objects of the same size because Child does not declare any other field.

The following class structure instead:

public class Composable // overhead 8 bytes
{
    int a, b, c, d; // int 4 bytes * 4 = 16 bytes
}

public class Composite // overhead 8 bytes
{
    Composable c = new Composable(); // 4 bytes (reference on the heap)
}

var composable = new Composable(); // 24 bytes
var composite = new Composite(); // 36 bytes (24 + 12) [NOTE: this creates TWO different objects, with one referencing the other]

Will suffer of a slightly higher overhead for two reasons: the "empty object" overhead of a new object created and the reference allocated for the inner object on the stack.

Responding to your question: Yes, composition requires a slight more amount of memory then inheritance, but the numbers are really too small to be afraid of.

Regarding your other questions

When initializing an object of subclass type, are the bytes of that object's parent class's properties stored alongside the bytes of the subclass's properties?

Yes they are, as clearly shown by the inheritance example: we have a single object containing all the fields of both its class and any inherited class.

It was said that the data of B contains the data of A also in the first example. Are there two allocations or one allocation when allocating the memory of a subclassed object?

One single allocation

In the second example, you're allocating memory twice: once for the contained property object of type A and once again for the object class B, so I'm presuming that you have two distinct memory allocations and two distinct objects with a pointer to A inside B.

You are almost correct, the second allocation happens only if you really create that object. In your example you are just declaring a field A myA: this takes 4 bytes of memory (in x86) and no more. It will occupy more memory when you create that object (e.g. A myA = new A())

If a subclass only allocates memory once for the entire size of all its properties and all its inherited properties, and stores all that information inline, then wouldn't that make it a superior memory allocation approach than allocating multiple objects for one object?

Composition vs Inheritance have different characteristic, I do not believe it has any real-world impact but yes, inheritance occupies slightly less memory then Composition.

Reference: OF MEMORY AND STRINGS by C#... err... I mean Jon Skeet.


问:
python: invalid value encountered in true_divide - but where?
I have a question regarding the following problem:

I want to plot the following easy function:

f(x) = x_1*x_2/(x_1^2+x_2^2)

If x & y are zero you would divide by zero, so I added an exception to prevent this case:

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x1, x2):
    return np.where(np.logical_and(x1==0,x2==0),
                    0,
                    x1*x2/(x1*x1+x2*x2))

n = 3
x = y = np.linspace(-5,5,n)
xv, yv = np.meshgrid(x, y)
z = f(xv,yv)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xv,yv,z)
plt.show()
</code>```

My figure is plot and if I inspect my solution it seems also to be correct. However if I run the code I get a division error:

```<code>RuntimeWarning: invalid value encountered in true_divide
</code>```

I tested already the np.where function manually and it returns the x_1=x_2=0 value as true. That seems to work.

Does anybody know where this warning comes from?

答:
As it has been pointed out, you will evaluate every case using np.where(). To avoid the error just code it in a lower level such as

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x1, x2):
    shape = np.shape(x1)
    y = np.zeros(shape)
    for i in range(0,shape[0]):
        for j in range(0,shape[1]):
            if x1[i,j]!=0 and x2[i,j]!=0:
                y[i,j] = x1[i,j]*x2[i,j]/(x1[i,j]*x1[i,j]+x2[i,j]*x2[i,j])
    return y

n = 3
x = y = np.linspace(-5,5,n)
xv, yv = np.meshgrid(x, y)
z = f(xv,yv)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xv,yv,z)
plt.show()
</code>```

Body:
I have a question regarding the following problem:

I want to plot the following easy function:

f(x) = x_1*x_2/(x_1^2+x_2^2)

If x & y are zero you would divide by zero, so I added an exception to prevent this case:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x1, x2):
    return np.where(np.logical_and(x1==0,x2==0),
                    0,
                    x1*x2/(x1*x1+x2*x2))

n = 3
x = y = np.linspace(-5,5,n)
xv, yv = np.meshgrid(x, y)
z = f(xv,yv)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xv,yv,z)
plt.show()

My figure is plot and if I inspect my solution it seems also to be correct. However if I run the code I get a division error:

RuntimeWarning: invalid value encountered in true_divide

I tested already the np.where function manually and it returns the x_1=x_2=0 value as true. That seems to work.

Does anybody know where this warning comes from?

Body:
As it has been pointed out, you will evaluate every case using np.where(). To avoid the error just code it in a lower level such as

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def f(x1, x2):
    shape = np.shape(x1)
    y = np.zeros(shape)
    for i in range(0,shape[0]):
        for j in range(0,shape[1]):
            if x1[i,j]!=0 and x2[i,j]!=0:
                y[i,j] = x1[i,j]*x2[i,j]/(x1[i,j]*x1[i,j]+x2[i,j]*x2[i,j])
    return y

n = 3
x = y = np.linspace(-5,5,n)
xv, yv = np.meshgrid(x, y)
z = f(xv,yv)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xv,yv,z)
plt.show()


问:
Deserialize a json field with different data types without using Newtonsoft json but with System.Web.Script.Serialization.JavaScriptSerializer
I have an issue while deserializing json data which can have both float or array type of data.  The same issue from here
Dealing with JSON field that holds different types in C#

But everywhere the solution is to use json.net with a JsonConverter.  I need to achieve the deserialization using only System.Web.Script.Serialization.JavaScriptSerializer in c#. Can anyone help, pls?

答:
You can use a JavaScriptConverter for this purpose.  However, unlike Json.NET's JsonConverter a JavaScriptConverter can only be used for types that map from and to a JSON object -- not an array or primitive type.  Thus you will need to create a custom converter for any object that may contain a polymorphic property that could be an array or singleton item.

Let's imagine you have JSON that looks like the following:

```<code>{
  "name": "my name",
  "data": {
    "foo": "Foo",
    "bar": "Bar"
  },
  "values": [
    3.14,
    2.718
  ]
}
</code>```

Where "values" might sometimes be a primitive value like so:

```<code>  "values": 3.14
</code>```

And, you want to map this to the following POCO:

```<code>public class RootObject
{
    public string name { get; set; }
    public NestedData data { get; set; }
    public float[] Values { get; set; }
}

public class NestedData
{
    public string foo { get; set; }
    public string bar { get; set; }
}
</code>```

As JavaScriptConverter.Deserialize() is passed an IDictionary<string, object> of parsed values, the steps to take are:

Detach any properties that need custom processing (keeping in mind that JavaScriptSerializer is case-insensitive but that the dictionary is not).

Generate a default deserialization for any remaining properties using JavaScriptSerializer.ConvertToType<T>() using a fresh serializer that does not contain the converter.

Manually deserialize and populate the custom properties into the partially deserialized object, and return it.

For the type shown above, the following converter, based somewhat on this answer, does the job:

```<code>class RootObjectConverter : CustomPropertiesConverter<RootObject>
{
    const string ValuesName = "values";

    protected override IEnumerable<string> CustomProperties
    {
        get { return new[] { ValuesName }; }
    }

    protected override void DeserializeCustomProperties(Dictionary<string, object> customDictionary, RootObject obj, JavaScriptSerializer serializer)
    {
        object itemCost;
        if (customDictionary.TryGetValue(ValuesName, out itemCost) && itemCost != null)
            obj.Values = serializer.FromSingleOrArray<float>(itemCost).ToArray();
    }

    protected override void SerializeCustomProperties(RootObject obj, Dictionary<string, object> dict, JavaScriptSerializer serializer)
    {
        obj.Values.ToSingleOrArray(dict, ValuesName);
    }
}

public abstract class CustomPropertiesConverter<T> : JavaScriptConverter
{
    protected abstract IEnumerable<string> CustomProperties { get; }

    protected abstract void DeserializeCustomProperties(Dictionary<string, object> customDictionary, T obj, JavaScriptSerializer serializer);

    protected abstract void SerializeCustomProperties(T obj, Dictionary<string, object> dict, JavaScriptSerializer serializer);

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        // Detach custom properties
        var customDictionary = new Dictionary<string, object>();
        foreach (var key in CustomProperties)
        {
            object value;
            if (dictionary.TryRemoveInvariant(key, out value))
                customDictionary.Add(key, value);
        }

        // Deserialize and populate all members other than "values"
        var obj = new JavaScriptSerializer().ConvertToType<T>(dictionary);

        // Populate custom properties
        DeserializeCustomProperties(customDictionary, obj, serializer);

        return obj;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        // Generate a default serialization.  Is there an easier way to do this?
        var defaultSerializer = new JavaScriptSerializer();
        var dict = defaultSerializer.Deserialize<Dictionary<string, object>>(defaultSerializer.Serialize(obj));

        // Remove default serializations of custom properties, if present
        foreach (var key in CustomProperties)
        {
            dict.RemoveInvariant(key);
        }

        // Add custom properties
        SerializeCustomProperties((T)obj, dict, serializer);

        return dict;
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new[] { typeof(T) }; }
    }
}

public static class JavaScriptSerializerObjectExtensions
{
    public static void ReplaceInvariant<T>(this IDictionary<string, T> dictionary, string key, T value)
    {
        RemoveInvariant(dictionary, key);
        dictionary.Add(key, value);
    }

    public static bool TryRemoveInvariant<T>(this IDictionary<string, T> dictionary, string key, out T value)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        var keys = dictionary.Keys.Where(k => string.Equals(k, key, StringComparison.OrdinalIgnoreCase)).ToArray();
        if (keys.Length == 0)
        {
            value = default(T);
            return false;
        }
        else if (keys.Length == 1)
        {
            value = dictionary[keys[0]];
            dictionary.Remove(keys[0]);
            return true;
        }
        else
        {
            throw new ArgumentException(string.Format("Duplicate keys found: {0}", String.Join(",", keys)));
        }
    }

    public static void RemoveInvariant<T>(this IDictionary<string, T> dictionary, string key)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        foreach (var actualKey in dictionary.Keys.Where(k => string.Equals(k, key, StringComparison.OrdinalIgnoreCase)).ToArray())
            dictionary.Remove(actualKey);
    }

    public static void ToSingleOrArray<T>(this ICollection<T> list, IDictionary<string, object> dictionary, string key)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        if (list == null || list.Count == 0)
            dictionary.RemoveInvariant(key);
        else if (list.Count == 1)
            dictionary.ReplaceInvariant(key, list.First());
        else
            dictionary.ReplaceInvariant(key, list.ToArray());
    }

    public static List<T> FromSingleOrArray<T>(this JavaScriptSerializer serializer, object value)
    {
        if (value == null)
            return null;
        if (value.IsJsonArray())
        {
            return value.AsJsonArray().Select(i => serializer.ConvertToType<T>(i)).ToList();
        }
        else
        {
            return new List<T> { serializer.ConvertToType<T>(value) };
        }
    }

    public static bool IsJsonArray(this object obj)
    {
        if (obj is string || obj is IDictionary)
            return false;
        return obj is IEnumerable;
    }

    public static IEnumerable<object> AsJsonArray(this object obj)
    {
        return (obj as IEnumerable).Cast<object>();
    }
}
</code>```

Then use it like:

```<code>var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new RootObjectConverter() });
var root = serializer.Deserialize<RootObject>(json);
</code>```

Body:
You can use a JavaScriptConverter for this purpose.  However, unlike Json.NET's JsonConverter a JavaScriptConverter can only be used for types that map from and to a JSON object -- not an array or primitive type.  Thus you will need to create a custom converter for any object that may contain a polymorphic property that could be an array or singleton item.

Let's imagine you have JSON that looks like the following:

{
  "name": "my name",
  "data": {
    "foo": "Foo",
    "bar": "Bar"
  },
  "values": [
    3.14,
    2.718
  ]
}

Where "values" might sometimes be a primitive value like so:

  "values": 3.14

And, you want to map this to the following POCO:

public class RootObject
{
    public string name { get; set; }
    public NestedData data { get; set; }
    public float[] Values { get; set; }
}

public class NestedData
{
    public string foo { get; set; }
    public string bar { get; set; }
}

As JavaScriptConverter.Deserialize() is passed an IDictionary<string, object> of parsed values, the steps to take are:

Detach any properties that need custom processing (keeping in mind that JavaScriptSerializer is case-insensitive but that the dictionary is not).

Generate a default deserialization for any remaining properties using JavaScriptSerializer.ConvertToType<T>() using a fresh serializer that does not contain the converter.

Manually deserialize and populate the custom properties into the partially deserialized object, and return it.

For the type shown above, the following converter, based somewhat on this answer, does the job:

class RootObjectConverter : CustomPropertiesConverter<RootObject>
{
    const string ValuesName = "values";

    protected override IEnumerable<string> CustomProperties
    {
        get { return new[] { ValuesName }; }
    }

    protected override void DeserializeCustomProperties(Dictionary<string, object> customDictionary, RootObject obj, JavaScriptSerializer serializer)
    {
        object itemCost;
        if (customDictionary.TryGetValue(ValuesName, out itemCost) && itemCost != null)
            obj.Values = serializer.FromSingleOrArray<float>(itemCost).ToArray();
    }

    protected override void SerializeCustomProperties(RootObject obj, Dictionary<string, object> dict, JavaScriptSerializer serializer)
    {
        obj.Values.ToSingleOrArray(dict, ValuesName);
    }
}

public abstract class CustomPropertiesConverter<T> : JavaScriptConverter
{
    protected abstract IEnumerable<string> CustomProperties { get; }

    protected abstract void DeserializeCustomProperties(Dictionary<string, object> customDictionary, T obj, JavaScriptSerializer serializer);

    protected abstract void SerializeCustomProperties(T obj, Dictionary<string, object> dict, JavaScriptSerializer serializer);

    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        // Detach custom properties
        var customDictionary = new Dictionary<string, object>();
        foreach (var key in CustomProperties)
        {
            object value;
            if (dictionary.TryRemoveInvariant(key, out value))
                customDictionary.Add(key, value);
        }

        // Deserialize and populate all members other than "values"
        var obj = new JavaScriptSerializer().ConvertToType<T>(dictionary);

        // Populate custom properties
        DeserializeCustomProperties(customDictionary, obj, serializer);

        return obj;
    }

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        // Generate a default serialization.  Is there an easier way to do this?
        var defaultSerializer = new JavaScriptSerializer();
        var dict = defaultSerializer.Deserialize<Dictionary<string, object>>(defaultSerializer.Serialize(obj));

        // Remove default serializations of custom properties, if present
        foreach (var key in CustomProperties)
        {
            dict.RemoveInvariant(key);
        }

        // Add custom properties
        SerializeCustomProperties((T)obj, dict, serializer);

        return dict;
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return new[] { typeof(T) }; }
    }
}

public static class JavaScriptSerializerObjectExtensions
{
    public static void ReplaceInvariant<T>(this IDictionary<string, T> dictionary, string key, T value)
    {
        RemoveInvariant(dictionary, key);
        dictionary.Add(key, value);
    }

    public static bool TryRemoveInvariant<T>(this IDictionary<string, T> dictionary, string key, out T value)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        var keys = dictionary.Keys.Where(k => string.Equals(k, key, StringComparison.OrdinalIgnoreCase)).ToArray();
        if (keys.Length == 0)
        {
            value = default(T);
            return false;
        }
        else if (keys.Length == 1)
        {
            value = dictionary[keys[0]];
            dictionary.Remove(keys[0]);
            return true;
        }
        else
        {
            throw new ArgumentException(string.Format("Duplicate keys found: {0}", String.Join(",", keys)));
        }
    }

    public static void RemoveInvariant<T>(this IDictionary<string, T> dictionary, string key)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        foreach (var actualKey in dictionary.Keys.Where(k => string.Equals(k, key, StringComparison.OrdinalIgnoreCase)).ToArray())
            dictionary.Remove(actualKey);
    }

    public static void ToSingleOrArray<T>(this ICollection<T> list, IDictionary<string, object> dictionary, string key)
    {
        if (dictionary == null)
            throw new ArgumentNullException();
        if (list == null || list.Count == 0)
            dictionary.RemoveInvariant(key);
        else if (list.Count == 1)
            dictionary.ReplaceInvariant(key, list.First());
        else
            dictionary.ReplaceInvariant(key, list.ToArray());
    }

    public static List<T> FromSingleOrArray<T>(this JavaScriptSerializer serializer, object value)
    {
        if (value == null)
            return null;
        if (value.IsJsonArray())
        {
            return value.AsJsonArray().Select(i => serializer.ConvertToType<T>(i)).ToList();
        }
        else
        {
            return new List<T> { serializer.ConvertToType<T>(value) };
        }
    }

    public static bool IsJsonArray(this object obj)
    {
        if (obj is string || obj is IDictionary)
            return false;
        return obj is IEnumerable;
    }

    public static IEnumerable<object> AsJsonArray(this object obj)
    {
        return (obj as IEnumerable).Cast<object>();
    }
}

Then use it like:

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new RootObjectConverter() });
var root = serializer.Deserialize<RootObject>(json);


问:
Creating highlight effect on text with padding using CSS
I am trying to create highlighted text effect with line break(s).

Example:

I cannot figure out how to add padding to the text. Here is the CSS for the span element that contains the text:

```<code>background: none repeat scroll 0 0 #1B1615;
display: inline;
font-size: 15px;
line-height: 24px;
padding-left: 5px;
</code>```

When adding padding it only adds padding to beginning of the text and the end, as seen here:

CSS:

```<code>background: none repeat scroll 0 0 #1B1615;
display: inline;
font-size: 15px;
line-height: 3em;
padding: 10px;
</code>```

Does anybody have any idea on how to make this happen?

答:
you can use box-decoration-break

```<code>-moz-box-decoration-break:clone;
-webkit-box-decoration-break:clone;
box-decoration-break:clone;
</code>```

working sample codepen

Body:
I am trying to create highlighted text effect with line break(s).

Example:

I cannot figure out how to add padding to the text. Here is the CSS for the span element that contains the text:

background: none repeat scroll 0 0 #1B1615;
display: inline;
font-size: 15px;
line-height: 24px;
padding-left: 5px;

When adding padding it only adds padding to beginning of the text and the end, as seen here:

CSS:

background: none repeat scroll 0 0 #1B1615;
display: inline;
font-size: 15px;
line-height: 3em;
padding: 10px;

Does anybody have any idea on how to make this happen?

Body:
you can use box-decoration-break

-moz-box-decoration-break:clone;
-webkit-box-decoration-break:clone;
box-decoration-break:clone;

working sample codepen


问:
Read webs from a file and ping them with a loop (?)
im making an script to ping different websites. I want to read addresses from a file, ping them one time, and write the results on another text file.

```<code>echo off
cls

echo "TEST" > %cd%\out.txt
time >> %cd%\out.txt
ping -n 1 google.com>> %cd%\out.txt

pause>null
</code>```

I dont know how to make the loop for pinging and also, how to read line by line from the file. Can anyone help me?
Thanks.

答:
Something along the lines of the following should be what you want:

```<code>@echo off& setlocal
echo google.com>sites.txt
echo yahoo.com>>sites.txt
set cd=.

for /f %%w in (sites.txt) do call :NextSite %%w
exit /b

:NextSite
echo. >>%cd%\out.txt
echo. >>%cd%\out.txt
echo. | time | find "current" >>%cd%\out.txt
ping -n 1 %1 >>%cd%\out.txt
</code>```

The logic starts at the line with the "for" statement; the preceding lines merely set up a test environment.  You will have your own %cd% setting and filename to replace "sites.txt"

Body:
im making an script to ping different websites. I want to read addresses from a file, ping them one time, and write the results on another text file.

echo off
cls

echo "TEST" > %cd%\out.txt
time >> %cd%\out.txt
ping -n 1 google.com>> %cd%\out.txt

pause>null

I dont know how to make the loop for pinging and also, how to read line by line from the file. Can anyone help me?
Thanks.

Body:
Something along the lines of the following should be what you want:

@echo off& setlocal
echo google.com>sites.txt
echo yahoo.com>>sites.txt
set cd=.

for /f %%w in (sites.txt) do call :NextSite %%w
exit /b

:NextSite
echo. >>%cd%\out.txt
echo. >>%cd%\out.txt
echo. | time | find "current" >>%cd%\out.txt
ping -n 1 %1 >>%cd%\out.txt

The logic starts at the line with the "for" statement; the preceding lines merely set up a test environment.  You will have your own %cd% setting and filename to replace "sites.txt"


问:
Jquery second keydown not detected by $(document).keydown()
I would like to use create two keyboard shorcuts. The first one (keyCode == 80) works but not the second one. I tried the solutions given here but without success.

```<code>  <!DOCTYPE html>
    <html>
      <head>
    <base target="_top">
  </head>
  <body style="background-color: #FFC0CB;">

    <p><red> Ctrl + P = 1 color // Ctrl + I = 2 colors</red></p>
    <p id="log"> </p>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
    $('.warning-bar:first',parent.document).hide();
    $(document).ready(function(){
      $(document).keydown(function(e){
      // 80=p / 81=q  / 73=i  / 77=m /  cf http://keycode.info/
      e.preventDefault();
      if(e.ctrlKey && e.shiftKey && e.altKey && e.keyCode == 80){
          $('#log').html('you pressed Ctrl + p');
           google.script.run.added();
            }
       if(e.ctrlKey && e.shiftKey && e.altKey &&  e.keyCode == 77){
          $('#log').html('you pressed Ctrl + m');
           google.script.run.modified();
      }
      });

    });

    </script>

}

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

答:
I get the correct results using both ctrl + shift + alt + m and ctrl + shift + alt + p using your code: https://jsfiddle.net/7acakxeg/

I only removed the google script and $('.warning-bar:first',parent.document).hide();

Body:
I would like to use create two keyboard shorcuts. The first one (keyCode == 80) works but not the second one. I tried the solutions given here but without success.

  <!DOCTYPE html>

    <base target="_top">

<red> Ctrl + P = 1 color // Ctrl + I = 2 colors</red>

}


问:
VBA to save workbook - error with replacing file with same name
I am using the VBA Code below to automatically save a file, but allow for the user to pick the file location and name.   I have a fixed filename that I want the user to use, for example: TestImport.xlsx, but I need some code to allow them to pick the path on their specific PC.   They will be running this routine weekly, so they will likely have a previous version of the Workbook with the exact same name, so they will have to answer the dialog box prompt to replace the file.

When I run the code, I get the following error:

Run-time error '1004'

  Cannot access 'TestImport.xlsx'

Can you help me see what the problem is with the content below?

```<code>Dim fd As FileDialog, fillName As String

    On Error GoTo ErrorHandler

    Set fd = Application.FileDialog(msoFileDialogSaveAs)

    If fd.Show = True Then
        If fd.SelectedItems(1) <> vbNullString Then
            fillName = fd.SelectedItems(1)
        End If
    Else
        'Stop Code Execution for Null File String
        End
    End If

    saveFileAs = fillName

    'Cleanup
    Set fd = Nothing

    Windows("MeritImport.xlsx").Activate
    Application.ActiveWorkbook.SaveAs Filename:=fillName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    Exit Sub

ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)
</code>```

答:
Instead of using

```<code>Set fd = Application.FileDialog(msoFileDialogSaveAs)
</code>```

use

```<code>Set fd = Application.FileDialog(msoFileDialogFolderPicker)
</code>```

and then create your filename as

```<code>fillname = fillName & Application.PathSeparator & "TestImport.xlsx"
</code>```

To stop displaying messages such as "Are you sure you want to replace this file", use Application.DisplayAlerts = False.

To ensure that the user doesn't already have the file open in the current version of Excel (it's harder to test that it isn't open in another instance, or by another user, etc), you could use code such as:

```<code>'Check to ensure that TestImport.xlsx isn't currently open
On Error Resume Next
Dim wb As Workbook
Set wb = Workbooks("TestImport.xlsx")
On Error GoTo 0
If Not wb Is Nothing Then
    MsgBox "Please close 'TestImport.xlsx'"
    End
End If
</code>```

The final code could look like:

```<code>    Dim fd As FileDialog, fillName As String, wb As Workbook

    'Check to ensure that TestImport.xlsx isn't currently open
    On Error Resume Next
    Set wb = Workbooks("TestImport.xlsx")
    On Error GoTo 0
    If Not wb Is Nothing Then
        MsgBox "Please close 'TestImport.xlsx'"
        End
    End If

    On Error GoTo ErrorHandler

    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    fd.Title = "File Save"  ' to change the title from "Browse" to "File Save"
    If fd.Show = True Then
        If fd.SelectedItems(1) <> vbNullString Then
            fillName = fd.SelectedItems(1)
        Else
            End
        End If
    Else
        'Stop Code Execution for Null File String
        End
    End If
    fillName = fillName & Application.PathSeparator & "TestImport.xlsx"

    'Cleanup
    Set fd = Nothing

    Windows("MeritImport.xlsx").Activate
    Application.DisplayAlerts = False
    Application.ActiveWorkbook.SaveAs Filename:=fillName, _
                                      FileFormat:=xlOpenXMLWorkbook, _
                                      CreateBackup:=False
    Application.DisplayAlerts = True
    Exit Sub

ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)
</code>```

Body:
I am using the VBA Code below to automatically save a file, but allow for the user to pick the file location and name.   I have a fixed filename that I want the user to use, for example: TestImport.xlsx, but I need some code to allow them to pick the path on their specific PC.   They will be running this routine weekly, so they will likely have a previous version of the Workbook with the exact same name, so they will have to answer the dialog box prompt to replace the file.

When I run the code, I get the following error:

Run-time error '1004'

  Cannot access 'TestImport.xlsx'

Can you help me see what the problem is with the content below?

Dim fd As FileDialog, fillName As String

    On Error GoTo ErrorHandler

    Set fd = Application.FileDialog(msoFileDialogSaveAs)

    If fd.Show = True Then
        If fd.SelectedItems(1) <> vbNullString Then
            fillName = fd.SelectedItems(1)
        End If
    Else
        'Stop Code Execution for Null File String
        End
    End If

    saveFileAs = fillName

    'Cleanup
    Set fd = Nothing

    Windows("MeritImport.xlsx").Activate
    Application.ActiveWorkbook.SaveAs Filename:=fillName, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

    Exit Sub

ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)

Body:
Instead of using

Set fd = Application.FileDialog(msoFileDialogSaveAs)

use

Set fd = Application.FileDialog(msoFileDialogFolderPicker)

and then create your filename as

fillname = fillName & Application.PathSeparator & "TestImport.xlsx"

To stop displaying messages such as "Are you sure you want to replace this file", use Application.DisplayAlerts = False.

To ensure that the user doesn't already have the file open in the current version of Excel (it's harder to test that it isn't open in another instance, or by another user, etc), you could use code such as:

'Check to ensure that TestImport.xlsx isn't currently open
On Error Resume Next
Dim wb As Workbook
Set wb = Workbooks("TestImport.xlsx")
On Error GoTo 0
If Not wb Is Nothing Then
    MsgBox "Please close 'TestImport.xlsx'"
    End
End If

The final code could look like:

    Dim fd As FileDialog, fillName As String, wb As Workbook

    'Check to ensure that TestImport.xlsx isn't currently open
    On Error Resume Next
    Set wb = Workbooks("TestImport.xlsx")
    On Error GoTo 0
    If Not wb Is Nothing Then
        MsgBox "Please close 'TestImport.xlsx'"
        End
    End If

    On Error GoTo ErrorHandler

    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    fd.Title = "File Save"  ' to change the title from "Browse" to "File Save"
    If fd.Show = True Then
        If fd.SelectedItems(1) <> vbNullString Then
            fillName = fd.SelectedItems(1)
        Else
            End
        End If
    Else
        'Stop Code Execution for Null File String
        End
    End If
    fillName = fillName & Application.PathSeparator & "TestImport.xlsx"

    'Cleanup
    Set fd = Nothing

    Windows("MeritImport.xlsx").Activate
    Application.DisplayAlerts = False
    Application.ActiveWorkbook.SaveAs Filename:=fillName, _
                                      FileFormat:=xlOpenXMLWorkbook, _
                                      CreateBackup:=False
    Application.DisplayAlerts = True
    Exit Sub

ErrorHandler:
    Set fd = Nothing
    MsgBox "Error " & Err & ": " & Error(Err)


问:
Parse string from environment variable in JavaScript
I have a API key stored in the .env file (this has a structure of NAME=key. The key in question is a Firebase private key which has a multiline format, something like this:

```<code>"private_key": "-----BEGIN PRIVATE KEY-----\randomletters\nrandomletters\n-----END PRIVATE KEY-----\n"
</code>```

It's originally saved in a JSON file but I needed to store it in a .env file to include it in a Glitch project. I enclosed it in ""but when I try to import it in my Node module using process.env.NAME it looks like a string but without formatting (no new line, instead \n is printed) and when I submit it to Firebase it is not accepted.

How can I transform that long unformatted String into a multiline String in JavaScript?

答:
You can replace the \ns with new lines with using the replace() method:

```<code>escaped.replace(/\\n/g, '\n');
</code>```

Body:
I have a API key stored in the .env file (this has a structure of NAME=key. The key in question is a Firebase private key which has a multiline format, something like this:

"private_key": "-----BEGIN PRIVATE KEY-----\randomletters\nrandomletters\n-----END PRIVATE KEY-----\n"

It's originally saved in a JSON file but I needed to store it in a .env file to include it in a Glitch project. I enclosed it in ""but when I try to import it in my Node module using process.env.NAME it looks like a string but without formatting (no new line, instead \n is printed) and when I submit it to Firebase it is not accepted.

How can I transform that long unformatted String into a multiline String in JavaScript?

Body:
You can replace the \ns with new lines with using the replace() method:

escaped.replace(/\\n/g, '\n');


问:
windows powershell add text to the beginning of each object in a csv file
I have a csv file like this:

```<code>samaccountname,enabled
user1,false
user2,false
</code>```

I want to take each entry in the samaccaountname column and add this exact text:

C:\Users\

then I need to create a new csv file that only contains a single column with the new data like this:

```<code>header
C:\Users\User1
C:\Users\User2
C:\Users\User3
</code>```

what is the best way to accomplish this?

答:
Import the csv, loop through the entries of that csv, for each of them create an object with the property name you want. Then export</p>

```<code>$DataToExport = Import-CSV $sourcefile | ForEach-Object {
    [pscustomobject]@{
        "Header" = "C:\Users\$($_.samaccountname)"
    }
}
$DataToExport | Export-CSV $newfile -NoTypeInformation
</code>```

Body:
I have a csv file like this:

samaccountname,enabled
user1,false
user2,false

I want to take each entry in the samaccaountname column and add this exact text:

C:\Users\

then I need to create a new csv file that only contains a single column with the new data like this:

header
C:\Users\User1
C:\Users\User2
C:\Users\User3

what is the best way to accomplish this?

Body:
Import the csv, loop through the entries of that csv, for each of them create an object with the property name you want. Then export

$DataToExport = Import-CSV $sourcefile | ForEach-Object {
    [pscustomobject]@{
        "Header" = "C:\Users\$($_.samaccountname)"
    }
}
$DataToExport | Export-CSV $newfile -NoTypeInformation


问:
Can't connect to SQL Server 2005 instance on remote server - Error 14
I'm trying to set up a DSN using ODBC on my local machine to a remote SQL Server 2005 instance.  I'm using SQL Server Authentication, but when I try to connect, I get SQL Server Error 14 - DBNETLIB Invalid Connection, SQL State: '01000' and '08001'.  The confusing thing is that I can connect just fine through SQL Server Management Studio on my local PC, I just can't setup a connection using ODBC.  Any help or insight is appreciated.  I've checked the usual suspects, Named Pipes and TCP/IP are both enabled on the server and port 1433 is open on both the local and remote machines.</p>

答:
Ok, was able to get it going thanks to the suggestions on this post

Looks, like I have to use the SQL Native Client driver instead of the SQL Server driver.  Wonder why is that's the case?  What's the difference??

ContentLicense: CC BY-SA 2.5


问:
segue to specific Firebase data
I have a tableView and it has about 5 cells and each cell has a different subject. Upon clicking on the cell, I will like to segue to a view controller that is populated with Firebase data only containing posts that has the specific subject clicked.

```<code>override func viewDidLoad() {
        super.viewDidLoad()
  FIRDatabase.database().reference().child("books").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                self.Category = postsDictionary["Category"] as? String ?? ""

            }})
    }

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segue" {

                let showBooks = segue.destination as! SearchTableViewController

                showBooks.categorySegue = self.Category

        }
    }
</code>```

In my Firebase database, I have a bunch of posts made by different users and in every post, they set the category to which the post belongs to. For example, if I click on the tableView cell that has the subject: Economics, I would like to segue to a view controller that only has the Economics category.

This is how I retrieve the post attributed to certain subjects:

```<code>databaseRef.child("books").queryOrdered(byChild:  "category").queryEqual(toValue: categorySegue).observeSingleEvent(of: .value, with: { (snapshot) in

        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary
        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedUser?.uid)
        {
            print("same as logged in user")
        }
        else
        {
        self.usersArray.append(snapshot)
             self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
        }

        }) { (error) in
            print(error.localizedDescription)
        }
        tableView.tableFooterView = UIView()
</code>```

答:
If the category is directly below the posts node under a uniqueID, then try this

Example :

```<code>posts
    -> post_id1
         ->category : "books"
         -> other keys

    -> post_id2
         ->category : "music"
         -> other keys
</code>```

The query to fetch the posts by category will be like this,

```<code> let strCategory = "music"
 baseRef.child("posts").queryOrdered(byChild:  "category").queryEqualToValue(strCategory).observeSingleEvent(of: .value, with: { (snapshot) in

  print(snapshot)

})
</code>```

To get the cell index on selection,

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow{
        let selectedRow = indexPath.row
        let categorySelected = Subjects[selectedRow]

    }
}
</code>```

Title: segue to specific Firebase data

Body:
I have a tableView and it has about 5 cells and each cell has a different subject. Upon clicking on the cell, I will like to segue to a view controller that is populated with Firebase data only containing posts that has the specific subject clicked.

override func viewDidLoad() {
        super.viewDidLoad()
  FIRDatabase.database().reference().child("books").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                self.Category = postsDictionary["Category"] as? String ?? ""

            }})
    }

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "segue" {

                let showBooks = segue.destination as! SearchTableViewController

                showBooks.categorySegue = self.Category

        }
    }

In my Firebase database, I have a bunch of posts made by different users and in every post, they set the category to which the post belongs to. For example, if I click on the tableView cell that has the subject: Economics, I would like to segue to a view controller that only has the Economics category.

This is how I retrieve the post attributed to certain subjects:

databaseRef.child("books").queryOrdered(byChild:  "category").queryEqual(toValue: categorySegue).observeSingleEvent(of: .value, with: { (snapshot) in

        let key = snapshot.key
        let snapshot = snapshot.value as? NSDictionary
        snapshot?.setValue(key, forKey: "uid")

        if(key == self.loggedUser?.uid)
        {
            print("same as logged in user")
        }
        else
        {
        self.usersArray.append(snapshot)
             self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
        }

        }) { (error) in
            print(error.localizedDescription)
        }
        tableView.tableFooterView = UIView()

Body:
If the category is directly below the posts node under a uniqueID, then try this

Example :

posts
    -> post_id1
         ->category : "books"
         -> other keys

    -> post_id2
         ->category : "music"
         -> other keys

The query to fetch the posts by category will be like this,

 let strCategory = "music"
 baseRef.child("posts").queryOrdered(byChild:  "category").queryEqualToValue(strCategory).observeSingleEvent(of: .value, with: { (snapshot) in

  print(snapshot)

})

To get the cell index on selection,

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let indexPath = tableView.indexPathForSelectedRow{
        let selectedRow = indexPath.row
        let categorySelected = Subjects[selectedRow]

    }
}


问:
Stack corruption during conversion of large double to unsigned int
On a windows machine, running visual c++, I discovered that the following lines of code seem corrupt memory via a call to something called __dtoui3 (a bunch of bytes change after this call. Specifically it seems like the value of DBL_MAX is printed twice in a row in a random place in memory)

```<code>double temp =  DBL_MAX;
unsigned int blissfullyUnaware = (unsigned int) temp;
</code>```

The following, however, do not:

```<code>double temp =  0;
unsigned int blissfullyUnaware = (unsigned int) temp;
</code>```

Can anyone shed light on why this is happening?

答:
[conv.fpint]/1 A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be
  represented in the destination type.

Emphasis mine. DBL_MAX is somewhere around 2^1024, while unsigned int likely tops out at 2^32.

Body:
On a windows machine, running visual c++, I discovered that the following lines of code seem corrupt memory via a call to something called __dtoui3 (a bunch of bytes change after this call. Specifically it seems like the value of DBL_MAX is printed twice in a row in a random place in memory)

double temp =  DBL_MAX;
unsigned int blissfullyUnaware = (unsigned int) temp;

The following, however, do not:

double temp =  0;
unsigned int blissfullyUnaware = (unsigned int) temp;

Can anyone shed light on why this is happening?


问:
Where is Correlate Button to Configure Analytical Driver Correlation?
It is really giving me a headache trying to figure out and find resources on how to Analytical Driver Correlation.

I am trying to follow the instruction from Wiki Spagobi, however, I can't find the configuration page where the correlate button is located.

My ultimate goal is to have a filter on my Cockpit report as mentioned on Wiki Spagobi as an example:

"consider two geographical Analytical Driver 'continent' and 'state', if you associate both to a business document probably you want that if a user choose a continent then the state Analytical Driver shows only the states of the continent selected."

Any information, suggestion, advice, direction will be greatly appreciated!

J

答:
Actually in SpagoBI 5.2, which is what i'm using, you manage correlation of two analytical drivers in the "Document detail" of the document that you want to make this.

highlighted button of correlation


问:
Will `navigator.storage.persist` grandfather regular cache entries into persistent ones?
If I make a call to navigator.storage.persist, will entries already added to (and not yet expunged from) a regular cache automatically become persistent, or must a new cache be created (e.g., by somehow copying the old non-persistent cache into a newly created (and now, given user permissions, persistent) one)?

I'd like to get my my app started doing regular caching of critical files early on and then requesting persistence and registering a service worker to install these files ideally without making any new requests (unless the user already somehow cleared the cache before the worker installs).

答:
The following excerpts from sections 3 & 3.1 of the specification are relevant:

...Each origin has an associated site storage unit. A site storage
  unit contains a single box.

A box has mode which is either "best-effort" or "persistent"...

A box is considered to be an atomic unit. Whenever a box is cleared by
  the user agent, it must be cleared in its entirety.

So there's a single conceptual "box" for your origin's storage, and that origin is cleared in an all-or-nothing fashion. That would apply to items that were stored either before or after the "box" transitioned from being "best-effort" to being "persistent".

That's all to say that you can cache things early, and then request persistence later on.


问:
What does the landing time mean in airflow?
There is a section called "landing time" in the DAG view on the web console of airflow.

An example screen shot taken from airbnb's blog:

But what does it mean? There is no definition in the documents or in their repository.

答:
Since the existing answer here wasn't totally clear, and this is the top hit for "airflow landing time" I went to the chat archives and found the original answer being referenced here:

```<code>Maxime Beauchemin @mistercrunch Jun 09 2016 11:12
it's the number of hours after the time the scheduling period ended
take a schedule_interval='@daily' run for 2016-01-01 that finishes at 2016-01-02 03:52:00
landing time is 3:52
</code>```

https://gitter.im/apache/incubator-airflow/archives/2016/06/09

It seems the Y axis is in hours, and the negative landing times are a result of running jobs manually so they finish hours before they "should have finished" based on the schedule.

Body:
Since the existing answer here wasn't totally clear, and this is the top hit for "airflow landing time" I went to the chat archives and found the original answer being referenced here:

Maxime Beauchemin @mistercrunch Jun 09 2016 11:12
it's the number of hours after the time the scheduling period ended
take a schedule_interval='@daily' run for 2016-01-01 that finishes at 2016-01-02 03:52:00
landing time is 3:52

https://gitter.im/apache/incubator-airflow/archives/2016/06/09

It seems the Y axis is in hours, and the negative landing times are a result of running jobs manually so they finish hours before they "should have finished" based on the schedule.


问:
Android Client Socket IOException
EDIT: The problem is the input in the Client.class so when the Android devices receives an answer from the Server. Those are the following lines that causes the crash:

```<code>        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));

        String text;

        while ((text = reader.readLine()) != null) {
            Log.d("ClientLog", "Received from Server"+ text);
        }
</code>```

Here is my Client.class in Android:

```<code>public class Client implements Runnable{

public Client() {

}

@Override
public void run() {
    try {
        Log.d("ClientLog", "Socket creation incoming");
        Socket client = new Socket("localhost", 5555);
        Log.d("ClientLog", "Client has been started");

        // Streams:
        OutputStream out = client.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        // -----------------------------------------------------------------------

        writer.write("Test");
        writer.newLine();
        writer.flush();

        String text;

        while ((text = reader.readLine()) != null) {
            Log.d("ClientLog", "Received from Server"+ text);
        }

        writer.close();
        reader.close();

    } catch (UnknownHostException e) {
        Log.d("ClientLog", "Error: Host not found");
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("ClientLog", "Error: IOException");
        e.printStackTrace();
    }
}
</code>```

}

And if needed my Server.class in Java:

```<code>public class Server {

public static void main(String[] args) {

    ExecutorService executor = Executors.newFixedThreadPool(30);

    ServerSocket server;
    try {
        server = new ServerSocket(5555);
        System.out.println("Server has been started on Port 5555");

        while(true) {
            try {
                Socket client = server.accept();

                //Thread t = new Thread(new Handler(client));
                //t.start();
                executor.execute(new Handler(client));

            } catch (IOException e) {
                System.out.println("Error IOExceotion");
                e.printStackTrace();
            }
        }

    } catch (IOException e1) {
        e1.printStackTrace();
    }

}
</code>```

The Handler.class needed for Server.class:

```<code>public class Handler implements Runnable{
private Socket client;

public Handler(Socket pClient) {
    client = pClient;
}

@Override
public void run() {
    try {
                // Streams:
                OutputStream out = client.getOutputStream();
                PrintWriter writer = new PrintWriter(out);

                InputStream input = client.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                // -----------------------------------------------------------------------

                String text = null;

                while ((text = reader.readLine()) != null) {
                    writer.write(text+ "\n");
                    writer.flush();
                    System.out.println("Recieved from Client: "+ text);
                }

                //Close Streams
                writer.close();
                reader.close();

                client.close();
    } catch (IOException e) {
        System.out.println("Error IOException");
        e.printStackTrace();
    }
}
</code>```

}

答:
The debugging was resolved in the comments above.

Step 1: Add permissions to the android manifest file as was outlined here: Java socket IOException - permission denied

Step 2: Change the while ((text = reader.readLine()) != null) check. I guess the text = reader.readLine() != null check was problematic.

Title: Android Client Socket IOException

Body:
EDIT: The problem is the input in the Client.class so when the Android devices receives an answer from the Server. Those are the following lines that causes the crash:

        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));

        String text;

        while ((text = reader.readLine()) != null) {
            Log.d("ClientLog", "Received from Server"+ text);
        }

Here is my Client.class in Android:

public class Client implements Runnable{

public Client() {

}

@Override
public void run() {
    try {
        Log.d("ClientLog", "Socket creation incoming");
        Socket client = new Socket("localhost", 5555);
        Log.d("ClientLog", "Client has been started");

        // Streams:
        OutputStream out = client.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

        InputStream input = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        // -----------------------------------------------------------------------

        writer.write("Test");
        writer.newLine();
        writer.flush();

        String text;

        while ((text = reader.readLine()) != null) {
            Log.d("ClientLog", "Received from Server"+ text);
        }

        writer.close();
        reader.close();

    } catch (UnknownHostException e) {
        Log.d("ClientLog", "Error: Host not found");
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("ClientLog", "Error: IOException");
        e.printStackTrace();
    }
}

}

And if needed my Server.class in Java:

public class Server {

public static void main(String[] args) {

    ExecutorService executor = Executors.newFixedThreadPool(30);

    ServerSocket server;
    try {
        server = new ServerSocket(5555);
        System.out.println("Server has been started on Port 5555");

        while(true) {
            try {
                Socket client = server.accept();

                //Thread t = new Thread(new Handler(client));
                //t.start();
                executor.execute(new Handler(client));

            } catch (IOException e) {
                System.out.println("Error IOExceotion");
                e.printStackTrace();
            }
        }

    } catch (IOException e1) {
        e1.printStackTrace();
    }

}

The Handler.class needed for Server.class:

public class Handler implements Runnable{
private Socket client;

public Handler(Socket pClient) {
    client = pClient;
}

@Override
public void run() {
    try {
                // Streams:
                OutputStream out = client.getOutputStream();
                PrintWriter writer = new PrintWriter(out);

                InputStream input = client.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                // -----------------------------------------------------------------------

                String text = null;

                while ((text = reader.readLine()) != null) {
                    writer.write(text+ "\n");
                    writer.flush();
                    System.out.println("Recieved from Client: "+ text);
                }

                //Close Streams
                writer.close();
                reader.close();

                client.close();
    } catch (IOException e) {
        System.out.println("Error IOException");
        e.printStackTrace();
    }
}

}


问:
Android listview with button lost reference when clicked
I am trying to edit content in listview but when clicked to update some item, others position update also. This data are saved on SQLite database. Please see below my adapter</p>

```<code>public View getView(int position, View convertView, ViewGroup parent) {
    View v = super.getView(position, convertView, parent);

    txtId = (TextView) v.findViewById(R.id.txtId);
    txtValue = (TextView) v.findViewById(R.id.txtValue);
    ckb = (CheckBox) v.findViewById(R.id.ckbEnable);
    btnUpdate = (Button) v.findViewById(R.id.btnUpdate);

    final String id = list.get(position).get("id").toString();
    final String value= list.get(position).get("value").toString();
    boolean bval = list.get(position).get("enbl").toString().equals("true") ? true : false;

    txtId.setText(id);
    txtValue.setText(value);
    ckb.setChecked(bval);

    btnUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            control = new DataControl(context);
            cal = new DataCal();
            cal.setId(id);
            cal.setValue(txtValue.getText().toString());
            cal.setEnable(String.valueOf(ckb.isChecked()));
            int ctrl = control.editCal(cal);
            if (ctrl > 0)
                MessageBox("Success on updating");
            else
                MessageBox("Error while updating!");
        }
    });

    return v;
</code>```

答:
Try to use "ViewHolder" class within your Adapter, I hope it will resolve all your issues. Something like that:</p>

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

 /**
 * Created by Zohaib Hassan on 11/28/2016.
 */

 public class InboxAdapter extends ArrayAdapter<InboxRow> {

 ArrayList<InboxRow> items;
 Context context;

 public InboxAdapter(Context context, int resource, ArrayList<InboxRow> items) {
super(context , resource , items);
this.context = context;
this.items = items;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

// Get the data item for this position

InboxRow rowItem = getItem(position);

// Check if an existing view is being reused, otherwise inflate the view

ViewHolder viewHolder; // view lookup cache stored in tag

if (convertView == null) {

    viewHolder = new ViewHolder();

    LayoutInflater inflater = LayoutInflater.from(context);

    convertView = inflater.inflate(R.layout.inbox_row, null);

    viewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_user_name_inbox);
    viewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message_inbox);
    viewHolder.tvTimeCount = (TextView) convertView.findViewById(R.id.tv_time_count_inbox);
    viewHolder.userProfilePic = (CircleImageView) convertView.findViewById(R.id.inbox_profile_image);

    convertView.setTag(viewHolder);

} else {

    viewHolder = (ViewHolder) convertView.getTag();

}

// Set Your data here!
/*CircleImageView ivProfileImage Set Background with Picasso*/

return convertView;

}

private static class ViewHolder {

TextView tvUserName , tvMessage , tvTimeCount;
CircleImageView userProfilePic;

}

}
</code>```

Body:
I am trying to edit content in listview but when clicked to update some item, others position update also. This data are saved on SQLite database. Please see below my adapter

public View getView(int position, View convertView, ViewGroup parent) {
    View v = super.getView(position, convertView, parent);

    txtId = (TextView) v.findViewById(R.id.txtId);
    txtValue = (TextView) v.findViewById(R.id.txtValue);
    ckb = (CheckBox) v.findViewById(R.id.ckbEnable);
    btnUpdate = (Button) v.findViewById(R.id.btnUpdate);

    final String id = list.get(position).get("id").toString();
    final String value= list.get(position).get("value").toString();
    boolean bval = list.get(position).get("enbl").toString().equals("true") ? true : false;

    txtId.setText(id);
    txtValue.setText(value);
    ckb.setChecked(bval);

    btnUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            control = new DataControl(context);
            cal = new DataCal();
            cal.setId(id);
            cal.setValue(txtValue.getText().toString());
            cal.setEnable(String.valueOf(ckb.isChecked()));
            int ctrl = control.editCal(cal);
            if (ctrl > 0)
                MessageBox("Success on updating");
            else
                MessageBox("Error while updating!");
        }
    });

    return v;

Body:
Try to use "ViewHolder" class within your Adapter, I hope it will resolve all your issues. Something like that:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

import de.hdodenhof.circleimageview.CircleImageView;

 /**
 * Created by Zohaib Hassan on 11/28/2016.
 */

 public class InboxAdapter extends ArrayAdapter<InboxRow> {

 ArrayList<InboxRow> items;
 Context context;

 public InboxAdapter(Context context, int resource, ArrayList<InboxRow> items) {
super(context , resource , items);
this.context = context;
this.items = items;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

// Get the data item for this position

InboxRow rowItem = getItem(position);

// Check if an existing view is being reused, otherwise inflate the view

ViewHolder viewHolder; // view lookup cache stored in tag

if (convertView == null) {

    viewHolder = new ViewHolder();

    LayoutInflater inflater = LayoutInflater.from(context);

    convertView = inflater.inflate(R.layout.inbox_row, null);

    viewHolder.tvUserName = (TextView) convertView.findViewById(R.id.tv_user_name_inbox);
    viewHolder.tvMessage = (TextView) convertView.findViewById(R.id.tv_message_inbox);
    viewHolder.tvTimeCount = (TextView) convertView.findViewById(R.id.tv_time_count_inbox);
    viewHolder.userProfilePic = (CircleImageView) convertView.findViewById(R.id.inbox_profile_image);

    convertView.setTag(viewHolder);

} else {

    viewHolder = (ViewHolder) convertView.getTag();

}

// Set Your data here!
/*CircleImageView ivProfileImage Set Background with Picasso*/

return convertView;

}

private static class ViewHolder {

TextView tvUserName , tvMessage , tvTimeCount;
CircleImageView userProfilePic;

}

}


问:
Know clicked view using ButterKnife
I have this code :

```<code>@OnClick( {R.id.iv_first,R.id.iv_second} )
public void launchCards() {
    Log.i(TAG,"clicked");
}
</code>```

Is there a way to know inside the launchCards() method which of the two ImageView has been clicked ?

答:
Maybe reading the documentation at http://jakewharton.github.io/butterknife/ wouldn't hurt - just change your method signature to launchCards(View v) and then use v.getId() inside your function.

Hope this helps you, comment if you have any questions

Title: Know clicked view using ButterKnife

Body:
I have this code :

@OnClick( {R.id.iv_first,R.id.iv_second} )
public void launchCards() {
    Log.i(TAG,"clicked");
}

Is there a way to know inside the launchCards() method which of the two ImageView has been clicked ?


问:
Function doesn't print anything c++
```<code>#include <iostream>
using namespace std;

int compute_binare_code(int n, int a[][4]){
    int i,j;
    int bC = 0, p = 1;
    for(i = 1;i <= n;i++){
        for(j = i+1;j <= n;j++){ //just counting bC
            bC += a[i][j]*p;
            p =p*2;
           }
     }
    return bC;
}

int main(){
  cout << "mata3";
  int a[4][4],b[5][5],i,j;
  for(i=1;i<=4;i++)
    for(j=1;j<=4;j++)
        if( (i+j)%2 == 0)
            a[i][j]=0;
        else
            a[i][j]=1;

  cout<<"mata1";
  cout<<compute_binare_code(4, a);
  cout<<"mata2";
  return 0;
}
</code>```

When i run this program, it doesn't give any error but it runs in background forever. It does not print anything, not even "mata3". Can someone explain me why?

答:
Arrays in C++ are indexed from 0.

Your for loop increments i/j from 1 to 4, but it should be 0 to 3.

See also Accessing an array out of bounds gives no error, why?

Title: Function doesn't print anything c++

Body:
#include <iostream>
using namespace std;

int compute_binare_code(int n, int a[][4]){
    int i,j;
    int bC = 0, p = 1;
    for(i = 1;i <= n;i++){
        for(j = i+1;j <= n;j++){ //just counting bC
            bC += a[i][j]*p;
            p =p*2;
           }
     }
    return bC;
}

int main(){
  cout << "mata3";
  int a[4][4],b[5][5],i,j;
  for(i=1;i<=4;i++)
    for(j=1;j<=4;j++)
        if( (i+j)%2 == 0)
            a[i][j]=0;
        else
            a[i][j]=1;

  cout<<"mata1";
  cout<<compute_binare_code(4, a);
  cout<<"mata2";
  return 0;
}

When i run this program, it doesn't give any error but it runs in background forever. It does not print anything, not even "mata3". Can someone explain me why?


问:
How to solve Docker permission error when trigger by Jenkins
My Jenkins is not run in Docker container, just tradional install to VPS. I got the following error when executing a simple test project. I am using Ubuntu 14, java 7, and stable Jenkins. I tried all methods I can find on google, but can't get it work.

I am trying to execute this shell

```<code>docker build --pull=true -t nick/hello-jenkins:$GIT_COMMIT .
</code>```

After code change.

Here is error:

```<code>Got permission denied while trying to connect to the Docker daemon socket at unix: ....
</code>```

```<code>Started by user nicolas xu
Building in workspace /var/lib/jenkins/workspace/hello-Jenkins
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/nicolasxu/hello-nick-jenkins.git # timeout=10
Fetching upstream changes from https://github.com/nicolasxu/hello-nick-jenkins.git
 > git --version # timeout=10
 > git fetch --tags --progress https://github.com/nicolasxu/hello-nick-jenkins.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision d94ae21a8a2cf58ffc790dcad15bd851fb17df5a (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f d94ae21a8a2cf58ffc790dcad15bd851fb17df5a
 > git rev-list d94ae21a8a2cf58ffc790dcad15bd851fb17df5a # timeout=10
[hello-Jenkins] $ /bin/sh -xe /tmp/hudson5076309502904684976.sh
+ docker build --pull=true -t nick/hello-jenkins:d94ae21a8a2cf58ffc790dcad15bd851fb17df5a .
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.27/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&pull=1&rm=1&shmsize=0&t=nick%2Fhello-jenkins%3Ad94ae21a8a2cf58ffc790dcad15bd851fb17df5a&ulimits=null: dial unix /var/run/docker.sock: connect: permission denied
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>```

I can run 'docker' in console as root no problem, why jenkins can't try a shell command which runs 'docker'? What is going on? Totally confused.......

答:
In your VPS server terminal, do this to add your jenkins user to the docker group:

```<code>sudo usermod -aG docker jenkins
</code>```

Then restart your jenkins server to refresh the group.

Take into account any security issue that this could produce:

Warning: The docker group grants privileges equivalent to the root user. For details on how this impacts security in your system, see Docker Daemon Attack Surface.

Refer to the docs

Edit (mentioned by @iger): Just make sure to restart the Jenkins from command-line (i.e. sudo service jenkins restart), but not through the rest endpoint (http:///restart)

Body:
My Jenkins is not run in Docker container, just tradional install to VPS. I got the following error when executing a simple test project. I am using Ubuntu 14, java 7, and stable Jenkins. I tried all methods I can find on google, but can't get it work.

I am trying to execute this shell

docker build --pull=true -t nick/hello-jenkins:$GIT_COMMIT .

After code change.

Here is error:

Got permission denied while trying to connect to the Docker daemon socket at unix: ....

Started by user nicolas xu
Building in workspace /var/lib/jenkins/workspace/hello-Jenkins
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/nicolasxu/hello-nick-jenkins.git # timeout=10
Fetching upstream changes from https://github.com/nicolasxu/hello-nick-jenkins.git
 > git --version # timeout=10
 > git fetch --tags --progress https://github.com/nicolasxu/hello-nick-jenkins.git +refs/heads/*:refs/remotes/origin/*
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision d94ae21a8a2cf58ffc790dcad15bd851fb17df5a (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f d94ae21a8a2cf58ffc790dcad15bd851fb17df5a
 > git rev-list d94ae21a8a2cf58ffc790dcad15bd851fb17df5a # timeout=10
[hello-Jenkins] $ /bin/sh -xe /tmp/hudson5076309502904684976.sh
+ docker build --pull=true -t nick/hello-jenkins:d94ae21a8a2cf58ffc790dcad15bd851fb17df5a .
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.27/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&pull=1&rm=1&shmsize=0&t=nick%2Fhello-jenkins%3Ad94ae21a8a2cf58ffc790dcad15bd851fb17df5a&ulimits=null: dial unix /var/run/docker.sock: connect: permission denied
Build step 'Execute shell' marked build as failure
Finished: FAILURE

I can run 'docker' in console as root no problem, why jenkins can't try a shell command which runs 'docker'? What is going on? Totally confused.......

Body:
In your VPS server terminal, do this to add your jenkins user to the docker group:

sudo usermod -aG docker jenkins

Then restart your jenkins server to refresh the group.

Take into account any security issue that this could produce:

Warning: The docker group grants privileges equivalent to the root user. For details on how this impacts security in your system, see Docker Daemon Attack Surface.

Refer to the docs

Edit (mentioned by @iger): Just make sure to restart the Jenkins from command-line (i.e. sudo service jenkins restart), but not through the rest endpoint (http:///restart)


问:
What is label_keys parameter good for in a Classifier - Tensorflow?
What is label_keys parameter good for in a Classifier.
Can you visualize the labeled data on Tensorboard at the Embeddings section?

答: Not in tensorboard, but the predict method can return the class names instead of numbers if you provide label_keys.</p>


问:
Kotlin infinity loop on list in recursion
This follows infinite loop, in clojure such things just fine  </p>

```<code>tailrec fun passHeaders (xH: List<Int>)
{
    while (xH.isNotEmpty())
    {
        passHeaders(xH.drop(1))
    }
}
</code>```

答: The first call to this function will never terminate if xH isn't empty. .drop() doesn't modify the original list.

Body:
This follows infinite loop, in clojure such things just fine

tailrec fun passHeaders (xH: List<Int>)
{
    while (xH.isNotEmpty())
    {
        passHeaders(xH.drop(1))
    }
}


答: List.drop does not mutate the List, but rather produces a new List instance. Thus, you're while loop is infinite.

Title: Kotlin infinity loop on list in recursion


问:
Does HTML5 audio tag support serving mp3s from another domain?
So I am having a web application with domian "www.example.com" that needs to serve audio from "www.example2.com", but for some reason this is not working (the audio just does not stream)

<audio src="http://www.example2.com/song.mp3" controls preload></audio>

Given that if I put the sound source url directly into the browser the audio will be available

Anyone tried this? thanks

Wa'el

答:
Apparently I cannot vote up CyberK's response (don't have the reputation yet to do so) but I agree with him. You cannot do <audio> or <video> cross-domain. I have tried this exact thing on both Chrome and Firefox. There are more than a couple of articles about this. Finding this out for myself today; not happy with the restriction.

http://www.bluishcoder.co.nz/2008/11/video-audio-and-cross-domain-usage.html


问:
Faster calculation histogram of a set of images
I have about 3 million images and need to calculate a histogram for each one. Right now I am using python but it is taking of lot of time. Is there any way to process the images in batches? I have NVIDIA 1080 Ti GPU cards, so maybe if there is a way to process on the GPU?

I can't find any code or library to process the images in parallel. Any kind of help to boost up the speed is appreciated

答:
Python is among the slowest production-ready languages you can use.

As you haven't posted any code, I can only provide general suggestions. They are listed in order of practicality below:

Use a compiled version of python, such as pypy or cpython

Use existing software with your desired functionality. There's nothing wrong with finding free software online.

Use a more efficient (or perhaps even lossy) algorithm to skip computation

Use a faster language such as Rust, C++, C#, or Java


问:
Test 3 activities with Espresso
I have two activities which consist of filling a form and editing\viewing the filled form.

I would like to know whether the input text that was filled with one activity matches the text that is displayed in another activity.
Currently, my test starts the form activity, fills random data and saves the form.

I would like to search for the filled form in a different activity, in which I click a button and then the filled details are shown and tested.
What is the best way of testing such behavior?

答: Espresso doesn't really care about Activities (other than the one you start with).  You can start the Espresso test with one activity and then use ViewActions to navigate through your app to the one where you want to do the verification.  One of the biggest issues that you may need to overcome is getting Espresso to 'wait' for anything asynchronous to occur while you're traveling from Point A to Point B in your app.  Espresso will wait for AsyncTasks and provides rudimentary support for creating IdlingResources.  In depth discussion of these things require more in depth knowledge of the specific issues that you are running into.</p>

Title: Test 3 activities with Espresso


问:
Retrieving a sibling xml element
I have a set of xml elements that are siblings

```<code><z>1</z>
<b>1</b>
<w>1</w>
<n>1</n>
<e>1</e>
<v>1</v>
</code>```

XElement y is currently pointing to Element e. I now want to look at Element b.

The code

```<code>var y = e.ElementsBeforeSelf("b");
</code>```

does return a collection with just the element b.

Of course, now I need to return just the single element b. I am not always certain that Element b will be a fixed number of elements above e. I am missing something really obvious here because I have not been able with looking at a lot of good articles to figure this out.

Things I have tried:

```<code>var y = e.ElementsBeforeSelf().First().Element("b");
var y = e.ElementsBeforeSelf("b").Element("b");
var y = e.ElementsBeforeSelf().Single().Element("b");
var y = e.ElementsBeforeSelf().Single(x=>x.Name=="b").Element("b");
</code>```

How do I select and return just the single element b, starting with element e?

答:
```<code>var y = e.ElementsBeforeSelf("b").First();
</code>```

Title: Retrieving a sibling xml element

Body:
I have a set of xml elements that are siblings

<z>1</z>
1
<w>1</w>
<n>1</n>
<e>1</e>
<v>1</v>

XElement y is currently pointing to Element e. I now want to look at Element b.

The code

var y = e.ElementsBeforeSelf("b");

does return a collection with just the element b.

Of course, now I need to return just the single element b. I am not always certain that Element b will be a fixed number of elements above e. I am missing something really obvious here because I have not been able with looking at a lot of good articles to figure this out.

Things I have tried:

var y = e.ElementsBeforeSelf().First().Element("b");
var y = e.ElementsBeforeSelf("b").Element("b");
var y = e.ElementsBeforeSelf().Single().Element("b");
var y = e.ElementsBeforeSelf().Single(x=>x.Name=="b").Element("b");

How do I select and return just the single element b, starting with element e?


问:
SSL Certificate for Email Server
Here is the scenario, I have a web application (ASP.NET) and mail server reside on the same server. my website is using a single domain SSL Certificate and my mail is configured as mail.mydomain.com

When I send emails through my web application or the mail client they end up in the junk mail because they are not secured. So I would like to use SSL/TLS Certificate for the mail.mydomain.com

My question is how to do that? can I purchase any separate SSL Certificate for mail.mydomain.com or is there any specific requirement that should be done prior to that.

I'm using Windows Server 2012 and SmarterMail for the mail server (Both on the same server)

答:
You will need to purchase a separate SSL certificate for the mail.domain.com so it can work like https://mail.domain.com

Following is the steps to install SSL on Smartermail.

==> Export SSL Certificate to a Base-64 Encoded Certificate :-

(1) Connect to your VPS/Server through Remote Desktop where you have installed SmarterMail.
  (2) Click Start, select Run. Type MMC, hit enter.
  (3) Open File >> Add\Remove Snap ins.
  (4) From the list of available snap-ins, select Certificates and hit Add.
  (5) A new window will appear, choose Computer account and hit Next.
      Ensure local computer is selected and hit Finish.
  (6) In certificate tree view, expand Personal and choose Certificates.
  (7) Right click on certificate you wish to export >> All Tasks >> Export.
  (8) A new window will appear, hit Next.
  (9) Select No, do not export private key >> Next.

(10) Save the certificate as Base 64 x509 .cer file >> Next.
  (12) Save the certificate at location C:\SmarterMail\Certificates\mail.domain.com. Name the certificate and click Save.

==> Add Ports to Listen Over SSL/TLS at SmarterMail :-

(1) Login to SmarterMail as admin user.
  (2) Click on Settings icon.
  (3) Expand the Bindings folder and click Ports in the navigation pane.
  (4) Click New in the content pane toolbar. A popup window will display.
  (5) Enter required fields;

(A) Protocol : SMTP
(B) Encryption : SSL
(C) Name : SMTP SSL
(D) Port : 465
(E) Certificate Path : C:/Smartermail/Certificates/mail.domain.com
(F) Discription : certificate

(6) Click on Verify Certificate to ensure the certificate exists in the specified path.
  (7) Click on Save.
  (8) Using above steps, add POP3, SMTP and IMAP ports to be encrypted with SSL or TLS.

==> Add Secure Ports to Listen on SmarterMail IP address

(1) Log in to SmarterMail as admin user.
  (2) Click on Settings icon.
  (3) Expand the Bindings folder and click IP Addresses in the navigation pane.
  (4) Select desired IP address and click Edit.
  (5) Binding IP Address
  (6) Use the checkboxes to select the port(s) you would like the IP address to listen on.
  (7) Click Save.
  (8) Restart SmarterMail service.

Now, you can work with SSL for SmarterMail.

Title: SSL Certificate for Email Server


问:
-timestamp in Django
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

```<code>class Meta:
    ordering = ('-timestamp',)
</code>```

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

答:
You have to add Meta to your Model (rather than to the views.py):

```<code>class Post(models.Model):
    title = models.CharField()
    timestamp = (...)

    class Meta:
        ordering = ['-timestamp']
</code>```

Now, whenever you get your Posts they will be ordered by -timestamp.

If you want to learn more about Meta options, take a look at the documentation.

Title: -timestamp in Django

Body:
I'm trying to learn Django. I'm completely green so far. I'm learning from not very good book - first thing we're creating is a simple blog. So, at the end of this excersie they want me to sort my blog post - so the new posts are on top. In order to achieve that im adding:

class Meta:
    ordering = ('-timestamp',)

in views.py. Unfortunately, it changes nothing - my posts are not moving. The book is not very descriptive about that. Do I have to register this class somewhere? I want my pseudo-blog to be pwetty! :P

Thanks in advance.

Body:
You have to add Meta to your Model (rather than to the views.py):

class Post(models.Model):
    title = models.CharField()
    timestamp = (...)

    class Meta:
        ordering = ['-timestamp']

Now, whenever you get your Posts they will be ordered by -timestamp.

If you want to learn more about Meta options, take a look at the documentation.


问:
django server not running on host with vagrant
Vagrantfile:

```<code>config.vm.network "forwarded_port", guest: 8080, host: 8080
</code>```

On my virtual machine I am running this command:

```<code>python manage.py runserver 0.0.0.0:8080
</code>```

But when I try to curl on host machine, response is curl: (52) Empty reply from server and on browser it says 127.0.0.1 didn’t send any data.

I looked on stackoverflow for this problem, most of them were able to resolve it by adding 0.0.0.0 to the runserver command. But, I have already added it.

I tried:

Disabling the firewall and allowing all connections to the virtual machine by accepting all input and output in iptables.

I changed the 127.0.0.1 localhost in /etc/hosts to 0.0.0.0 localhost but still the same response.

I ensured that my host machine is not preventing it by disabling the firewall on my host machine too.

Note: I am using ubuntu machine on virtual box and mac OS on host.

答:
Make sure your port forwards are not auto corrected. If so, halt all the machines and remove the port forwarding cache by following:</p>

```<code>rm -rf ~/.vagrant.d/data/fp-leases
</code>```

Body:
Vagrantfile:

config.vm.network "forwarded_port", guest: 8080, host: 8080

On my virtual machine I am running this command:

python manage.py runserver 0.0.0.0:8080

But when I try to curl on host machine, response is curl: (52) Empty reply from server and on browser it says 127.0.0.1 didn’t send any data.

I looked on stackoverflow for this problem, most of them were able to resolve it by adding 0.0.0.0 to the runserver command. But, I have already added it.

I tried:

Disabling the firewall and allowing all connections to the virtual machine by accepting all input and output in iptables.

I changed the 127.0.0.1 localhost in /etc/hosts to 0.0.0.0 localhost but still the same response.

I ensured that my host machine is not preventing it by disabling the firewall on my host machine too.

Note: I am using ubuntu machine on virtual box and mac OS on host.

Body:
Make sure your port forwards are not auto corrected. If so, halt all the machines and remove the port forwarding cache by following:

rm -rf ~/.vagrant.d/data/fp-leases