问:
Why are structs so much faster than classes for this specific case?
I have three cases to test the relative performance of classes, classes with inheritence and structs. These are to be used for tight  loops so performance counts. Dot products are used as part of many algorithms in 2D and 3D geometry and I have run the profiler on real code. The below tests are indicative of real world performance problems I have seen.

The results for 100000000 times through the loop and application of the dot product gives

```<code>ControlA 208 ms   ( class with inheritence )
ControlB 201 ms   ( class with no inheritence )
ControlC 85  ms   ( struct )
</code>```

The tests were being run without debugging and optimization turned on. My question is, what is it about classes in this case that cause them to be so slow?

I presumed the JIT would still be able to inline all the calls, class or struct, so in effect the results should be identical. Note that if I disable optimizations then my results are identical.

```<code>ControlA 3239
ControlB 3228
ControlC 3213
</code>```

They are always within 20ms of each other if the test is re-run.

The classes under investigation

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

public class PointControlA
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public PointControlA(double x, double y)
    {
        X = x;
        Y = y;
    }
}

public class Point3ControlA : PointControlA
{
    public double Z
    {
        get;
        set;
    }

    public Point3ControlA(double x, double y, double z): base (x, y)
    {
        Z = z;
    }

    public static double Dot(Point3ControlA a, Point3ControlA b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public class Point3ControlB
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlB(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlB a, Point3ControlB b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public struct Point3ControlC
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlC(double x, double y, double z):this()
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlC a, Point3ControlC b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}
</code>```

Test Script

```<code>public class Program
{
    public static void TestStructClass()
    {
        var vControlA = new Point3ControlA(11, 12, 13);
        var vControlB = new Point3ControlB(11, 12, 13);
        var vControlC = new Point3ControlC(11, 12, 13);
        var sw = Stopwatch.StartNew();
        var n = 10000000;
        double acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlA.Dot(vControlA, vControlA);
        }

        Console.WriteLine("ControlA " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlB.Dot(vControlB, vControlB);
        }

        Console.WriteLine("ControlB " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }

        Console.WriteLine("ControlC " + sw.ElapsedMilliseconds);
    }

    public static void Main()
    {
        TestStructClass();
    }
}
</code>```

This dotnet fiddle is proof of compilation only. It does not show the performance differences.

I am trying to explain to a vendor why their choice to use classes instead of structs for small numeric types is a bad idea. I now have the test case to prove it but I can't understand why.

NOTE : I have tried to set a breakpoint in the debugger with JIT optimizations turned on but the debugger will not break. Looking at the IL with JIT optimizations turned off doesn't tell me anything.

EDIT

After the answer by @pkuderov I took his code and played with it. I changed the code and found that if I forced inlining via

```<code>   [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static double Dot(Point3Class a)
    {
        return a.X * a.X + a.Y * a.Y + a.Z * a.Z;
    }
</code>```

the difference between the struct and class for dot product vanished. Why with some setups the attribute is not needed but for me it was is not clear. However I did not give up. There is still a performance problem with the vendor code and I think the DotProduct is not the best example.

I modified @pkuderov's code to implement Vector Add which will create new instances of the structs and classes. The results are here

https://gist.github.com/bradphelan/9b383c8e99edc38068fcc0dccc8a7b48

In the example I also modifed the code to pick a pseudo random vector from an array to avoid the problem of the instances sticking in the registers ( I hope ).

The results show that:

DotProduct performance is identical or maybe faster for classes

Vector Add, and I assume anything that creates a new object is slower.

Add class/class             2777ms
Add struct/struct           2457ms

DotProd class/class         1909ms
DotProd struct/struct       2108ms

The full code and results are here if anybody wants to try it out.

Edit Again

For the vector add example where an array of vectors is summed together the struct version keeps the accumulator in 3 registers

```<code> var accStruct = new Point3Struct(0, 0, 0);
 for (int i = 0; i < n; i++)
     accStruct = Point3Struct.Add(accStruct, pointStruct[(i + 1) % m]);
</code>```

the asm body is

```<code>// load the next vector into a register
00007FFA3CA2240E  vmovsd      xmm3,qword ptr [rax]
00007FFA3CA22413  vmovsd      xmm4,qword ptr [rax+8]
00007FFA3CA22419  vmovsd      xmm5,qword ptr [rax+10h]
// Sum the accumulator (the accumulator stays in the registers )
00007FFA3CA2241F  vaddsd      xmm0,xmm0,xmm3
00007FFA3CA22424  vaddsd      xmm1,xmm1,xmm4
00007FFA3CA22429  vaddsd      xmm2,xmm2,xmm5
</code>```

but for class based vector version it reads and writes out the accumulator each time to main memory which is inefficient

```<code>var accPC = new Point3Class(0, 0, 0);
for (int i = 0; i < n; i++)
    accPC = Point3Class.Add(accPC, pointClass[(i + 1) % m]);
</code>```

the asm body is

```<code>// Read and add both accumulator X and Xnext from main memory
00007FFA3CA2224A  vmovsd      xmm0,qword ptr [r14+8]
00007FFA3CA22250  vmovaps     xmm7,xmm0
00007FFA3CA22255  vaddsd      xmm7,xmm7,mmword ptr [r12+8]

// Read and add both accumulator Y and Ynext from main memory
00007FFA3CA2225C  vmovsd      xmm0,qword ptr [r14+10h]
00007FFA3CA22262  vmovaps     xmm8,xmm0
00007FFA3CA22267  vaddsd      xmm8,xmm8,mmword ptr [r12+10h]

// Read and add both accumulator Z and Znext from main memory
00007FFA3CA2226E  vmovsd      xmm9,qword ptr [r14+18h]
00007FFA3CA22283  vmovaps     xmm0,xmm9
00007FFA3CA22288  vaddsd      xmm0,xmm0,mmword ptr [r12+18h]

// Move accumulator accumulator X,Y,Z back to main memory.
00007FFA3CA2228F  vmovsd      qword ptr [rax+8],xmm7
00007FFA3CA22295  vmovsd      qword ptr [rax+10h],xmm8
00007FFA3CA2229B  vmovsd      qword ptr [rax+18h],xmm0
</code>```

答:
As I thought , this test doesn't prove much.

TLDR: the compiler completely optimizes away the call to Point3ControlC.Dot while preserves the calls to the other two. the difference is not because structs are faster in this case, but because you skip the entire calculation part.

My settings:

Visual studio 2015 update 3

.Net framework version 4.6.1

Release mode, Any CPU (my  CPU is 64 bit)

Windows 10

CPU: Processor   Intel(R) Core(TM) i5-5300U CPU @ 2.30GHz, 2295 Mhz, 2 Core(s), 4 Logical Processor(s)

The generated assembly for

```<code>for (int i = 0; i < n; i++)
        {
            acc += Point3ControlA.Dot(vControlA, vControlA);
        }
</code>```

is:

```<code>00DC0573  xor         edx,edx  // temp = 0
00DC0575  mov         dword ptr [ebp-10h],edx // i = temp
00DC0578  mov         ecx,edi  // load vControlA as first parameter
00DC057A  mov         edx,edi  //load vControlA as second parameter
00DC057C  call        dword ptr ds:[0BA4F0Ch] //call Point3ControlA.Dot
00DC0582  fstp        st(0)  //store the result
00DC0584  inc         dword ptr [ebp-10h]  //i++
00DC0587  cmp         dword ptr [ebp-10h],989680h //does i == n?
00DC058E  jl          00DC0578  //if not, jump to the begining of the loop
</code>```

After thoughts:

The JIT compiler for some reason did not use a register for i, so it incremented an integer on the stack (ebp-10h) instead. as result, this test has the poorest performance.

Moving on to the second test:

```<code>for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }
</code>```

Generated assembly:

```<code>00DC0612  xor         edi,edi  //i = 0
00DC0614  mov         ecx,esi  //load vControlB as the first argument
00DC0616  mov         edx,esi  //load vControlB as the second argument
00DC0618  call        dword ptr ds:[0BA4FD4h] // call Point3ControlB.Dot
00DC061E  fstp        st(0) //store the result
00DC0620  inc         edi  //++i
00DC0621  cmp         edi,989680h //does i == n
00DC0627  jl          00DC0614  //if not, jump to the beginning of the loop
</code>```

After thoughts: this generated assembly is almost identical to the first one, but this time, the JIT did use a register for i, hence the minor performance boost over the first test.

Moving on to the test in question:

```<code>for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }
</code>```

And for the generated assembly:

```<code>00DC06A7  xor         eax,eax  //i = 0
00DC06A9  inc         eax  //++i
00DC06AA  cmp         eax,989680h //does i == n ?
00DC06AF  jl          00DC06A9  //if not, jump to the beginning of the loop
</code>```

As we can see, the JIT has completely optimized away the call for Point3ControlC.Dot , so actually, you only pay for the loop, and not for the call itself. hence this "test" finishes first, as it didn't do much to begin with.

Can we say something about structs vs classes from this test alone? well, no.
I'm still not quit sure why has the compiler decided to optimize out the call for the struct-function while preserved the other calls. what I'm sure about is that in real-life code, the compiler can not optimize the call away if the result is used. in this mini-benchmark, we don't do much with the result and even if we did, the compiler can calculate the result on compile time. so the compiler can be more aggressive than it could have been than in real-life code.

Body:
I have three cases to test the relative performance of classes, classes with inheritence and structs. These are to be used for tight  loops so performance counts. Dot products are used as part of many algorithms in 2D and 3D geometry and I have run the profiler on real code. The below tests are indicative of real world performance problems I have seen.

The results for 100000000 times through the loop and application of the dot product gives

ControlA 208 ms   ( class with inheritence )
ControlB 201 ms   ( class with no inheritence )
ControlC 85  ms   ( struct )

The tests were being run without debugging and optimization turned on. My question is, what is it about classes in this case that cause them to be so slow?

I presumed the JIT would still be able to inline all the calls, class or struct, so in effect the results should be identical. Note that if I disable optimizations then my results are identical.

ControlA 3239
ControlB 3228
ControlC 3213

They are always within 20ms of each other if the test is re-run.

The classes under investigation

using System;
using System.Diagnostics;

public class PointControlA
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public PointControlA(double x, double y)
    {
        X = x;
        Y = y;
    }
}

public class Point3ControlA : PointControlA
{
    public double Z
    {
        get;
        set;
    }

    public Point3ControlA(double x, double y, double z): base (x, y)
    {
        Z = z;
    }

    public static double Dot(Point3ControlA a, Point3ControlA b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public class Point3ControlB
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlB(double x, double y, double z)
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlB a, Point3ControlB b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

public struct Point3ControlC
{
    public double X
    {
        get;
        set;
    }

    public double Y
    {
        get;
        set;
    }

    public double Z
    {
        get;
        set;
    }

    public Point3ControlC(double x, double y, double z):this()
    {
        X = x;
        Y = y;
        Z = z;
    }

    public static double Dot(Point3ControlC a, Point3ControlC b)
    {
        return a.X * b.X + a.Y * b.Y + a.Z * b.Z;
    }
}

Test Script

public class Program
{
    public static void TestStructClass()
    {
        var vControlA = new Point3ControlA(11, 12, 13);
        var vControlB = new Point3ControlB(11, 12, 13);
        var vControlC = new Point3ControlC(11, 12, 13);
        var sw = Stopwatch.StartNew();
        var n = 10000000;
        double acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlA.Dot(vControlA, vControlA);
        }

        Console.WriteLine("ControlA " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlB.Dot(vControlB, vControlB);
        }

        Console.WriteLine("ControlB " + sw.ElapsedMilliseconds);
        acc = 0;
        sw = Stopwatch.StartNew();
        for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }

        Console.WriteLine("ControlC " + sw.ElapsedMilliseconds);
    }

    public static void Main()
    {
        TestStructClass();
    }
}

This dotnet fiddle is proof of compilation only. It does not show the performance differences.

I am trying to explain to a vendor why their choice to use classes instead of structs for small numeric types is a bad idea. I now have the test case to prove it but I can't understand why.

NOTE : I have tried to set a breakpoint in the debugger with JIT optimizations turned on but the debugger will not break. Looking at the IL with JIT optimizations turned off doesn't tell me anything.

EDIT

After the answer by @pkuderov I took his code and played with it. I changed the code and found that if I forced inlining via

   [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static double Dot(Point3Class a)
    {
        return a.X * a.X + a.Y * a.Y + a.Z * a.Z;
    }

the difference between the struct and class for dot product vanished. Why with some setups the attribute is not needed but for me it was is not clear. However I did not give up. There is still a performance problem with the vendor code and I think the DotProduct is not the best example.

I modified @pkuderov's code to implement Vector Add which will create new instances of the structs and classes. The results are here

https://gist.github.com/bradphelan/9b383c8e99edc38068fcc0dccc8a7b48

In the example I also modifed the code to pick a pseudo random vector from an array to avoid the problem of the instances sticking in the registers ( I hope ).

The results show that:

DotProduct performance is identical or maybe faster for classes

Vector Add, and I assume anything that creates a new object is slower.

Add class/class             2777ms
Add struct/struct           2457ms

DotProd class/class         1909ms
DotProd struct/struct       2108ms

The full code and results are here if anybody wants to try it out.

Edit Again

For the vector add example where an array of vectors is summed together the struct version keeps the accumulator in 3 registers

 var accStruct = new Point3Struct(0, 0, 0);
 for (int i = 0; i < n; i++)
     accStruct = Point3Struct.Add(accStruct, pointStruct[(i + 1) % m]);

the asm body is

// load the next vector into a register
00007FFA3CA2240E  vmovsd      xmm3,qword ptr [rax]
00007FFA3CA22413  vmovsd      xmm4,qword ptr [rax+8]
00007FFA3CA22419  vmovsd      xmm5,qword ptr [rax+10h]
// Sum the accumulator (the accumulator stays in the registers )
00007FFA3CA2241F  vaddsd      xmm0,xmm0,xmm3
00007FFA3CA22424  vaddsd      xmm1,xmm1,xmm4
00007FFA3CA22429  vaddsd      xmm2,xmm2,xmm5

but for class based vector version it reads and writes out the accumulator each time to main memory which is inefficient

var accPC = new Point3Class(0, 0, 0);
for (int i = 0; i < n; i++)
    accPC = Point3Class.Add(accPC, pointClass[(i + 1) % m]);

the asm body is

// Read and add both accumulator X and Xnext from main memory
00007FFA3CA2224A  vmovsd      xmm0,qword ptr [r14+8]
00007FFA3CA22250  vmovaps     xmm7,xmm0
00007FFA3CA22255  vaddsd      xmm7,xmm7,mmword ptr [r12+8]

// Read and add both accumulator Y and Ynext from main memory
00007FFA3CA2225C  vmovsd      xmm0,qword ptr [r14+10h]
00007FFA3CA22262  vmovaps     xmm8,xmm0
00007FFA3CA22267  vaddsd      xmm8,xmm8,mmword ptr [r12+10h]

// Read and add both accumulator Z and Znext from main memory
00007FFA3CA2226E  vmovsd      xmm9,qword ptr [r14+18h]
00007FFA3CA22283  vmovaps     xmm0,xmm9
00007FFA3CA22288  vaddsd      xmm0,xmm0,mmword ptr [r12+18h]

// Move accumulator accumulator X,Y,Z back to main memory.
00007FFA3CA2228F  vmovsd      qword ptr [rax+8],xmm7
00007FFA3CA22295  vmovsd      qword ptr [rax+10h],xmm8
00007FFA3CA2229B  vmovsd      qword ptr [rax+18h],xmm0

Body:
As I thought , this test doesn't prove much.

TLDR: the compiler completely optimizes away the call to Point3ControlC.Dot while preserves the calls to the other two. the difference is not because structs are faster in this case, but because you skip the entire calculation part.

My settings:

Visual studio 2015 update 3

.Net framework version 4.6.1

Release mode, Any CPU (my  CPU is 64 bit)

Windows 10

CPU: Processor   Intel(R) Core(TM) i5-5300U CPU @ 2.30GHz, 2295 Mhz, 2 Core(s), 4 Logical Processor(s)

The generated assembly for

for (int i = 0; i < n; i++)
        {
            acc += Point3ControlA.Dot(vControlA, vControlA);
        }

is:

00DC0573  xor         edx,edx  // temp = 0
00DC0575  mov         dword ptr [ebp-10h],edx // i = temp
00DC0578  mov         ecx,edi  // load vControlA as first parameter
00DC057A  mov         edx,edi  //load vControlA as second parameter
00DC057C  call        dword ptr ds:[0BA4F0Ch] //call Point3ControlA.Dot
00DC0582  fstp        st(0)  //store the result
00DC0584  inc         dword ptr [ebp-10h]  //i++
00DC0587  cmp         dword ptr [ebp-10h],989680h //does i == n?
00DC058E  jl          00DC0578  //if not, jump to the begining of the loop

After thoughts:

The JIT compiler for some reason did not use a register for i, so it incremented an integer on the stack (ebp-10h) instead. as result, this test has the poorest performance.

Moving on to the second test:

for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }

Generated assembly:

00DC0612  xor         edi,edi  //i = 0
00DC0614  mov         ecx,esi  //load vControlB as the first argument
00DC0616  mov         edx,esi  //load vControlB as the second argument
00DC0618  call        dword ptr ds:[0BA4FD4h] // call Point3ControlB.Dot
00DC061E  fstp        st(0) //store the result
00DC0620  inc         edi  //++i
00DC0621  cmp         edi,989680h //does i == n
00DC0627  jl          00DC0614  //if not, jump to the beginning of the loop

After thoughts: this generated assembly is almost identical to the first one, but this time, the JIT did use a register for i, hence the minor performance boost over the first test.

Moving on to the test in question:

for (int i = 0; i < n; i++)
        {
            acc += Point3ControlC.Dot(vControlC, vControlC);
        }

And for the generated assembly:

00DC06A7  xor         eax,eax  //i = 0
00DC06A9  inc         eax  //++i
00DC06AA  cmp         eax,989680h //does i == n ?
00DC06AF  jl          00DC06A9  //if not, jump to the beginning of the loop

As we can see, the JIT has completely optimized away the call for Point3ControlC.Dot , so actually, you only pay for the loop, and not for the call itself. hence this "test" finishes first, as it didn't do much to begin with.

Can we say something about structs vs classes from this test alone? well, no.
I'm still not quit sure why has the compiler decided to optimize out the call for the struct-function while preserved the other calls. what I'm sure about is that in real-life code, the compiler can not optimize the call away if the result is used. in this mini-benchmark, we don't do much with the result and even if we did, the compiler can calculate the result on compile time. so the compiler can be more aggressive than it could have been than in real-life code.


来源: stackexchange

问:
In prometheus all target servers show as down with this error: dial tcp 10.7.17.11:9100: getsockopt: connection timed out
I have configured the Node Exporter in Kubernetes and start monitoring using Prometheus, But in Prometheus all servers are showing as down with the error below:

Get http://10.7.17.11:9100/metrics: dial tcp 10.7.17.11:9100:
  getsockopt: connection timed out

Can anyone help why it is showing down ?

答:
Make sure firewall is not blocking port 9100.
Try to curl this URL from other nodes and from the prometheus pod</p>

ContentLicense: CC BY-SA 3.0


问:
How do I get the XML root node with C#?
I know that it's possible to get any XML node using C# if you know the node name, but I want to get the root node so that I can find out the name. Is this possible?

Update: I'm using XMLTextReader to read in the URL of a file and then loading that into XMLDocument object. Basically I'm trying to avoid LINQ to XML, but if there's another, better way then I'm always a good student.

答:
Root node is the DocumentElement property of XmlDocument

```<code>XmlElement root = xmlDoc.DocumentElement
</code>```

If you only have the node, you can get the root node by

```<code>XmlElement root = xmlNode.OwnerDocument.DocumentElement
</code>```

ContentLicense: CC BY-SA 2.5

Title: How do I get the XML root node with C#?

Body:
Root node is the DocumentElement property of XmlDocument

XmlElement root = xmlDoc.DocumentElement

If you only have the node, you can get the root node by

XmlElement root = xmlNode.OwnerDocument.DocumentElement


问:
Cartopy: subsetting features for plotting a specific river
Working in Python3 with cartopy, I am trying to subset and plot a specific river from the Natureal Earth database.

It is quite straightforward to plot all the rivers and then set the extent over a particular area:

```<code>import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature

rivers = cartopy.feature.NaturalEarthFeature(
    category='physical', name='rivers_lake_centerlines',
    scale='10m', facecolor='none', edgecolor='blue')

fig, ax = plt.subplots(
    nrows=1, ncols=1, subplot_kw={'projection': ccrs.PlateCarree()},
                         figsize=(10,6))
ax.add_feature(rivers, linewidth=1)
ax.set_extent([-65, -45, -40, -17.5])
plt.show()
</code>```

(Results shown below)

However, if I wish to plot only a particular river (for purposes of illustration the Paraná, which is named Paran? in the data due to encoding issues, there doesn't seem to be a clear way to do this The cartopy Feature interface documentation

答:
You need to use cartopy.io.shapereader, here is the code that works on my computer:

```<code>from cartopy import config
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io import shapereader

#config  # format-dict

# assuming you have downloaded that file already using your original code
# its full path name should be (Windows)
fpath = config['data_dir'] + r'\shapefiles\natural_earth\physical\10m_rivers_lake_centerlines.shp'

as_shp = shapereader.Reader( fpath )

fig, ax = plt.subplots( nrows=1, ncols=1, \
                       subplot_kw={'projection': ccrs.PlateCarree()}, \
                       figsize=(10,6) )

# plot some geometries, based on their attribs
for rec in as_shp.records():
    if rec.attributes['name'] == 'Parana?ba':
        ax.add_geometries( [rec.geometry], ccrs.PlateCarree(), edgecolor='none', facecolor='blue' )
    pass

ax.coastlines( resolution='110m' )
ax.set_extent([-65, -45, -40, -17.5])
plt.show()
</code>```

Body:
Working in Python3 with cartopy, I am trying to subset and plot a specific river from the Natureal Earth database.

It is quite straightforward to plot all the rivers and then set the extent over a particular area:

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature

rivers = cartopy.feature.NaturalEarthFeature(
    category='physical', name='rivers_lake_centerlines',
    scale='10m', facecolor='none', edgecolor='blue')

fig, ax = plt.subplots(
    nrows=1, ncols=1, subplot_kw={'projection': ccrs.PlateCarree()},
                         figsize=(10,6))
ax.add_feature(rivers, linewidth=1)
ax.set_extent([-65, -45, -40, -17.5])
plt.show()

(Results shown below)

However, if I wish to plot only a particular river (for purposes of illustration the Paraná, which is named Paran? in the data due to encoding issues, there doesn't seem to be a clear way to do this The cartopy Feature interface documentation

Body:
You need to use cartopy.io.shapereader, here is the code that works on my computer:

from cartopy import config
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
from cartopy.io import shapereader

#config  # format-dict

# assuming you have downloaded that file already using your original code
# its full path name should be (Windows)
fpath = config['data_dir'] + r'\shapefiles\natural_earth\physical\10m_rivers_lake_centerlines.shp'

as_shp = shapereader.Reader( fpath )

fig, ax = plt.subplots( nrows=1, ncols=1, \
                       subplot_kw={'projection': ccrs.PlateCarree()}, \
                       figsize=(10,6) )

# plot some geometries, based on their attribs
for rec in as_shp.records():
    if rec.attributes['name'] == 'Parana?ba':
        ax.add_geometries( [rec.geometry], ccrs.PlateCarree(), edgecolor='none', facecolor='blue' )
    pass

ax.coastlines( resolution='110m' )
ax.set_extent([-65, -45, -40, -17.5])
plt.show()


问:
Switch language in jinja template
I'm migrating a multi lingual Django application from Django's template engine to Jinja2. In the templates I currently switch the active language on a per object basis using Django's language template tag i.e.:

```<code>{% load i18n %}
<h1>{% trans 'Page title' %}</h1>
<ul>
{% for obj in object_list %}
{% language obj.language_code %}
    <li><a href="{{ obj.get_absolute_url }}">{% trans 'view' %}: {{ obj.title }}</a>
{% endlanguage %}
{% endfor %}
</ul>
</code>```

We also use i18n_patterns so the urls of each object are language specific as well.

I'm stuck on how to convert this to Jinja. I cannot use Django's i18n template tags and cannot find something equivalent for Jinja.

I was also looking at Babel to help with extracting messages from the templates. So a solution that works with Babel as well as with Django would be preferred.

答:
I have this code snippet to switch between languages in jinja2.

```<code>def change_lang(request, lang=None, *args, **kwargs):
"""
Get active page's url by a specified language, it activates
Usage: {{ change_lang(request, 'en') }}
"""

path = request.path
url_parts = resolve(path)

url = path
cur_language = get_language()
try:
    activate(lang)
    url = reverse(url_parts.view_name, kwargs=url_parts.kwargs)
finally:
    activate(cur_language)

return "%s" % url
</code>```

in settings.py

```<code>TEMPLATES = [
{
    "BACKEND": "django_jinja.backend.Jinja2",
    'DIRS': [
        os.path.join(BASE_DIR, 'templates/jinja'),
    ],
    "OPTIONS": {
        # Match the template names ending in .html but not the ones in the admin folder.
        "match_extension": ".html",
        "match_regex": r"^(?!admin/).*",
        "newstyle_gettext": True,
        "extensions": [
            "jinja2.ext.do",
            "jinja2.ext.loopcontrols",
            "jinja2.ext.with_",
            "jinja2.ext.i18n",
            "jinja2.ext.autoescape",
            "django_jinja.builtins.extensions.CsrfExtension",
            "django_jinja.builtins.extensions.CacheExtension",
            "django_jinja.builtins.extensions.TimezoneExtension",
            "django_jinja.builtins.extensions.UrlsExtension",
            "django_jinja.builtins.extensions.StaticFilesExtension",
            "django_jinja.builtins.extensions.DjangoFiltersExtension",
        ],
        'globals': {
            'change_lang': 'drug.utils.change_lang'
        },
        "bytecode_cache": {
            "name": "default",
            "backend": "django_jinja.cache.BytecodeCache",
            "enabled": False,
        },
        "autoescape": True,
        "auto_reload": DEBUG,
        "translation_engine": "django.utils.translation",
        "context_processors": [
            "dashboard.context_processors.auth",
            # "django.template.context_processors.debug",
            "django.template.context_processors.i18n",
            # "django.template.context_processors.media",
            # "django.template.context_processors.static",
            # "django.template.context_processors.tz",
            "django.contrib.messages.context_processors.messages",
        ]
    }
},
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        os.path.join(BASE_DIR, 'templates'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ]
    },
},]
</code>```

and then you can use this in anywhere in your templates {{ _('Hello World') }}

Title: Switch language in jinja template

Body:
I'm migrating a multi lingual Django application from Django's template engine to Jinja2. In the templates I currently switch the active language on a per object basis using Django's language template tag i.e.:

{% load i18n %}

{% trans 'Page title' %}

{% for obj in object_list %}
{% language obj.language_code %}

{% trans 'view' %}: {{ obj.title }}
{% endlanguage %}
{% endfor %}

We also use i18n_patterns so the urls of each object are language specific as well.

I'm stuck on how to convert this to Jinja. I cannot use Django's i18n template tags and cannot find something equivalent for Jinja.

I was also looking at Babel to help with extracting messages from the templates. So a solution that works with Babel as well as with Django would be preferred.

Body:
I have this code snippet to switch between languages in jinja2.

def change_lang(request, lang=None, *args, **kwargs):
"""
Get active page's url by a specified language, it activates
Usage: {{ change_lang(request, 'en') }}
"""

path = request.path
url_parts = resolve(path)

url = path
cur_language = get_language()
try:
    activate(lang)
    url = reverse(url_parts.view_name, kwargs=url_parts.kwargs)
finally:
    activate(cur_language)

return "%s" % url

in settings.py

TEMPLATES = [
{
    "BACKEND": "django_jinja.backend.Jinja2",
    'DIRS': [
        os.path.join(BASE_DIR, 'templates/jinja'),
    ],
    "OPTIONS": {
        # Match the template names ending in .html but not the ones in the admin folder.
        "match_extension": ".html",
        "match_regex": r"^(?!admin/).*",
        "newstyle_gettext": True,
        "extensions": [
            "jinja2.ext.do",
            "jinja2.ext.loopcontrols",
            "jinja2.ext.with_",
            "jinja2.ext.i18n",
            "jinja2.ext.autoescape",
            "django_jinja.builtins.extensions.CsrfExtension",
            "django_jinja.builtins.extensions.CacheExtension",
            "django_jinja.builtins.extensions.TimezoneExtension",
            "django_jinja.builtins.extensions.UrlsExtension",
            "django_jinja.builtins.extensions.StaticFilesExtension",
            "django_jinja.builtins.extensions.DjangoFiltersExtension",
        ],
        'globals': {
            'change_lang': 'drug.utils.change_lang'
        },
        "bytecode_cache": {
            "name": "default",
            "backend": "django_jinja.cache.BytecodeCache",
            "enabled": False,
        },
        "autoescape": True,
        "auto_reload": DEBUG,
        "translation_engine": "django.utils.translation",
        "context_processors": [
            "dashboard.context_processors.auth",
            # "django.template.context_processors.debug",
            "django.template.context_processors.i18n",
            # "django.template.context_processors.media",
            # "django.template.context_processors.static",
            # "django.template.context_processors.tz",
            "django.contrib.messages.context_processors.messages",
        ]
    }
},
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [
        os.path.join(BASE_DIR, 'templates'),
    ],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ]
    },
},]

and then you can use this in anywhere in your templates {{ _('Hello World') }}


问:
How do I implement CORS from IE11 using C# and JQuery.ajax?
I'm struggling to get CORS to work via IE11.

I have to make ajax requests using jquery (or with whatever the browser supports natively), no additional libraries. These requests are cross-domain and they work perfectly in Chrome and Firefox.

```<code>$.ajax(otherDomainConnectUrl, {
        contentType: 'application/json',
        dataType: 'json',
        crossDomain: true,
        success: (connectParams, textStatus, jqxhr) => {
            console.log('Connect ok. Params: ', connectParams);
            success(connectParams);
        },
        error:  (jqxr, textStatus, errorThrown) => {
            this.errorRenderer.renderError(connectionError);
            console.log('jquery error results:', jqxr, textStatus, errorThrown);
        }
    });
</code>```

On the server-side I use ASP.NET MVC and C#. I do a CORS-check using a custom attribute on my controller action:

```<code>    [AllowCrossSiteJson]
    public string Connect()
    {
        // ... logic logic...
        var serializedMessage = JsonConvert.SerializeObject(databag, settings);
        return serializedMessage;
    }
</code>```

The CORS custom attribute has the following logic. Note how I retrieve a list of valid domains, then check if the Referrer URL is one of those domains, and then choose to accept/deny the CORS request:

```<code>    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var allowedDomains = ClientSpecificConfig.GetAllowedHostDomains();

        if (filterContext?.RequestContext?.HttpContext?.Request?.UrlReferrer != null
            && allowedDomains.Contains(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Host))
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        }

        base.OnActionExecuting(filterContext);
    }
</code>```

So I only append Access-Control-Allow-Origin:* for known domains. I don't want to open the action to calls from absolutely any host anywhere.

The problem is that IE11 does not supply the Referrer at all, so I can't approve the CORS check by adding the necessary headers. So how do I check if the source host is a valid host when the script is running in IE11?

答:
You can add a custom header with jQuery:

```<code>// Request with custom header
$.ajax({
    headers: { 'x-cors-auth': window.location.href }
});
</code>```

From here you can set these headers to whatever value you want. Since IE isn't sending a referrer you can try actual setting the referrer header.

You can also use $.ajaxSetup to specify headers that will be sent on every request or you will be calling multiple domains you use before send:

```<code>$.ajaxSetup({
    beforeSend: function(xhr) {
        headers: { 'x-cors-auth': window.location.href }
    }
});
</code>```

Body:
I'm struggling to get CORS to work via IE11.

I have to make ajax requests using jquery (or with whatever the browser supports natively), no additional libraries. These requests are cross-domain and they work perfectly in Chrome and Firefox.

$.ajax(otherDomainConnectUrl, {
        contentType: 'application/json',
        dataType: 'json',
        crossDomain: true,
        success: (connectParams, textStatus, jqxhr) => {
            console.log('Connect ok. Params: ', connectParams);
            success(connectParams);
        },
        error:  (jqxr, textStatus, errorThrown) => {
            this.errorRenderer.renderError(connectionError);
            console.log('jquery error results:', jqxr, textStatus, errorThrown);
        }
    });

On the server-side I use ASP.NET MVC and C#. I do a CORS-check using a custom attribute on my controller action:

    [AllowCrossSiteJson]
    public string Connect()
    {
        // ... logic logic...
        var serializedMessage = JsonConvert.SerializeObject(databag, settings);
        return serializedMessage;
    }

The CORS custom attribute has the following logic. Note how I retrieve a list of valid domains, then check if the Referrer URL is one of those domains, and then choose to accept/deny the CORS request:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var allowedDomains = ClientSpecificConfig.GetAllowedHostDomains();

        if (filterContext?.RequestContext?.HttpContext?.Request?.UrlReferrer != null
            && allowedDomains.Contains(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Host))
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        }

        base.OnActionExecuting(filterContext);
    }

So I only append Access-Control-Allow-Origin:* for known domains. I don't want to open the action to calls from absolutely any host anywhere.

The problem is that IE11 does not supply the Referrer at all, so I can't approve the CORS check by adding the necessary headers. So how do I check if the source host is a valid host when the script is running in IE11?

Body:
You can add a custom header with jQuery:

// Request with custom header
$.ajax({
    headers: { 'x-cors-auth': window.location.href }
});

From here you can set these headers to whatever value you want. Since IE isn't sending a referrer you can try actual setting the referrer header.

You can also use $.ajaxSetup to specify headers that will be sent on every request or you will be calling multiple domains you use before send:

$.ajaxSetup({
    beforeSend: function(xhr) {
        headers: { 'x-cors-auth': window.location.href }
    }
});


问:
Parse error in list monad's `do` notation
OK, so here's a weird one.

This works perfectly:

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]
</code>```

But this:

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]
</code>```

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)

答:
After do, each line which starts on the same column as the first word after do starts a new entry. With explicit braces, your code is equivalent to

```<code>test = do
  { x <- [1..5]
  ; y <- [1..5]
  ; [
      x+y,
      x-y
  ; ]
  }
</code>```

This is due to the indentation rules. As we can see, the last semicolon should not be there -- to avoid it, we should indent the last line more.

Body:
OK, so here's a weird one.

This works perfectly:

test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]

But this:

test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)

Body:
After do, each line which starts on the same column as the first word after do starts a new entry. With explicit braces, your code is equivalent to

test = do
  { x <- [1..5]
  ; y <- [1..5]
  ; [
      x+y,
      x-y
  ; ]
  }

This is due to the indentation rules. As we can see, the last semicolon should not be there -- to avoid it, we should indent the last line more.


问:
Setting up a Selenium node on Linux
I am currently trying to set up a Selenium node on a Linux VM (headless). The hub is being run from a Windows device on port 5786 (4444 was in use).

I initiate the hub using the following code:

```<code>java -jar selenium-server-standalone-
2.53.0.jar -role node –hub http://<myIP>:5786/grid/register -port 5558
</code>```

When i execute this, it returns the following error messages:

```<code>13:42:12.765 INFO - Launching a Selenium Grid node
13:42:13.435 WARN - error getting the parameters from the hub. The node may
end up with wrong timeouts.Connect to 10.146.48.80:4444 [/10.146.48.80]
failed: Connection refused
13:42:13.445 INFO - Java: Oracle Corporation 24.60-b09
13:42:13.445 INFO - OS: Linux 3.10.0-514.21.1.el7.x86_64 amd64
13:42:13.450 INFO - v2.53.0, with Core v2.53.0. Built from revision 35ae25b
13:42:13.521 INFO - Driver provider
org.openqa.selenium.ie.InternetExplorerDriver registration is skipped:
registration capabilities Capabilities [{platform=WINDOWS,
ensureCleanSession=true, browserName=internet explorer, version=}] does not
match the current platform LINUX
13:42:13.521 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver
registration is skipped:
registration capabilities Capabilities [{platform=WINDOWS,
browserName=MicrosoftEdge, version=}] does not match the current platform
LINUX
13:42:13.521 INFO - Driver class not found:
com.opera.core.systems.OperaDriver
13:42:13.521 INFO - Driver provider com.opera.core.systems.OperaDriver is not
registered
13:42:13.522 INFO - Driver provider org.openqa.selenium.safari.SafariDriver
registration is skipped:
registration capabilities Capabilities [{platform=MAC, browserName=safari,
version=}] does not match the current platform LINUX
13:42:13.523 INFO - Driver class not found:
org.openqa.selenium.htmlunit.HtmlUnitDriver
13:42:13.523 INFO - Driver provider
org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
13:42:13.552 INFO - Version Jetty/5.1.x
13:42:13.553 INFO - Started HttpContext[/selenium-server/driver,/selenium-
server/driver]
 13:42:13.553 INFO - Started HttpContext[/selenium-server,/selenium-server]
13:42:13.553 INFO - Started HttpContext[/,/]
13:44:03.596 INFO - Started
org.openqa.jetty.jetty.servlet.ServletHandler@188fd321
13:44:03.596 INFO - Started HttpContext[/wd,/wd]
13:44:03.599 INFO - Started SocketListener on 0.0.0.0:5555
13:44:03.599 INFO - Started org.openqa.jetty.jetty.Server@a01330f
13:44:03.599 INFO - Selenium Grid node is up and ready to register to the hub
13:44:03.630 INFO - Starting auto registration thread. Will try to register
every 5000 ms.
13:44:03.630 INFO - Registering the node to the hub:
http://10.146.48.80:4444/grid/register
13:44:03.638 INFO - Couldn't register this node: Error sending the
registration request: Connect to 10.146.48.80:4444 [/10.146.48.80] failed:
Connection refused
</code>```

答:
In the command that you shared viz.,

```<code>java -jar selenium-server-standalone-2.53.0.jar -role node –hub http://<myIP>:5786/grid/register -port 5558
</code>```

You have a copy paste problem. The - before the parameter hub doesn't seem to be a hyphen character.

I was able to deduce this as a possible root cause because the value of -hub is completely being ignored and the default hub port of 4444 is being attempted to use. The stacktrace that you shared re-iterates this

13:42:13.435 WARN - error getting the parameters from the hub. The node may
  end up with wrong timeouts.Connect to 10.146.48.80:4444 [/10.146.48.80]
  failed: Connection refused

As you can see, even though you are providing your Hub's registration URL to include a port number of 5786, its still picking up 4444 and complaining Connection refused.

Please try typing out the entire command for starting the hub and try again. That should work.

Title: Setting up a Selenium node on Linux

Body:
I am currently trying to set up a Selenium node on a Linux VM (headless). The hub is being run from a Windows device on port 5786 (4444 was in use).

I initiate the hub using the following code:

java -jar selenium-server-standalone-
2.53.0.jar -role node –hub http://<myIP>:5786/grid/register -port 5558

When i execute this, it returns the following error messages:

13:42:12.765 INFO - Launching a Selenium Grid node
13:42:13.435 WARN - error getting the parameters from the hub. The node may
end up with wrong timeouts.Connect to 10.146.48.80:4444 [/10.146.48.80]
failed: Connection refused
13:42:13.445 INFO - Java: Oracle Corporation 24.60-b09
13:42:13.445 INFO - OS: Linux 3.10.0-514.21.1.el7.x86_64 amd64
13:42:13.450 INFO - v2.53.0, with Core v2.53.0. Built from revision 35ae25b
13:42:13.521 INFO - Driver provider
org.openqa.selenium.ie.InternetExplorerDriver registration is skipped:
registration capabilities Capabilities [{platform=WINDOWS,
ensureCleanSession=true, browserName=internet explorer, version=}] does not
match the current platform LINUX
13:42:13.521 INFO - Driver provider org.openqa.selenium.edge.EdgeDriver
registration is skipped:
registration capabilities Capabilities [{platform=WINDOWS,
browserName=MicrosoftEdge, version=}] does not match the current platform
LINUX
13:42:13.521 INFO - Driver class not found:
com.opera.core.systems.OperaDriver
13:42:13.521 INFO - Driver provider com.opera.core.systems.OperaDriver is not
registered
13:42:13.522 INFO - Driver provider org.openqa.selenium.safari.SafariDriver
registration is skipped:
registration capabilities Capabilities [{platform=MAC, browserName=safari,
version=}] does not match the current platform LINUX
13:42:13.523 INFO - Driver class not found:
org.openqa.selenium.htmlunit.HtmlUnitDriver
13:42:13.523 INFO - Driver provider
org.openqa.selenium.htmlunit.HtmlUnitDriver is not registered
13:42:13.552 INFO - Version Jetty/5.1.x
13:42:13.553 INFO - Started HttpContext[/selenium-server/driver,/selenium-
server/driver]
 13:42:13.553 INFO - Started HttpContext[/selenium-server,/selenium-server]
13:42:13.553 INFO - Started HttpContext[/,/]
13:44:03.596 INFO - Started
org.openqa.jetty.jetty.servlet.ServletHandler@188fd321
13:44:03.596 INFO - Started HttpContext[/wd,/wd]
13:44:03.599 INFO - Started SocketListener on 0.0.0.0:5555
13:44:03.599 INFO - Started org.openqa.jetty.jetty.Server@a01330f
13:44:03.599 INFO - Selenium Grid node is up and ready to register to the hub
13:44:03.630 INFO - Starting auto registration thread. Will try to register
every 5000 ms.
13:44:03.630 INFO - Registering the node to the hub:
http://10.146.48.80:4444/grid/register
13:44:03.638 INFO - Couldn't register this node: Error sending the
registration request: Connect to 10.146.48.80:4444 [/10.146.48.80] failed:
Connection refused

Body:
In the command that you shared viz.,

java -jar selenium-server-standalone-2.53.0.jar -role node –hub http://<myIP>:5786/grid/register -port 5558

You have a copy paste problem. The - before the parameter hub doesn't seem to be a hyphen character.

I was able to deduce this as a possible root cause because the value of -hub is completely being ignored and the default hub port of 4444 is being attempted to use. The stacktrace that you shared re-iterates this

13:42:13.435 WARN - error getting the parameters from the hub. The node may
  end up with wrong timeouts.Connect to 10.146.48.80:4444 [/10.146.48.80]
  failed: Connection refused

As you can see, even though you are providing your Hub's registration URL to include a port number of 5786, its still picking up 4444 and complaining Connection refused.

Please try typing out the entire command for starting the hub and try again. That should work.


问:
How to overlap two divs with transparency
I have two div's that I want to overlap. Div A contains a Google Map and div B is a loading indicator I want to show when some changes are made and the map reloads.

What I want to accomplish is this:

What I currently get is this (div B not showing at all):

Here's the code I'm using:

```<code><div class="col-md-8 col-sm-8 full-height no-padding">
    <div class="full-height" style="position: relative">
        <div id="B" class="full-height" style="background-color: blue; opacity: 0.5; position: absolute; top: 0px; left: 0px; z-index: 99;"></div>
        <div id="A" class="full-height"></div>
    </div>
</div>
</code>```

I've tried a few other things such as this and this but they don't seem to be working, maybe because I'm using Bootstrap and height: 100%;. What am I doing wrong?

答: Please try to give width: 100% to the div with id="B"

Body:
I have two div's that I want to overlap. Div A contains a Google Map and div B is a loading indicator I want to show when some changes are made and the map reloads.

What I want to accomplish is this:

What I currently get is this (div B not showing at all):

Here's the code I'm using:

I've tried a few other things such as this and this but they don't seem to be working, maybe because I'm using Bootstrap and height: 100%;. What am I doing wrong?


问:
Statistical regression on multi-dimensional data
I have a set of data in (x, y, z) format where z is the output of some formula involving x and y. I want to find out what the formula is, and my Internet research suggests that statistical regression is the way to do this.

However, all of the examples I have found while researching only deal with two-dimensional data sets (x, y) which is not useful for my situation. Said examples also don't seem to provide a way to see what the resulting formula is, they just provide a function for predicting future outputs based on data not in a training data set.

The level of precision needed is that the formula for z needs to produce results within +/- 0.5 of actual values.

Can anyone tell me how I can do what I want to do? Please note I was not asking for specific recommendations on a software library to use.

答:
If the formula is a linear function, checkout this tutorial. It uses Ordinary least squares to fit your data which is quite powerful.

Assume that you have data points (x1, y1, z1), (x2, y2, z2), ..., (xn, yn, zn), transform them into three separated numpy arrays X, Y and Z.

```<code>import numpy as np
X = np.array([x1, x2, ..., xn])
Y = np.array([y1, y2, ..., yn])
Z = np.array([z1, z2, ..., zn])
</code>```

Then, use ols to fit them!

```<code>import pandas
from statsmodels.formula.api import ols

# Your data.
# Z = a*X + b*Y + c
data = pandas.DataFrame({'x': X, 'y': Y, 'z': Z})

# Fit your data with ols model.
model = ols("Z ~ X + Y", data).fit()

# Get your model summary.
print(model.summary())

# Get your model parameters.
print(model._results.params)
# should be approximately array([c, a, b])
</code>```

If more variables are presented

Add as much variables in the DataFrame as you like.

```<code># Your data.
data = pandas.DataFrame({'v1': V1, 'v2': V2, 'v3': V3, 'v4': V4, 'z': Z})
</code>```

Reference

Python package StatsModel

Body:
If the formula is a linear function, checkout this tutorial. It uses Ordinary least squares to fit your data which is quite powerful.

Assume that you have data points (x1, y1, z1), (x2, y2, z2), ..., (xn, yn, zn), transform them into three separated numpy arrays X, Y and Z.

import numpy as np
X = np.array([x1, x2, ..., xn])
Y = np.array([y1, y2, ..., yn])
Z = np.array([z1, z2, ..., zn])

Then, use ols to fit them!

import pandas
from statsmodels.formula.api import ols

# Your data.
# Z = a*X + b*Y + c
data = pandas.DataFrame({'x': X, 'y': Y, 'z': Z})

# Fit your data with ols model.
model = ols("Z ~ X + Y", data).fit()

# Get your model summary.
print(model.summary())

# Get your model parameters.
print(model._results.params)
# should be approximately array([c, a, b])

If more variables are presented

Add as much variables in the DataFrame as you like.

# Your data.
data = pandas.DataFrame({'v1': V1, 'v2': V2, 'v3': V3, 'v4': V4, 'z': Z})

Reference

Python package StatsModel


问:
Taking out bypass_ujvc hint in 12c converting update to merge statements
Hi I've been tasked with getting rid of the bypass_ujvc hint from a number of update statements as it's no longer supported in Oracle 12c, I have decided to replace the update statements with a merge statement, unluckily one of these update statements has a returning clause and a bulk collect, so i'm unsure how to approach this as a merge statement does not use a returning clause. Any advice is much appreciated. The query is below.</p>

```<code>  UPDATE    /*+ bypass_ujvc */ (SELECT caco.surr_id,
                                       caco.lead_item_yn,
                                       caco.case_reference,
                                       caco.logically_deleted_y
                                FROM TABLE (CAST(l_cc_surr_id AS db_surr_id_type_tab)) cc
                                JOIN case_contexts caco ON (caco.cc_surr_id = cc.COLUMN_VALUE)
                                JOIN cases cas ON (cas.REFERENCE = caco.case_reference )
                                WHERE caco.logically_deleted_y IS NULL
                                AND cas.status IN ('INP', 'TOS'))
  SET logically_deleted_y = 'Y'
  RETURNING         surr_id, lead_item_yn, case_reference
  BULK COLLECT INTO l_caco_surr_id, l_lead_item, l_all_cases;
</code>```

答:
An approach using bulk collect and forall would look something like this:

```<code>begin
    select caco.surr_id, caco.lead_item_yn, caco.case_reference
    bulk collect into l_caco_surr_id, l_lead_item, l_all_cases
    from   table(l_cc_surr_id) cc
           join case_contexts caco on caco.cc_surr_id = cc.column_value
           join cases cas on cas.reference = caco.case_reference
    where  caco.logically_deleted_y is null
    and    cas.status in ('INP', 'TOS');

    forall i in 1..l_caco_surr_id.count
        update case_contexts
        set    logically_deleted_y = 'Y'
        where  surr_id = l_caco_surr_id(i);
end;
</code>```

You might want to put that in a loop with a limit clause, but this should give the general idea.

Body:
Hi I've been tasked with getting rid of the bypass_ujvc hint from a number of update statements as it's no longer supported in Oracle 12c, I have decided to replace the update statements with a merge statement, unluckily one of these update statements has a returning clause and a bulk collect, so i'm unsure how to approach this as a merge statement does not use a returning clause. Any advice is much appreciated. The query is below.

  UPDATE    /*+ bypass_ujvc */ (SELECT caco.surr_id,
                                       caco.lead_item_yn,
                                       caco.case_reference,
                                       caco.logically_deleted_y
                                FROM TABLE (CAST(l_cc_surr_id AS db_surr_id_type_tab)) cc
                                JOIN case_contexts caco ON (caco.cc_surr_id = cc.COLUMN_VALUE)
                                JOIN cases cas ON (cas.REFERENCE = caco.case_reference )
                                WHERE caco.logically_deleted_y IS NULL
                                AND cas.status IN ('INP', 'TOS'))
  SET logically_deleted_y = 'Y'
  RETURNING         surr_id, lead_item_yn, case_reference
  BULK COLLECT INTO l_caco_surr_id, l_lead_item, l_all_cases;

Body:
An approach using bulk collect and forall would look something like this:

begin
    select caco.surr_id, caco.lead_item_yn, caco.case_reference
    bulk collect into l_caco_surr_id, l_lead_item, l_all_cases
    from   table(l_cc_surr_id) cc
           join case_contexts caco on caco.cc_surr_id = cc.column_value
           join cases cas on cas.reference = caco.case_reference
    where  caco.logically_deleted_y is null
    and    cas.status in ('INP', 'TOS');

    forall i in 1..l_caco_surr_id.count
        update case_contexts
        set    logically_deleted_y = 'Y'
        where  surr_id = l_caco_surr_id(i);
end;

You might want to put that in a loop with a limit clause, but this should give the general idea.


问:
c++ function matching and constness
I have a question regarding function matching. consider this code:

main.hpp:

```<code>struct Foo
{
  Foo(double = 1.0)
  {
    std::cout << "Foo constructor\n";
  }
  operator double()
  {
    std::cout << "Foo double\n";
    return double(1.0);
  }
  operator int()
  {
    std::cout << "Foo int\n";
    return int(1);
  }
};

void Bar(Foo &f)
{
  std::cout << "Bar Foo\n";
}

void Bar(int)
{
  std::cout << "Bar int\n";
}
</code>```

main.cpp:

```<code>double d;

Bar(Foo(d));
</code>```

output:

```<code>Foo constructor
Foo int
Bar int
</code>```

however if i change void Bar(Foo &f) to void Bar(const Foo &f), output changes to

```<code>Foo constructor
Bar Foo
</code>```

I'm not sure why const causes to call Bar(Foo) instead of Bar(int) even though Foo(d) is not const.

答: Foo(d) is a rvalue/temporary, it can't bind to a Foo& but it can bind to a const Foo& which is why it can call void Bar(const Foo &f), const Foo& is a better match here than conversion to int and then Bar(int) because that requires an extra user-defined conversion. When using Foo& the compiler isn't allowed to call Bar(Foo&) but it sees that it can make a conversion to int and then call Bar(int), so it does.

Title: c++ function matching and constness

Body:
I have a question regarding function matching. consider this code:

main.hpp:

struct Foo
{
  Foo(double = 1.0)
  {
    std::cout << "Foo constructor\n";
  }
  operator double()
  {
    std::cout << "Foo double\n";
    return double(1.0);
  }
  operator int()
  {
    std::cout << "Foo int\n";
    return int(1);
  }
};

void Bar(Foo &f)
{
  std::cout << "Bar Foo\n";
}

void Bar(int)
{
  std::cout << "Bar int\n";
}

main.cpp:

double d;

Bar(Foo(d));

output:

Foo constructor
Foo int
Bar int

however if i change void Bar(Foo &f) to void Bar(const Foo &f), output changes to

Foo constructor
Bar Foo

I'm not sure why const causes to call Bar(Foo) instead of Bar(int) even though Foo(d) is not const.


问:
Cannot upload file to my Ubuntu server through php script
My problem is setting permission to var/www which seems impossible to me.so this is a problem related to ubuntu because i found many other people facing the same problem in ubuntu.

Here is my script

```<code><?php
ini_set("display_errors","on");
if(isset($_POST['submit'])){
    echo "submitted<br>";
    $file_name     = $_POST['fname'];
    $uploader_name = $_POST['uname'];

    if(!empty($_POST['description'])){
        $description   =  $_POST['description'];
    }
    else{
        $description="";
    }

    if(isset($_FILES['upload'])){
        echo 'success';
        move_uploaded_file($_FILES['upload']['tmp_name'], "security/{$_FILES['upload']['name']}");
    }
    else
    {
        echo 'file not uploaded';
    }
}

 ?>

<!DOCTYPE html>
<html>
<head>
    <title>upload</title>
</head>
<body>
<form action='upload.php' method='post'>
    <strong style="color:red;display: inline-block;width: 180px">Name of File:*</strong>
    <input type="text" name="fname" size="50"  maxlength="100" required=""><br><br>

    <strong style="color:red;display: inline-block;width: 180px">Name of Uploader:*</strong>
    <input type="text" name="uname" size='50' maxlength="100" required=""><br><br>

    <strong style="color:red;display: inline-block;width: 180px ">Description(optional)</strong><br><br>
    <textarea rows="20" cols="100"></textarea><br><br>

    <input type="file" name="upload"  required=""><br><br>
    <input type="submit" name="submit"  value="Upload">

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

I tried everything I found on Ask Ubuntu, Stack Overflow and Ubuntu Forums ie chmod and chown.

PS:this question was moved from askubuntu.Please help

答:
You forgot to add enctype = "multipart/form-data" to your form

Try it as

```<code><form action='upload.php' method='post' enctype="multipart/form-data">
</code>```

Body:
My problem is setting permission to var/www which seems impossible to me.so this is a problem related to ubuntu because i found many other people facing the same problem in ubuntu.

Here is my script

<?php
ini_set("display_errors","on");
if(isset($_POST['submit'])){
    echo "submitted
";
    $file_name     = $_POST['fname'];
    $uploader_name = $_POST['uname'];

    if(!empty($_POST['description'])){
        $description   =  $_POST['description'];
    }
    else{
        $description="";
    }

    if(isset($_FILES['upload'])){
        echo 'success';
        move_uploaded_file($_FILES['upload']['tmp_name'], "security/{$_FILES['upload']['name']}");
    }
    else
    {
        echo 'file not uploaded';
    }
}

 ?>

<!DOCTYPE html>

    <title>upload</title>

<form action='upload.php' method='post'>
    Name of File:*
    <input type="text" name="fname" size="50"  maxlength="100" required="">

    Name of Uploader:*
    <input type="text" name="uname" size='50' maxlength="100" required="">

    Description(optional)

    <textarea rows="20" cols="100"></textarea>

    <input type="file" name="upload"  required="">

    <input type="submit" name="submit"  value="Upload">

</form>

I tried everything I found on Ask Ubuntu, Stack Overflow and Ubuntu Forums ie chmod and chown.

PS:this question was moved from askubuntu.Please help

Body:
You forgot to add enctype = "multipart/form-data" to your form

Try it as

<form action='upload.php' method='post' enctype="multipart/form-data">


问:
Open local html file in new window
I have a local html file on my desktop, when i click on it, if I already have chrome open with several tabs open, it will open my local file in the chrome browser in a new tab.

I want it to open in a separate chrome browser window, so its the only webpage open in that window, no other existing tabs should be open.

I also want to resize the window and ive tried something like this in the header of the html file

```<code><script type="text/javascript">
var myWindow;
function resizeWinTo() {
    myWindow.resizeTo(600, 600);
    myWindow.focus();
}
window.onload = resizeWinTo;
</script>
</code>```

but it does not work.

How can i do this, open in a new browser window and then resize that window?

EDIT: Just to clarify, I'm clicking in a html file icon on my desktop, not on a link to an html file within some webpage.

EDIT 2: So ive tried doing what some answer has said below, as a test I have created a simple 'hello world' html page called 'myfile.html' which is saved to my desktop, the code for the file is

```<code><!DOCTYPE html>
<html lang="en">
<head>

<script type="text/javascript">
OpenInNewWindow();
var WindowReference;
function OpenInNewWindow()
{
WindowReference = window.open("http://www.google.com",
"DescriptiveWindowName", "resizable=yes,scrollbars=yes,status=yes");
}
</script>

</head>

<body>
    <H1> HELLO WORLD! </H1>
</body>

</html>
</code>```

But if I already have my broswer open (my be minimized) with say some pages open, say bbc.com and cnn.com, so I already have two tabs open. When I double click on 'myfile.html' on my desktop, it just opens a third tab in my existing browser.

But I want a completely new separate browser window to open, how can this be done?

答:
Here is what you can do.

Press win + R to open Run, enter regedit and press enter

```<code>Go to HKEY_CLASSES_ROOT\ChromeHTML\shell\open\command
</code>```

You should see one key, named (Default). Double click this to get an editing pop-up.
Change the key value

From

```<code>"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"
</code>```

To

```<code>"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --new-window "%1"
</code>```

Now whenever you open any saved html page you should be able to see in a new window.

Source

Title: Open local html file in new window

Body:
I have a local html file on my desktop, when i click on it, if I already have chrome open with several tabs open, it will open my local file in the chrome browser in a new tab.

I want it to open in a separate chrome browser window, so its the only webpage open in that window, no other existing tabs should be open.

I also want to resize the window and ive tried something like this in the header of the html file

but it does not work.

How can i do this, open in a new browser window and then resize that window?

EDIT: Just to clarify, I'm clicking in a html file icon on my desktop, not on a link to an html file within some webpage.

EDIT 2: So ive tried doing what some answer has said below, as a test I have created a simple 'hello world' html page called 'myfile.html' which is saved to my desktop, the code for the file is

<!DOCTYPE html>

 HELLO WORLD!

But if I already have my broswer open (my be minimized) with say some pages open, say bbc.com and cnn.com, so I already have two tabs open. When I double click on 'myfile.html' on my desktop, it just opens a third tab in my existing browser.

But I want a completely new separate browser window to open, how can this be done?

Body:
Here is what you can do.

Press win + R to open Run, enter regedit and press enter

Go to HKEY_CLASSES_ROOT\ChromeHTML\shell\open\command

You should see one key, named (Default). Double click this to get an editing pop-up.
Change the key value

From

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -- "%1"

To

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --new-window "%1"

Now whenever you open any saved html page you should be able to see in a new window.

Source


问:
How to get the endorsement from multiple peers by using command line to invoke the transaction
How to get the endorsement from multiple peers by using command line to invoke the transaction? Now the example e2e_cli only shows us get the endorsement from one peer.
The command like, CORE_PEER_ADDRESS=peer0:7051 peer chaincode invoke -C myc -n mycc -v v0 -c '{"Args":["invoke","a","b","10"]}'

Thanks.

答:
This is not implemented.
If you want CLI-like usage with a binary you can easily transfer across machines consider using the go-SDK</p>


问:
Can you query subversion to find all checkins by a specific author out of hours
I would like to run a query on subversion to find all the checkins performed by a specific user outside of the normal working hours (9am to 5pm) is there a way to do this?</p>

答:
I have taken ChrisK's advice, and created an XML file using the following syntax...

```<code>svn log <url> --xml <path>
</code>```

And then used the following query in LinqPad C# Statements to identify all checkins out of hours....

```<code>var xml = XElement.Load (@"c:\\work\\log.xml");

var query =
  from logEntry in xml.Elements()
  from myDate in logEntry.Elements()
  //from author in logEntry.Elements() //These lines get a specific author
  //where author.Value == "digiguru"
  //where author.Name == "author"
  where myDate.Name == "date"
  where !(DateTime.Parse(myDate.Value).Hour >= 9 && DateTime.Parse(myDate.Value).Hour <= 17)
  select logEntry;

query.Dump();
</code>```

Body:
I have taken ChrisK's advice, and created an XML file using the following syntax...

svn log <url> --xml <path>

And then used the following query in LinqPad C# Statements to identify all checkins out of hours....

var xml = XElement.Load (@"c:\\work\\log.xml");

var query =
  from logEntry in xml.Elements()
  from myDate in logEntry.Elements()
  //from author in logEntry.Elements() //These lines get a specific author
  //where author.Value == "digiguru"
  //where author.Name == "author"
  where myDate.Name == "date"
  where !(DateTime.Parse(myDate.Value).Hour >= 9 && DateTime.Parse(myDate.Value).Hour <= 17)
  select logEntry;

query.Dump();


答:
To upload a file you have to give enctype='multipart/form-data to form. change your form to

```<code><form action='upload.php' method='post' enctype='multipart/form-data>
</code>```

Title: Cannot upload file to my Ubuntu server through php script

Body:
To upload a file you have to give enctype='multipart/form-data to form. change your form to

<form action='upload.php' method='post' enctype='multipart/form-data>


问:
Error in render function: “TypeError: Cannot read property of undefined”, using Vuex and Vue Router
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

```<code>export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}
</code>```

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

```<code>getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}
</code>```

Here is Card.vue:

```<code><template>
  <div>
    <br>
    <div v-if="flipped" class="container">
      <div class="box">
        <pre v-if="card.code"><code class="preserve-ws">{{card.back}}</code>```

{{card.back}}

{{card.front}}

</template>

```

<p>I am getting the TypeError referenced in the title. My understanding is that the <code>created()</code> hook happens after <code>data()</code> has been set up, so then I can assign <code>{card}</code> using the getter. Unfortunately this displays nothing...</p>

<p>If I assign <code>card()</code> as a computed property:</p>

```computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}
```

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

答:
What you need is a derived state based on store state which is to return a filtered card based on a card id. This id is received to your component via the route params. So its better you use a computed property instead of passing  arguments to the store getters

Instead of initializing card in data property make card a computed property like this:

```<code>computed:{
    card(){
        return this.$store.state.allCards.find((card) => card._id === this.$route.params.id);
    }
}
</code>```

Note this

If a component needs derived store state based on its own state(in your case rourte params), it should define a local computed property

Body:
I have been dealing with an issue using Vue, Vuex and Vue-Router. I'm building a flash cards app, fetching all the cards on main app creation, then using a Vuex getter to get each card by its id which is passed as a route parameter.

Relevant bits:

App.vue

export default {
  components: {
    'app-header': header,
  },
  data() {
    return {
    }
  },
  created() {
    this.$store.dispatch('getAllCards');
  }
}

The dispatch('getAllCards') is just pulling all the cards from the DB and committing to Vuex store.js.

Now I set up a getter:

getters: {
  cardById: (state) => (id) => {
    return state.allCards.find((card) => card._id === id);
  }
}

Here is Card.vue:

<template>

{{card.back}}

{{card.back}}

{{card.front}}

</template>

I am getting the TypeError referenced in the title. My understanding is that the created() hook happens after data() has been set up, so then I can assign {card} using the getter. Unfortunately this displays nothing...

If I assign card() as a computed property:

computed: {
  card() {
    return this.$store.getters.cardById(this.$route.params.id);
  }
}

The card shows, but I still get that error in console. Any idea why? I looked at this and attempted that solution, but to no avail.

Body:
What you need is a derived state based on store state which is to return a filtered card based on a card id. This id is received to your component via the route params. So its better you use a computed property instead of passing  arguments to the store getters

Instead of initializing card in data property make card a computed property like this:

computed:{
    card(){
        return this.$store.state.allCards.find((card) => card._id === this.$route.params.id);
    }
}

Note this

If a component needs derived store state based on its own state(in your case rourte params), it should define a local computed property


问:
Get events added by my app in android calendar
In my app, I am adding some event in the google calendar on a screen. When the user comes to the screen again, it adds the events again so in calendar the duplicate event is also visible.
So before adding any new event, I want to check if the event already exists. If I get all the events of the calendar and iterate over it, my app becomes very slow or hangs with a notification

```<code>too many calendar deletes
</code>```

The code that I am using to insert the values is :

```<code>final ContentValues event = new ContentValues();

    event.put(CalendarContract.Events.CALENDAR_ID, calendarId);

    event.put(CalendarContract.Events.TITLE, name);
    event.put(CalendarContract.Events.DTSTART, millisstarttime);
    event.put(CalendarContract.Events.DTEND, millisendtime);
    event.put(CalendarContract.Events.EVENT_LOCATION, venue);
    event.put(CalendarContract.Events.ALL_DAY, 0);   // 0 for false, 1 for true
    event.put(CalendarContract.Events.HAS_ALARM, 1);
    event.put(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_PRIVATE);
    event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);// 0 for false, 1 for true

    String timeZone = TimeZone.getDefault().getID();
    event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);

    this.getContentResolver().insert(baseUri, event);
</code>```

And I am trying to get the values :

```<code>private void deleteeve(ContentResolver cr,int calendarId) {

    String[] projection = {CalendarContract.Events._ID,
            CalendarContract.Events.CUSTOM_APP_PACKAGE,CalendarContract.Events.CALENDAR_ID,CalendarContract.Events.ORGANIZER};
    // Get a Cursor over the Events Provider.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        return;
    }
    Cursor cursor = getContentResolver().query(
            CalendarContract.Events.CONTENT_URI, projection,"calendar_id=" + calendarId, null,
            null);
    assert cursor != null;
    cursor.moveToFirst();

    String idsToDelete = "";
    int nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Events.CUSTOM_APP_PACKAGE);
    int id=cursor.getColumnIndexOrThrow(CalendarContract.Events._ID);
    int org=cursor.getColumnIndexOrThrow(CalendarContract.Events.ORGANIZER);
    while (cursor.moveToNext()) {
        // Extract the name.
        String name = cursor.getString(nameIdx);
        String apppackage = getApplicationContext().getPackageName();
        String organizer=cursor.getString(org);
        String idevent = cursor.getString(id);
        for (int i = 0; i < cursor.getCount(); i++) {

            if (apppackage.equals(name)) {
                // MY CODE
            }

        }
    }

}
</code>```

I tried getting the events using package name, So is there anyway to get the events added by my app only, other than iterating over all events?

答:
I fixed it myself.
I was trying everything correct. It was hanging because it was trying to delete 200 events on the main thread.
Only thing I did was started the deletion and the saving of events in a sepatate Thread.

```<code>Thread mThread = new Thread(new Runnable(){
 @override
 public void run(){
    //MY stuff
 }

});
</code>```

THat's all.

Body:
In my app, I am adding some event in the google calendar on a screen. When the user comes to the screen again, it adds the events again so in calendar the duplicate event is also visible.
So before adding any new event, I want to check if the event already exists. If I get all the events of the calendar and iterate over it, my app becomes very slow or hangs with a notification

too many calendar deletes

The code that I am using to insert the values is :

final ContentValues event = new ContentValues();

    event.put(CalendarContract.Events.CALENDAR_ID, calendarId);

    event.put(CalendarContract.Events.TITLE, name);
    event.put(CalendarContract.Events.DTSTART, millisstarttime);
    event.put(CalendarContract.Events.DTEND, millisendtime);
    event.put(CalendarContract.Events.EVENT_LOCATION, venue);
    event.put(CalendarContract.Events.ALL_DAY, 0);   // 0 for false, 1 for true
    event.put(CalendarContract.Events.HAS_ALARM, 1);
    event.put(CalendarContract.Events.ACCESS_LEVEL, CalendarContract.Events.ACCESS_PRIVATE);
    event.put(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);// 0 for false, 1 for true

    String timeZone = TimeZone.getDefault().getID();
    event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);

    this.getContentResolver().insert(baseUri, event);

And I am trying to get the values :

private void deleteeve(ContentResolver cr,int calendarId) {

    String[] projection = {CalendarContract.Events._ID,
            CalendarContract.Events.CUSTOM_APP_PACKAGE,CalendarContract.Events.CALENDAR_ID,CalendarContract.Events.ORGANIZER};
    // Get a Cursor over the Events Provider.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        return;
    }
    Cursor cursor = getContentResolver().query(
            CalendarContract.Events.CONTENT_URI, projection,"calendar_id=" + calendarId, null,
            null);
    assert cursor != null;
    cursor.moveToFirst();

    String idsToDelete = "";
    int nameIdx = cursor.getColumnIndexOrThrow(CalendarContract.Events.CUSTOM_APP_PACKAGE);
    int id=cursor.getColumnIndexOrThrow(CalendarContract.Events._ID);
    int org=cursor.getColumnIndexOrThrow(CalendarContract.Events.ORGANIZER);
    while (cursor.moveToNext()) {
        // Extract the name.
        String name = cursor.getString(nameIdx);
        String apppackage = getApplicationContext().getPackageName();
        String organizer=cursor.getString(org);
        String idevent = cursor.getString(id);
        for (int i = 0; i < cursor.getCount(); i++) {

            if (apppackage.equals(name)) {
                // MY CODE
            }

        }
    }

}

I tried getting the events using package name, So is there anyway to get the events added by my app only, other than iterating over all events?

Body:
I fixed it myself.
I was trying everything correct. It was hanging because it was trying to delete 200 events on the main thread.
Only thing I did was started the deletion and the saving of events in a sepatate Thread.

Thread mThread = new Thread(new Runnable(){
 @override
 public void run(){
    //MY stuff
 }

});

THat's all.


问:
wirte on external sd card does not work
My app doesn't seem to have writing permissions on my external sd card. I can read from it, but writing does only work on the internal one (sdcard0).
When i try

```<code>File f = new File("/storacge/sdcard1/Test/file.mp3");
boolean b = f.delete();
</code>```

then b is false and the file still exists. But i can play it with MediaPlayer.

I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my Manifest

What am i doing wrong?

答:
If you're working on Android 6.0 or higher you will have to request for permissions exactly where you need them.

Create a method in your activity as such:

```<code>public void askForWritePermissions(){
    //If android marshmellow or higher
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
        //If permissions are not granted
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED ){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);

        }
    }
}
</code>```

And call the above method on whichever event you need. After the user grants access or doesn't grant access to the permissions, onRequestPermissionsResult() is called so make sure you handle that method appropriately.

Title: wirte on external sd card does not work

Body:
My app doesn't seem to have writing permissions on my external sd card. I can read from it, but writing does only work on the internal one (sdcard0).
When i try

File f = new File("/storacge/sdcard1/Test/file.mp3");
boolean b = f.delete();

then b is false and the file still exists. But i can play it with MediaPlayer.

I have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my Manifest

What am i doing wrong?

Body:
If you're working on Android 6.0 or higher you will have to request for permissions exactly where you need them.

Create a method in your activity as such:

public void askForWritePermissions(){
    //If android marshmellow or higher
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
        //If permissions are not granted
        if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED ){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},2);

        }
    }
}

And call the above method on whichever event you need. After the user grants access or doesn't grant access to the permissions, onRequestPermissionsResult() is called so make sure you handle that method appropriately.


问:
RegEx for the

 tags
i am working on the C# WinForm application. In that application, i have snippet like this:

```<code><ul>
<li>abc
<li>bbc
<li>xyz
<li>pqr </li></li></li></li>
</ul>
</code>```

but, i want to get output like..

```<code><ul>
<li>abc</li>
<li>bbc</li>
<li>xyz</li>
<li>pqr</li>
</ul>
</code>```

Is there any method using which this thing can be done?

Can anybody suggest me any RegEx for this problem?

Thanks. Regards.

答:
```<code>StringBuilder output = new StringBuilder("<ul>\n");
foreach (i in Regex.Matches(snippet, "<li>\\w*"))
{
    output.Append(i.Value).Append("</li>\n");
}
output.Append("\n</ul>");
</code>```

Title:
RegEx for the

 tags

Body:
i am working on the C# WinForm application. In that application, i have snippet like this:

abc

bbc

xyz

pqr

but, i want to get output like..

abc

bbc

xyz

pqr

Is there any method using which this thing can be done?

Can anybody suggest me any RegEx for this problem?

Thanks. Regards.


问:
Strange error message in Node.js
I've been getting a lot of strange error message lately, and now I can't even get app.js started. What could the following mean, and does anyone know how to solve it?</p>

```<code>node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Cannot read property 'port' of null
    at Object.<anonymous> (/Users/henrikpetersson81/node/last/test4/app.js:15:64)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)
</code>```

答:
the port that your localhost is listening to, is being used by some other application/service. try changing the port at the following location to a different port number like 8888 or 3000 and you should be good to go. </p>

<p>/Users/henrikpetersson81/node/last/test4/app.js</p>

Title: Strange error message in Node.js

Body:
I've been getting a lot of strange error message lately, and now I can't even get app.js started. What could the following mean, and does anyone know how to solve it?

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
TypeError: Cannot read property 'port' of null
    at Object.<anonymous> (/Users/henrikpetersson81/node/last/test4/app.js:15:64)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:40)

Body:
the port that your localhost is listening to, is being used by some other application/service. try changing the port at the following location to a different port number like 8888 or 3000 and you should be good to go.

/Users/henrikpetersson81/node/last/test4/app.js


问:
PHP/MySQL: Getting Multiple Columns With the Same Name in Join Query Without Aliases?
I have two tables. One for users and one for posts.
The users table has the following fields:

```<code>id, username, password, created_at, modified_at
</code>```

The posts table has the following fields:

```<code>id, user_id, title, body, created_at, modified_at
</code>```

When I use a query like:

```<code>SELECT * FROM `users` LEFT OUTER JOIN `posts` ON users.id=posts.user_id
</code>```

And fetch the results using PDO:

```<code>$sth = $this->$default_connection->prepare($query);
$sth->execute();
$sth->fetchAll(PDO::FETCH_ASSOC);
</code>```

The returned array overwrites all the columns with the same names like id, created_at, modified_at like this:

```<code> Array
(
    [0] => Array
        (
            [id] => 1
            [username] => johnSmith
            [password] => 2348r7edf8s79aa0230
            [created_at] => 0000-00-00 00:00:00
            [modified_at] => 0000-00-00 00:00:00
            [user_id] => 18
            [title] => First Post
            [body] => Just testing...
        )
)
</code>```

The id field for the user is not shown, instead overwritten by the id of the post. Same goes for the created_at & modified_at fields.

I believe I can solve this problem by either using aliases or something like this:

```<code>    SELECT
       users.id,
       users.username,
       users.password,
       users.created_at,
       users.modified_at,
       posts.id AS postId,
       posts.user_id,
       posts.title,
       posts.created_at AS postCreatedAt,
       posts.modified_at AS postModifiedAt
   FROM `users`
       LEFT OUTER JOIN `posts` ON (users.id=postId)
</code>```

Or something similar, but I was wondering if there was a way to do this without manually writing out the name of every single column or an alias for every time I want to distinguish between two columns of the same name?
Is it possible to do something like:

```<code>SELECT users.* AS User and posts.* AS Post from `users` LEFT OUTER JOIN ON (User.id=Post.user_id)
</code>```

And have it automatically use aliases for every column?
Or is there any other faster/more convenient way to do this?
Or can I do this without having to define any aliases myself?

Thank you

答:
U can add the same qualified name after ambiguous fields (use tildas or commas)</p>

```<code>SELECT
   users.id `users.id`,
...
   posts.id `posts.id`,
...
FROM `users`
   LEFT OUTER JOIN `posts` ON (users.id=posts.id)
</code>```

Body:
I have two tables. One for users and one for posts.
The users table has the following fields:

id, username, password, created_at, modified_at

The posts table has the following fields:

id, user_id, title, body, created_at, modified_at

When I use a query like:

SELECT * FROM `users` LEFT OUTER JOIN `posts` ON users.id=posts.user_id

And fetch the results using PDO:

$sth = $this->$default_connection->prepare($query);
$sth->execute();
$sth->fetchAll(PDO::FETCH_ASSOC);

The returned array overwrites all the columns with the same names like id, created_at, modified_at like this:

 Array
(
    [0] => Array
        (
            [id] => 1
            [username] => johnSmith
            [password] => 2348r7edf8s79aa0230
            [created_at] => 0000-00-00 00:00:00
            [modified_at] => 0000-00-00 00:00:00
            [user_id] => 18
            [title] => First Post
            [body] => Just testing...
        )
)

The id field for the user is not shown, instead overwritten by the id of the post. Same goes for the created_at & modified_at fields.

I believe I can solve this problem by either using aliases or something like this:

    SELECT
       users.id,
       users.username,
       users.password,
       users.created_at,
       users.modified_at,
       posts.id AS postId,
       posts.user_id,
       posts.title,
       posts.created_at AS postCreatedAt,
       posts.modified_at AS postModifiedAt
   FROM `users`
       LEFT OUTER JOIN `posts` ON (users.id=postId)

Or something similar, but I was wondering if there was a way to do this without manually writing out the name of every single column or an alias for every time I want to distinguish between two columns of the same name?
Is it possible to do something like:

SELECT users.* AS User and posts.* AS Post from `users` LEFT OUTER JOIN ON (User.id=Post.user_id)

And have it automatically use aliases for every column?
Or is there any other faster/more convenient way to do this?
Or can I do this without having to define any aliases myself?

Thank you

Body:
U can add the same qualified name after ambiguous fields (use tildas or commas)

SELECT
   users.id `users.id`,
...
   posts.id `posts.id`,
...
FROM `users`
   LEFT OUTER JOIN `posts` ON (users.id=posts.id)


问:
cordova bluetooth plugin yuflow
In my ionic project I have installed cordova-plugin-bluetooth-yuflow using command:

cordova plugin add cordova-plugin-bluetooth-yuflow

as mentioned in the plugin repo.

But I coudn't execute function that allows me to enable bluetooth from my smartphone. I have a 5.1 android version. I want to use this plugin to connect to multiple serial bluetooth HC05

I don't understand what it is means:

You can reach the plugin in your scripts at "window.bluetoothyuflow"

mentioned in the plugin repo

答: You may be better of using a well documented and often used plugin, I recommend to use this Cordova plugin: https://github.com/don/BluetoothSerial (also take a look at the examples folder of this repo)</p>

Title: cordova bluetooth plugin yuflow


问:
Get cell height in javafx TableView
I can"t find a way to programmatically get the size of a cell, kwowing the row and column indexes in a javafx.scene.control.TableView.

How can I find TableCell or TableColumn by  row and column  index?

I search a lot, but nothing found.

Thanks
Paolo

答:
I didn't find a clear way to do it, but for testing purposes, next should work:

traverse Table's scenegraph

note rows and columns on your way

once you get to cell, you'll have row and column number

determine if it's the cell you wanted and calculate its height

Traverse method:

```<code>// run it next way: traverse(table, -1, -1);

public void traverse(Node node, int row, int column) {
    //System.out.println(node.getClass()); // uncomment to see how traverse works

    // once we found a TableRow all children are from that row, so we save it's number
    int newRow = (node instanceof TableRow) ? ((TableRow) node).getIndex() : row;
    // same for the column, although there would be only one child
    int newColumn = (node instanceof TableCell) ? ((TableCell)node).getIndex() : column;
    // in my demo table cells are text, change to your implementation class for custom cells
    if (node.getClass().getName().contains("LabeledText")) {
        String text = ((com.sun.javafx.scene.control.skin.LabeledText) node).getText();
        if (!text.isEmpty()) { // this check is just to filter empty rows
            System.out.println("### " + text);
            System.out.println("# Row: " + row + " Column: " + column);
            System.out.println("# Height: " + node.getBoundsInParent().getHeight());
        }
    }
    // traverse code
    if (node instanceof Parent) {
        Parent parent = (Parent) node;
        parent.getChildrenUnmodifiable().forEach(n -> traverse(n, newRow, newColumn));
    }
}
</code>```

Full sample: https://pastebin.com/A7cTvq4i

Title: Get cell height in javafx TableView

Body:
I didn't find a clear way to do it, but for testing purposes, next should work:

traverse Table's scenegraph

note rows and columns on your way

once you get to cell, you'll have row and column number

determine if it's the cell you wanted and calculate its height

Traverse method:

// run it next way: traverse(table, -1, -1);

public void traverse(Node node, int row, int column) {
    //System.out.println(node.getClass()); // uncomment to see how traverse works

    // once we found a TableRow all children are from that row, so we save it's number
    int newRow = (node instanceof TableRow) ? ((TableRow) node).getIndex() : row;
    // same for the column, although there would be only one child
    int newColumn = (node instanceof TableCell) ? ((TableCell)node).getIndex() : column;
    // in my demo table cells are text, change to your implementation class for custom cells
    if (node.getClass().getName().contains("LabeledText")) {
        String text = ((com.sun.javafx.scene.control.skin.LabeledText) node).getText();
        if (!text.isEmpty()) { // this check is just to filter empty rows
            System.out.println("### " + text);
            System.out.println("# Row: " + row + " Column: " + column);
            System.out.println("# Height: " + node.getBoundsInParent().getHeight());
        }
    }
    // traverse code
    if (node instanceof Parent) {
        Parent parent = (Parent) node;
        parent.getChildrenUnmodifiable().forEach(n -> traverse(n, newRow, newColumn));
    }
}

Full sample: https://pastebin.com/A7cTvq4i