问:
Why bash script using if and grep works one every other call?
```<code>root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
</code>```

It should echo 12 on every line, but do so only on odd lines. Why?
How to fix?

答:
You are assuming that foo | echo $? will show the exit status of foo. This is not the case. Instead, it shows the exit status of the previous command or pipeline:

$ bash -c 'exit 42'
$ true | echo $?
42
```

<p>Your command therefore flip-flops like this one:</p>

<pre class="lang-none prettyprint-override"><code>$ [ $? = 1 ] && echo "Boop"
$ [ $? = 1 ] && echo "Boop"
Boop
$ [ $? = 1 ] && echo "Boop"
$ [ $? = 1 ] && echo "Boop"
Boop
</code>```

What you intended was to suppress grep output (here done with -q), and then add a second command (after a ;) that can write out the value:

```<code># Check for success when running a command and writing out
# the exit status and capturing it and comparing it to success
[ "`date | grep -q 20; echo $?`" -gt "0" ] && echo 12
</code>```

However, you can drop all the redundancies and just do:

```<code># Check for success when running a command
date | grep -q 20 && echo 12
</code>```

Body:
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12

It should echo 12 on every line, but do so only on odd lines. Why?
How to fix?

Body:
You are assuming that foo | echo $? will show the exit status of foo. This is not the case. Instead, it shows the exit status of the previous command or pipeline:

$ bash -c 'exit 42'
$ true | echo $?
42

Your command therefore flip-flops like this one:

$ [ $? = 1 ] && echo "Boop"
$ [ $? = 1 ] && echo "Boop"
Boop
$ [ $? = 1 ] && echo "Boop"
$ [ $? = 1 ] && echo "Boop"
Boop

What you intended was to suppress grep output (here done with -q), and then add a second command (after a ;) that can write out the value:

# Check for success when running a command and writing out
# the exit status and capturing it and comparing it to success
[ "`date | grep -q 20; echo $?`" -gt "0" ] && echo 12

However, you can drop all the redundancies and just do:

# Check for success when running a command
date | grep -q 20 && echo 12


来源: stackexchange

问:
Apache HttpClient not receiving all cookies?
I posted before but now I seem to actually see the problem, just having trouble fixing it.

I am trying to login to my schools grade website, maybe even make an app for it later, and when I use Chrome to inspect the cookies being created, I get all these,

```<code>Cookie:appName=chippewa_falls; tool=""; selection=""; districtID=1; endYear=2011; calendarID=0; permCalendarID=0; JSESSIONID=BE5AEF51EAA72975150FC2D0F77DDE13
</code>```

But when my program prints all the cookies it received, I only get this

[version: 0][name: JSESSIONID][value: BC1BAA33BEB23DC27B7883AC24934A1D][domain: campus.chipfalls.k12.wi.us][path: /campus][expiry: null]

here is my code,

```<code>public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("https://campus.chipfalls.k12.wi.us/campus/portal/chippewa_falls.jsp");
    httpget.addHeader("Referer", "http://cfsd.chipfalls.k12.wi.us//high/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        InputStream input = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String ln = "";
        while((ln = reader.readLine()) != null) {
            System.out.println("During Get - " + ln);
        }
    }
    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();

    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }
</code>```

Note that is just for the GET part of it,

Thanks for any help :)

Edit: I did forget to mention, it is using HTTPS, but to be honest, I don't know if that matters with apache client or not.

答:
Those cookies must be getting set AFTER you login, not before. Looking at the output with wget of the URL you have above you see this:

```<code>Resolving campus.chipfalls.k12.wi.us... 205.213.253.11
Connecting to campus.chipfalls.k12.wi.us|205.213.253.11|:443... connected.
WARNING: Certificate verification error for campus.chipfalls.k12.wi.us: self signed certificate in certificate chain
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Server: Apache-Coyote/1.1
  Set-Cookie: JSESSIONID=004549BDBCBDFB8289EBF859A4E743B2; Path=/campus; Secure
  Content-Type: text/html;charset=utf-8
  Content-Length: 6352
  Date: Tue, 17 May 2011 06:00:38 GMT
  Connection: keep-alive
Length: 6,352 (6.2K) [text/html]
</code>```

which is the exact same thing you see. Until you actually log in you will not see the other cookies.

ContentLicense: CC BY-SA 3.0

Body:
I posted before but now I seem to actually see the problem, just having trouble fixing it.

I am trying to login to my schools grade website, maybe even make an app for it later, and when I use Chrome to inspect the cookies being created, I get all these,

Cookie:appName=chippewa_falls; tool=""; selection=""; districtID=1; endYear=2011; calendarID=0; permCalendarID=0; JSESSIONID=BE5AEF51EAA72975150FC2D0F77DDE13

But when my program prints all the cookies it received, I only get this

[version: 0][name: JSESSIONID][value: BC1BAA33BEB23DC27B7883AC24934A1D][domain: campus.chipfalls.k12.wi.us][path: /campus][expiry: null]

here is my code,

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("https://campus.chipfalls.k12.wi.us/campus/portal/chippewa_falls.jsp");
    httpget.addHeader("Referer", "http://cfsd.chipfalls.k12.wi.us//high/");
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        InputStream input = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String ln = "";
        while((ln = reader.readLine()) != null) {
            System.out.println("During Get - " + ln);
        }
    }
    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();

    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

Note that is just for the GET part of it,

Thanks for any help :)

Edit: I did forget to mention, it is using HTTPS, but to be honest, I don't know if that matters with apache client or not.

Body:
Those cookies must be getting set AFTER you login, not before. Looking at the output with wget of the URL you have above you see this:

Resolving campus.chipfalls.k12.wi.us... 205.213.253.11
Connecting to campus.chipfalls.k12.wi.us|205.213.253.11|:443... connected.
WARNING: Certificate verification error for campus.chipfalls.k12.wi.us: self signed certificate in certificate chain
HTTP request sent, awaiting response...
  HTTP/1.1 200 OK
  Server: Apache-Coyote/1.1
  Set-Cookie: JSESSIONID=004549BDBCBDFB8289EBF859A4E743B2; Path=/campus; Secure
  Content-Type: text/html;charset=utf-8
  Content-Length: 6352
  Date: Tue, 17 May 2011 06:00:38 GMT
  Connection: keep-alive
Length: 6,352 (6.2K) [text/html]

which is the exact same thing you see. Until you actually log in you will not see the other cookies.


问:
Duplicate lines of code consecutively with Pycharm
I am currently creating a script which has approximately 100 lines of code. Within PyCharm, I am interested in duplicating each line of code consecutively throughout the script. An example demonstrating the desired output is shown below.

```<code># Current Code

print("Hello World")
print("I enjoy python")
print("Stack Overflow is amazing")

# Desired Output

print("Hello World")
print("Hello World")
print("Hello World")
print("I enjoy python")
print("I enjoy python")
print("I enjoy python")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
</code>```

As this is only a sample with 3 original lines of code, I simply created duplicates of the code by copying and pasting each line. In projects which contain over 100 lines of code, this would be impractical. How can I do this in PyCharm without copying and pasting line by line?

-Thanks

答:
Try this :

```<code># Using readlines()
file1 = open('input_file.py', 'r')
Lines = file1.readlines()

# open a (new) file to write
outF = open("myNewFile.py", "w")

for line in Lines:
   i = 0
   while i < 3:
       outF.write(line)
       outf.write("\n")

outF.close()
</code>```

This will create a new file with every line written 3 times. You could rename it later to whatever you want.

ContentLicense: CC BY-SA 4.0

Body:
I am currently creating a script which has approximately 100 lines of code. Within PyCharm, I am interested in duplicating each line of code consecutively throughout the script. An example demonstrating the desired output is shown below.

# Current Code

print("Hello World")
print("I enjoy python")
print("Stack Overflow is amazing")

# Desired Output

print("Hello World")
print("Hello World")
print("Hello World")
print("I enjoy python")
print("I enjoy python")
print("I enjoy python")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")
print("Stack Overflow is amazing")

As this is only a sample with 3 original lines of code, I simply created duplicates of the code by copying and pasting each line. In projects which contain over 100 lines of code, this would be impractical. How can I do this in PyCharm without copying and pasting line by line?

-Thanks

Body:
Try this :

# Using readlines()
file1 = open('input_file.py', 'r')
Lines = file1.readlines()

# open a (new) file to write
outF = open("myNewFile.py", "w")

for line in Lines:
   i = 0
   while i < 3:
       outF.write(line)
       outf.write("\n")

outF.close()

This will create a new file with every line written 3 times. You could rename it later to whatever you want.


问:
Problem with Gnuplot 4.4 and TikZ
I'm using Gnuplot 4.4, compiled with Lua support. It supposedly has the tikz terminal.

I've successfully compiled my gnuplots to tex using "set terminal tikz". However, when adding this source to my latex document I keep getting the following error:

! Package pgfkeys Error: I do not know the key '/tikz/gnuplot' and I am going t
  o ignore it. Perhaps you misspelled it.

I've included the tikz package in the original tex document. Any ideas?

EDIT: Solved. See answer bellow.

答: For later happless Fedora users: The package containing this here is gnuplot-latex, dnf doesn't recognize it as tex(gnuplot-lua-tikz.sty).

ContentLicense: CC BY-SA 2.5

Title: Problem with Gnuplot 4.4 and TikZ


问:
2d array as index of a 3d array
I had a 2D array (C) with 8000x64 elements, an 1D array (s) with 8000x1 elements and another 1D array (d) with 1x64 elements.
Every row of index i, where s[i] is True, shall be added by vector d.
This works quite well:

```<code>C[s == True] += d
</code>```

Now I have added one dimension to C, s, and d and the logic above shall be applied to every element of the additional dimension.

The following code does what I want, but it's very slow.

```<code>for i in range(I):
        C_this = C[:,:,i]
        s_this = s[:,i]
        d_this = d[:,i]

        C_this[s_this == True] += d_this
        C[:,:,i] = C_this
</code>```

Is there a numpy way to do this without a for loop?

Title: 2d array as index of a 3d array

Body:
I had a 2D array (C) with 8000x64 elements, an 1D array (s) with 8000x1 elements and another 1D array (d) with 1x64 elements.
Every row of index i, where s[i] is True, shall be added by vector d.
This works quite well:

C[s == True] += d

Now I have added one dimension to C, s, and d and the logic above shall be applied to every element of the additional dimension.

The following code does what I want, but it's very slow.

for i in range(I):
        C_this = C[:,:,i]
        s_this = s[:,i]
        d_this = d[:,i]

        C_this[s_this == True] += d_this
        C[:,:,i] = C_this

Is there a numpy way to do this without a for loop?

Body:
It's easier with the extra dimension at the beginning:

In [376]: C = np.zeros((4,2,3),int)
In [377]: s = np.array([[0,0],[0,1],[1,0],[1,1]],bool)
In [378]: d = np.arange(1,13).reshape(4,3)
In [379]: C.shape, s.shape, d.shape
Out[379]: ((4, 2, 3), (4, 2), (4, 3))
In [380]: I,J = np.nonzero(s)
In [381]: I,J
Out[381]: (array([1, 2, 3, 3]), array([1, 0, 0, 1]))

In [383]: C[I,J]=d[I]
In [384]: C
Out[384]:
array([[[ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 0,  0,  0],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [ 0,  0,  0]],

       [[10, 11, 12],
        [10, 11, 12]]])

Your way:

In [385]: C = np.zeros((4,2,3),int)
In [386]: for i in range(4):
     ...:     C[i,:,:][s[i,:]] += d[i,:]
     ...:
In [387]: C
Out[387]:
array([[[ 0,  0,  0],
        [ 0,  0,  0]],

       [[ 0,  0,  0],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [ 0,  0,  0]],

       [[10, 11, 12],
        [10, 11, 12]]])


问:
How do you determine the path of the file that a symlink points to?
In Linux, if you have a path to a file which you know is a symlink, how do you programmatically determine (in C or C++) the path to the file that it points to?</p>

答:
The readlink function. Do a man 2 readlink. This function is part of the Posix API, so it should work on almost any Unix.

If the path starts with a '/', then its an absolute symlink and you have the full absolute path of the file to which it refers (which may be another symbolic link, and you'll have to repeat the process again).

If the path does not start with '/', then it's a relative link and is interpreted relative to the directory the symlink is in. It's up to you to combine the path appropriately to figure out the real filename.

Of course, sometimes symlinks are used to store information that's not actually a path. Sometimes programs store a PID or other such information in them for locking purposes. The calls to create a symlink are one of the more reliably atomic operations that can be performed on an NFS mounted filesystem.

Also, on my Fedora system, if you do man 7 symlink you get a long discussion of symlinks, their behavior in various circumstances and a rundown of the functions that manipulate them or are affected by them.


问:
Image size independent shader
I'm trying to create a shader for an image material that draws a circle regardless of the aspect ratio of the image itself.

In Shadertoy (hlsl) I can do the following to create a round circle, regardless of aspect ratio:

```<code>void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord/iResolution.xy;
    uv -= 0.5;
    uv.x *= iResolution.x/iResolution.y; // < this compensates for the aspect ratio

    float l = length(uv);
    float s = smoothstep(0.5, 0.55, l);

    vec4 col = vec4(s);
    fragColor = vec4(col);
}
</code>```

Which gives the following output

If I remove the line uv.x *= iResolution.x/iResolution.y; the circle will warp based on the current aspect ratio.

Now I want to create the same effect in Unity, so I tried the (to me seemingly) same approach.
_MainTex_TexelSize contains the width/height of the texture (from the docs):

{TextureName}_TexelSize - a float4 property contains texture size information:

  - x contains 1.0/width

  - y contains 1.0/height

  - z contains width

  - w contains height

```<code>Shader "Unlit/Shader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100
        Blend SrcAlpha OneMinusSrcAlpha
        Cull off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.uv -= 0.5;
                o.uv.x *= _MainTex_TexelSize.z / _MainTex_TexelSize.w;
                return o;
            }

            float DrawCircle(float2 uv, float radius, float fallOff)
            {
                float d = length(uv);
                return smoothstep(radius, fallOff, d);
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                float c = DrawCircle(i.uv, 0.5, 0.55);
                col = lerp(col, fixed4(1,0,0,1), c);
                return col;
            }
            ENDCG
        }
    }
}

</code>```

The shader compiles as is, but the circle will still stretch based on the aspect ratio of the image.

I thought this may be due to the way the uv's are set up using o.uv = TRANSFORM_TEX(v.uv, _MainTex); so I tried dividing that by the image's size:

```<code>o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.uv / _MainTex_TexelSize.zw;
o.uv -= 0.5;
</code>```

However this did nothing

and setting up the uv's differently like so

```<code>o.uv = v.uv / _MainTex_TexelSize.zw;
o.uv / _MainTex_TexelSize.zw;
o.uv -= 0.5;
</code>```

results in the circle's center moving to the upper right, but still warp when the aspect ratio change.

What step am I missing/doing wrong to get the aspect ratio independent result like I get in shadertoy?

答:
The aspect ratio of the input texture _MainTex has nothing to do with the aspect ratio of the output*. In the shadertoy example that output is the screen, and iResolution gives you the screen dimensions (the equivalent in unity is _ScreenParams).

 If you want to draw a quad that is not full screen, you have to match the quad aspect ratio with the _MainTex aspect ratio to use _MainTex_TexelSize, or else just provide the aspect ratio or dimensions in a shader property (that is basically what _ScreenParams does):

```<code>float _Aspect;
fixed4 frag(v2f i) : SV_Target
{
    i.uv -= .5;
    i.uv.x *= _Aspect;

    fixed4 col = tex2D(_MainTex, i.uv);

    float c = DrawCircle(i.uv, .5, .55);
    col = lerp(col, fixed4(1,0,0,1), c);
    return col;
}
</code>```

You could calculate the aspect ratio with derivatives. Here dx and dy are the amount of uv change per pixel. This would also be useful if you want to have, for example, fallOff always be 10 pixels.

```<code>fixed4 frag(v2f i) : SV_Target
{
    i.uv -= .5;
    float dx = ddx(i.uv.x);
    float dy = ddy(i.uv.y);
    float aspect = dy/dx;
    i.uv.x *= aspect;

    fixed4 col = tex2D(_MainTex, i.uv);

    float c = DrawCircle(i.uv, .5, .55);
    col = lerp(col, fixed4(1,0,0,1), c);
    return col;
}
</code>```

Title: Image size independent shader

Body:
I'm trying to create a shader for an image material that draws a circle regardless of the aspect ratio of the image itself.

In Shadertoy (hlsl) I can do the following to create a round circle, regardless of aspect ratio:

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord/iResolution.xy;
    uv -= 0.5;
    uv.x *= iResolution.x/iResolution.y; // < this compensates for the aspect ratio

    float l = length(uv);
    float s = smoothstep(0.5, 0.55, l);

    vec4 col = vec4(s);
    fragColor = vec4(col);
}

Which gives the following output

If I remove the line uv.x *= iResolution.x/iResolution.y; the circle will warp based on the current aspect ratio.

Now I want to create the same effect in Unity, so I tried the (to me seemingly) same approach.
_MainTex_TexelSize contains the width/height of the texture (from the docs):

{TextureName}_TexelSize - a float4 property contains texture size information:

  - x contains 1.0/width

  - y contains 1.0/height

  - z contains width

  - w contains height

Shader "Unlit/Shader"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100
        Blend SrcAlpha OneMinusSrcAlpha
        Cull off

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            float4 _MainTex_TexelSize;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                o.uv -= 0.5;
                o.uv.x *= _MainTex_TexelSize.z / _MainTex_TexelSize.w;
                return o;
            }

            float DrawCircle(float2 uv, float radius, float fallOff)
            {
                float d = length(uv);
                return smoothstep(radius, fallOff, d);
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);

                float c = DrawCircle(i.uv, 0.5, 0.55);
                col = lerp(col, fixed4(1,0,0,1), c);
                return col;
            }
            ENDCG
        }
    }
}

The shader compiles as is, but the circle will still stretch based on the aspect ratio of the image.

I thought this may be due to the way the uv's are set up using o.uv = TRANSFORM_TEX(v.uv, _MainTex); so I tried dividing that by the image's size:

o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.uv / _MainTex_TexelSize.zw;
o.uv -= 0.5;

However this did nothing

and setting up the uv's differently like so

o.uv = v.uv / _MainTex_TexelSize.zw;
o.uv / _MainTex_TexelSize.zw;
o.uv -= 0.5;

results in the circle's center moving to the upper right, but still warp when the aspect ratio change.

What step am I missing/doing wrong to get the aspect ratio independent result like I get in shadertoy?

Body:
The aspect ratio of the input texture _MainTex has nothing to do with the aspect ratio of the output*. In the shadertoy example that output is the screen, and iResolution gives you the screen dimensions (the equivalent in unity is _ScreenParams).

 If you want to draw a quad that is not full screen, you have to match the quad aspect ratio with the _MainTex aspect ratio to use _MainTex_TexelSize, or else just provide the aspect ratio or dimensions in a shader property (that is basically what _ScreenParams does):

float _Aspect;
fixed4 frag(v2f i) : SV_Target
{
    i.uv -= .5;
    i.uv.x *= _Aspect;

    fixed4 col = tex2D(_MainTex, i.uv);

    float c = DrawCircle(i.uv, .5, .55);
    col = lerp(col, fixed4(1,0,0,1), c);
    return col;
}

You could calculate the aspect ratio with derivatives. Here dx and dy are the amount of uv change per pixel. This would also be useful if you want to have, for example, fallOff always be 10 pixels.

fixed4 frag(v2f i) : SV_Target
{
    i.uv -= .5;
    float dx = ddx(i.uv.x);
    float dy = ddy(i.uv.y);
    float aspect = dy/dx;
    i.uv.x *= aspect;

    fixed4 col = tex2D(_MainTex, i.uv);

    float c = DrawCircle(i.uv, .5, .55);
    col = lerp(col, fixed4(1,0,0,1), c);
    return col;
}


问:
codecs module cannot read in text file
I have a text file that I want to convert to base64 on a line by line basis.
Using pandas 1.0.1 and python 3.7
I have a text file consisting of words separated by carriage returns named sampleTEXT.txt
Pandas can read the file and it has data

```<code>
import pandas as pd
words = pd.read_table("sampleTEXT.txt",names=['word'],encoding="utf-8",header=None)
words.head()
---      word
---------------
---0    difference
---1    where
---2    mc
---3    is
---4    the
---
</code>```

The next jupyter cell has this code:

```<code>BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sampleTEXT.txt, "r", "utf-8") as sourceFile:
    with codecs.open(bsampleTEXT.b64, "w", "base64") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
</code>```

but I get this error:

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-118-8aec7c80fc16> in <module>
      1 import codecs
      2 BLOCKSIZE = 1048576 # or some other, desired size in bytes
----> 3 with codecs.open(sampleTEXT.txt, "r", "utf-8") as sourceFile:
      4     with codecs.open(bsampleTEXT.b64, "w", "base64") as targetFile:
      5         while True:

NameError: name 'sampleACAD' is not defined
</code>```

I know the file is there and that it's ok because pandas can import it as a dataframe. I know I'm using the correct syntax as described here

答:
I got this to work without error but it does not write anything:</p>

```<code>import io,codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with io.open("sampleACAD.txt",mode="rb") as sourceFile:
    with codecs.open("bsampleACAD.b64", mode="w", encoding="base64") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
</code>```

Title: codecs module cannot read in text file

Body:
I have a text file that I want to convert to base64 on a line by line basis.
Using pandas 1.0.1 and python 3.7
I have a text file consisting of words separated by carriage returns named sampleTEXT.txt
Pandas can read the file and it has data

import pandas as pd
words = pd.read_table("sampleTEXT.txt",names=['word'],encoding="utf-8",header=None)
words.head()
---      word
---------------
---0    difference
---1    where
---2    mc
---3    is
---4    the
---

The next jupyter cell has this code:

BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sampleTEXT.txt, "r", "utf-8") as sourceFile:
    with codecs.open(bsampleTEXT.b64, "w", "base64") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

but I get this error:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-118-8aec7c80fc16> in <module>
      1 import codecs
      2 BLOCKSIZE = 1048576 # or some other, desired size in bytes
----> 3 with codecs.open(sampleTEXT.txt, "r", "utf-8") as sourceFile:
      4     with codecs.open(bsampleTEXT.b64, "w", "base64") as targetFile:
      5         while True:

NameError: name 'sampleACAD' is not defined

I know the file is there and that it's ok because pandas can import it as a dataframe. I know I'm using the correct syntax as described here

Body:
I got this to work without error but it does not write anything:

import io,codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with io.open("sampleACAD.txt",mode="rb") as sourceFile:
    with codecs.open("bsampleACAD.b64", mode="w", encoding="base64") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)


问:
#VALUE! Error when trying to call a UDF function into another UDF function
Simply put, what I am attempting to do is a simple function that would calculate the sample variance of a selected range of cells in excel. The effect is to get a result exactly identical to the excel function =VAR.S()

I have coded in the user-defined function for mean (see below), but the error arises when trying to call my Mean1b function into my Var2a function. If I had simply defined mean as a constant in my variance formula, everything goes smoothly.

My question is, why am I not simply able to pass the input array through my Var2a function, such that it would be accepted by Mean1b function? What would also be the workaround this if I were to continue working in ParamArray?

```<code>Public Function Mean1b(ParamArray arr() As Variant)
   Dim rtot As Double
   Dim elem As Variant
   Dim i As Integer
   Dim count As Integer

   rtot = 0 'set initial state
   count = 0 'initiate count of elements in the array

    For i = LBound(arr) To UBound(arr) 'loop from lower bound to upper bound of array
        For Each elem In arr(i)
            rtot = rtot + elem.Value
            count = count + 1
        Next elem
    Next i
    Mean1b = rtot / count
End Function

Public Function Var2a(ParamArray arr() As Variant) As Double
    Dim rtot As Double
    Dim elem As Variant
    Dim i As Integer
    Dim count As Integer

    mean = Mean1b(arr)
    rtot = 0
    count = 0

    For i = LBound(arr) To UBound(arr)
        For Each elem In arr(i)
            rtot = rtot + (elem.Value - mean) ^ 2
            count = count + 1
        Next elem
    Next i
    Var2a = rtot / (count - 1)
End Function
</code>```

答:
Solved it! Turns out all you had to do was to modify this:

mean = Mean1b(arr)

to this:

mean = Mean1b(arr(0))

Apparently this is required when passing a ParamArray into another function

Body:
Simply put, what I am attempting to do is a simple function that would calculate the sample variance of a selected range of cells in excel. The effect is to get a result exactly identical to the excel function =VAR.S()

I have coded in the user-defined function for mean (see below), but the error arises when trying to call my Mean1b function into my Var2a function. If I had simply defined mean as a constant in my variance formula, everything goes smoothly.

My question is, why am I not simply able to pass the input array through my Var2a function, such that it would be accepted by Mean1b function? What would also be the workaround this if I were to continue working in ParamArray?

Public Function Mean1b(ParamArray arr() As Variant)
   Dim rtot As Double
   Dim elem As Variant
   Dim i As Integer
   Dim count As Integer

   rtot = 0 'set initial state
   count = 0 'initiate count of elements in the array

    For i = LBound(arr) To UBound(arr) 'loop from lower bound to upper bound of array
        For Each elem In arr(i)
            rtot = rtot + elem.Value
            count = count + 1
        Next elem
    Next i
    Mean1b = rtot / count
End Function

Public Function Var2a(ParamArray arr() As Variant) As Double
    Dim rtot As Double
    Dim elem As Variant
    Dim i As Integer
    Dim count As Integer

    mean = Mean1b(arr)
    rtot = 0
    count = 0

    For i = LBound(arr) To UBound(arr)
        For Each elem In arr(i)
            rtot = rtot + (elem.Value - mean) ^ 2
            count = count + 1
        Next elem
    Next i
    Var2a = rtot / (count - 1)
End Function


问:
Spring Boot with JPA - wrong column type encountered in column
I'm using Spring Boot Starter Data Jpa (2.1.9.RELEASE) and I'm trying to map this table:

CREATE TABLE `foo` (
  `id` int(11) NOT NULL,
  `woo` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
```

<p>The Entity is mapped as follows:</p>

<pre class="lang-java prettyprint-override"><code>@Entity
@Table(name = "foo")
public class Foo {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "woo")
    private Integer woo;

    public Integer getId() {
        return id;
    }

    public Integer getWoo() {
        return woo;
    }

}
</code>```

When I start the application I get the following error:

```<code>Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [woo] in table [foo]; found [tinyint (Types#TINYINT)], but expecting [integer (Types#INTEGER)]
</code>```

My properties are:

```<code>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=validate
</code>```

I tried to do the same mapping using vanilla Jpa and Hibernate (not managed by Spring) and it works fine.

Can anyone point me in the right direction?

Here's a link to the maven project, in case anyone want to try it directly.

答:
Your database is using a TinyInt, while your class is making it expect an integer. TinyInt maps to byte however, which is where the confusion is taking place.

```<code>@Column(name = "woo")
private Byte woo;
</code>```

A reference for mapping types can be found here.

Body:
I'm using Spring Boot Starter Data Jpa (2.1.9.RELEASE) and I'm trying to map this table:

CREATE TABLE `foo` (
  `id` int(11) NOT NULL,
  `woo` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The Entity is mapped as follows:

@Entity
@Table(name = "foo")
public class Foo {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "woo")
    private Integer woo;

    public Integer getId() {
        return id;
    }

    public Integer getWoo() {
        return woo;
    }

}

When I start the application I get the following error:

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [woo] in table [foo]; found [tinyint (Types#TINYINT)], but expecting [integer (Types#INTEGER)]

My properties are:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=validate

I tried to do the same mapping using vanilla Jpa and Hibernate (not managed by Spring) and it works fine.

Can anyone point me in the right direction?

Here's a link to the maven project, in case anyone want to try it directly.

Body:
Your database is using a TinyInt, while your class is making it expect an integer. TinyInt maps to byte however, which is where the confusion is taking place.

@Column(name = "woo")
private Byte woo;

A reference for mapping types can be found here.


问:
Horizontal lines with LineCollection in matplotlib?
How do I add, or create horizontal lines with LineCollection in matplotlib? I am trying to make an animation faster, and don't want to go over old ground, but basically I am trying to avoid using axhline in a for loop to construct an array of lines. Hence it was recommended that I try LineCollection. But so far I can only get to plot a series.

```<code>import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9]
y = [42,13,24,14,74,45,22,44,77]

lc = LineCollection(zip(x,y),color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,10)
a.set_ylim(0,100)
plt.show()
</code>```

And if I add the coordinates explicitly, for example:

```<code>x = [(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9)]
y = [(42,42),(13,13),(24,24),(14,14),(74,74),(45,45),(22,22),(44,44),(77,77)]
</code>```

I get the following plot?

How is that even possible?

答:
One options is this:</p>

```<code>import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

y = [42,13,24,14,74,45,22,44,77]
segs = np.zeros((len(y), 2, 2))
segs[:,:,1] = np.c_[y,y]
segs[:,1,0] = np.ones(len(y))

fig, ax = plt.subplots()
lc = LineCollection(segs,color='blue', transform=ax.get_yaxis_transform())
ax.add_collection(lc)
ax.set_xlim(0,10)
ax.set_ylim(0,100)
plt.show()
</code>```

Body:
How do I add, or create horizontal lines with LineCollection in matplotlib? I am trying to make an animation faster, and don't want to go over old ground, but basically I am trying to avoid using axhline in a for loop to construct an array of lines. Hence it was recommended that I try LineCollection. But so far I can only get to plot a series.

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

x = [1,2,3,4,5,6,7,8,9]
y = [42,13,24,14,74,45,22,44,77]

lc = LineCollection(zip(x,y),color='blue')
fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,10)
a.set_ylim(0,100)
plt.show()

And if I add the coordinates explicitly, for example:

x = [(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9),(0,9)]
y = [(42,42),(13,13),(24,24),(14,14),(74,74),(45,45),(22,22),(44,44),(77,77)]

I get the following plot?

How is that even possible?

Body:
One options is this:

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt

y = [42,13,24,14,74,45,22,44,77]
segs = np.zeros((len(y), 2, 2))
segs[:,:,1] = np.c_[y,y]
segs[:,1,0] = np.ones(len(y))

fig, ax = plt.subplots()
lc = LineCollection(segs,color='blue', transform=ax.get_yaxis_transform())
ax.add_collection(lc)
ax.set_xlim(0,10)
ax.set_ylim(0,100)
plt.show()


问:
Using itertools combination and permutation functions to count for repeated elements
I need to use itertools module to find the total number of permutations of an n element sequence of "O"s and "X"s. (n will be a known constant, but please give your answer for n=8). For example, if I was to enter 3, it should output:

```<code>OOO
OOX
OXO
XOO
OXX
XXO
XOX
XXX
</code>```

not necessarily in that order. I am currently using itertools and its combinations/permutations/combinations_with_replacement functions to do this, but it can't seem to figure out that if I give it an array with multiple elements that are the same, that they are the same. To find combinations, I am great, I can currently just do:

comb = combinations_with_replacement(["O", "X"], 8)
```

<p>which outputs</p>

```('O', 'O', 'O', 'O', 'O', 'O', 'O', 'O')
('O', 'O', 'O', 'O', 'O', 'O', 'O', 'X')
('O', 'O', 'O', 'O', 'O', 'O', 'X', 'X')
('O', 'O', 'O', 'O', 'O', 'X', 'X', 'X')
('O', 'O', 'O', 'O', 'X', 'X', 'X', 'X')
('O', 'O', 'O', 'X', 'X', 'X', 'X', 'X')
('O', 'O', 'X', 'X', 'X', 'X', 'X', 'X')
('O', 'X', 'X', 'X', 'X', 'X', 'X', 'X')
('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X')
```

However, when I use the permutations function, it differentiates between equal elements, making there be 8 factorial times 9 = 40320 times 9 output tuples, when there should only be 2^8=256 outputs. Can someone please help?

Thanks!

EDIT: I also need to actually generate the permutations. NOT JUST FIND THE TOTAL NUMBER OF THEM.

Body:
I need to use itertools module to find the total number of permutations of an n element sequence of "O"s and "X"s. (n will be a known constant, but please give your answer for n=8). For example, if I was to enter 3, it should output:

OOO
OOX
OXO
XOO
OXX
XXO
XOX
XXX

not necessarily in that order. I am currently using itertools and its combinations/permutations/combinations_with_replacement functions to do this, but it can't seem to figure out that if I give it an array with multiple elements that are the same, that they are the same. To find combinations, I am great, I can currently just do:

comb = combinations_with_replacement(["O", "X"], 8)

which outputs

('O', 'O', 'O', 'O', 'O', 'O', 'O', 'O')
('O', 'O', 'O', 'O', 'O', 'O', 'O', 'X')
('O', 'O', 'O', 'O', 'O', 'O', 'X', 'X')
('O', 'O', 'O', 'O', 'O', 'X', 'X', 'X')
('O', 'O', 'O', 'O', 'X', 'X', 'X', 'X')
('O', 'O', 'O', 'X', 'X', 'X', 'X', 'X')
('O', 'O', 'X', 'X', 'X', 'X', 'X', 'X')
('O', 'X', 'X', 'X', 'X', 'X', 'X', 'X')
('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X')

However, when I use the permutations function, it differentiates between equal elements, making there be 8 factorial times 9 = 40320 times 9 output tuples, when there should only be 2^8=256 outputs. Can someone please help?

Thanks!

EDIT: I also need to actually generate the permutations. NOT JUST FIND THE TOTAL NUMBER OF THEM.

Body:
You can use itertools.product with the repeat parameter to get the output you want:

for xos in itertools.product('OX', repeat=3):
    print(xos)

Gives:

('O', 'O', 'O')
('O', 'O', 'X')
('O', 'X', 'O')
('O', 'X', 'X')
('X', 'O', 'O')
('X', 'O', 'X')
('X', 'X', 'O')
('X', 'X', 'X')

For repeat=8, you'll get 256 results:

('O', 'O', 'O', 'O', 'O', 'O', 'O', 'O')
('O', 'O', 'O', 'O', 'O', 'O', 'O', 'X')
('O', 'O', 'O', 'O', 'O', 'O', 'X', 'O')
('O', 'O', 'O', 'O', 'O', 'O', 'X', 'X')
('O', 'O', 'O', 'O', 'O', 'X', 'O', 'O')
('O', 'O', 'O', 'O', 'O', 'X', 'O', 'X')
('O', 'O', 'O', 'O', 'O', 'X', 'X', 'O')
('O', 'O', 'O', 'O', 'O', 'X', 'X', 'X')
('O', 'O', 'O', 'O', 'X', 'O', 'O', 'O')
('O', 'O', 'O', 'O', 'X', 'O', 'O', 'X')
('O', 'O', 'O', 'O', 'X', 'O', 'X', 'O')
('O', 'O', 'O', 'O', 'X', 'O', 'X', 'X')
('O', 'O', 'O', 'O', 'X', 'X', 'O', 'O')
('O', 'O', 'O', 'O', 'X', 'X', 'O', 'X')
('O', 'O', 'O', 'O', 'X', 'X', 'X', 'O')
('O', 'O', 'O', 'O', 'X', 'X', 'X', 'X')
('O', 'O', 'O', 'X', 'O', 'O', 'O', 'O')
('O', 'O', 'O', 'X', 'O', 'O', 'O', 'X')
('O', 'O', 'O', 'X', 'O', 'O', 'X', 'O')
('O', 'O', 'O', 'X', 'O', 'O', 'X', 'X')
('O', 'O', 'O', 'X', 'O', 'X', 'O', 'O')
('O', 'O', 'O', 'X', 'O', 'X', 'O', 'X')
('O', 'O', 'O', 'X', 'O', 'X', 'X', 'O')
('O', 'O', 'O', 'X', 'O', 'X', 'X', 'X')
('O', 'O', 'O', 'X', 'X', 'O', 'O', 'O')
('O', 'O', 'O', 'X', 'X', 'O', 'O', 'X')
('O', 'O', 'O', 'X', 'X', 'O', 'X', 'O')
('O', 'O', 'O', 'X', 'X', 'O', 'X', 'X')
('O', 'O', 'O', 'X', 'X', 'X', 'O', 'O')
('O', 'O', 'O', 'X', 'X', 'X', 'O', 'X')
('O', 'O', 'O', 'X', 'X', 'X', 'X', 'O')
('O', 'O', 'O', 'X', 'X', 'X', 'X', 'X')
('O', 'O', 'X', 'O', 'O', 'O', 'O', 'O')
('O', 'O', 'X', 'O', 'O', 'O', 'O', 'X')
('O', 'O', 'X', 'O', 'O', 'O', 'X', 'O')
('O', 'O', 'X', 'O', 'O', 'O', 'X', 'X')
('O', 'O', 'X', 'O', 'O', 'X', 'O', 'O')
('O', 'O', 'X', 'O', 'O', 'X', 'O', 'X')
('O', 'O', 'X', 'O', 'O', 'X', 'X', 'O')
('O', 'O', 'X', 'O', 'O', 'X', 'X', 'X')
('O', 'O', 'X', 'O', 'X', 'O', 'O', 'O')
('O', 'O', 'X', 'O', 'X', 'O', 'O', 'X')
('O', 'O', 'X', 'O', 'X', 'O', 'X', 'O')
('O', 'O', 'X', 'O', 'X', 'O', 'X', 'X')
('O', 'O', 'X', 'O', 'X', 'X', 'O', 'O')
('O', 'O', 'X', 'O', 'X', 'X', 'O', 'X')
('O', 'O', 'X', 'O', 'X', 'X', 'X', 'O')
('O', 'O', 'X', 'O', 'X', 'X', 'X', 'X')
('O', 'O', 'X', 'X', 'O', 'O', 'O', 'O')
('O', 'O', 'X', 'X', 'O', 'O', 'O', 'X')
('O', 'O', 'X', 'X', 'O', 'O', 'X', 'O')
('O', 'O', 'X', 'X', 'O', 'O', 'X', 'X')
('O', 'O', 'X', 'X', 'O', 'X', 'O', 'O')
('O', 'O', 'X', 'X', 'O', 'X', 'O', 'X')
('O', 'O', 'X', 'X', 'O', 'X', 'X', 'O')
('O', 'O', 'X', 'X', 'O', 'X', 'X', 'X')
('O', 'O', 'X', 'X', 'X', 'O', 'O', 'O')
('O', 'O', 'X', 'X', 'X', 'O', 'O', 'X')
('O', 'O', 'X', 'X', 'X', 'O', 'X', 'O')
('O', 'O', 'X', 'X', 'X', 'O', 'X', 'X')
('O', 'O', 'X', 'X', 'X', 'X', 'O', 'O')
('O', 'O', 'X', 'X', 'X', 'X', 'O', 'X')
('O', 'O', 'X', 'X', 'X', 'X', 'X', 'O')
('O', 'O', 'X', 'X', 'X', 'X', 'X', 'X')
('O', 'X', 'O', 'O', 'O', 'O', 'O', 'O')
('O', 'X', 'O', 'O', 'O', 'O', 'O', 'X')
('O', 'X', 'O', 'O', 'O', 'O', 'X', 'O')
('O', 'X', 'O', 'O', 'O', 'O', 'X', 'X')
('O', 'X', 'O', 'O', 'O', 'X', 'O', 'O')
('O', 'X', 'O', 'O', 'O', 'X', 'O', 'X')
('O', 'X', 'O', 'O', 'O', 'X', 'X', 'O')
('O', 'X', 'O', 'O', 'O', 'X', 'X', 'X')
('O', 'X', 'O', 'O', 'X', 'O', 'O', 'O')
('O', 'X', 'O', 'O', 'X', 'O', 'O', 'X')
('O', 'X', 'O', 'O', 'X', 'O', 'X', 'O')
('O', 'X', 'O', 'O', 'X', 'O', 'X', 'X')
('O', 'X', 'O', 'O', 'X', 'X', 'O', 'O')
('O', 'X', 'O', 'O', 'X', 'X', 'O', 'X')
('O', 'X', 'O', 'O', 'X', 'X', 'X', 'O')
('O', 'X', 'O', 'O', 'X', 'X', 'X', 'X')
('O', 'X', 'O', 'X', 'O', 'O', 'O', 'O')
('O', 'X', 'O', 'X', 'O', 'O', 'O', 'X')
('O', 'X', 'O', 'X', 'O', 'O', 'X', 'O')
('O', 'X', 'O', 'X', 'O', 'O', 'X', 'X')
('O', 'X', 'O', 'X', 'O', 'X', 'O', 'O')
('O', 'X', 'O', 'X', 'O', 'X', 'O', 'X')
('O', 'X', 'O', 'X', 'O', 'X', 'X', 'O')
('O', 'X', 'O', 'X', 'O', 'X', 'X', 'X')
('O', 'X', 'O', 'X', 'X', 'O', 'O', 'O')
('O', 'X', 'O', 'X', 'X', 'O', 'O', 'X')
('O', 'X', 'O', 'X', 'X', 'O', 'X', 'O')
('O', 'X', 'O', 'X', 'X', 'O', 'X', 'X')
('O', 'X', 'O', 'X', 'X', 'X', 'O', 'O')
('O', 'X', 'O', 'X', 'X', 'X', 'O', 'X')
('O', 'X', 'O', 'X', 'X', 'X', 'X', 'O')
('O', 'X', 'O', 'X', 'X', 'X', 'X', 'X')
('O', 'X', 'X', 'O', 'O', 'O', 'O', 'O')
('O', 'X', 'X', 'O', 'O', 'O', 'O', 'X')
('O', 'X', 'X', 'O', 'O', 'O', 'X', 'O')
('O', 'X', 'X', 'O', 'O', 'O', 'X', 'X')
('O', 'X', 'X', 'O', 'O', 'X', 'O', 'O')
('O', 'X', 'X', 'O', 'O', 'X', 'O', 'X')
('O', 'X', 'X', 'O', 'O', 'X', 'X', 'O')
('O', 'X', 'X', 'O', 'O', 'X', 'X', 'X')
('O', 'X', 'X', 'O', 'X', 'O', 'O', 'O')
('O', 'X', 'X', 'O', 'X', 'O', 'O', 'X')
('O', 'X', 'X', 'O', 'X', 'O', 'X', 'O')
('O', 'X', 'X', 'O', 'X', 'O', 'X', 'X')
('O', 'X', 'X', 'O', 'X', 'X', 'O', 'O')
('O', 'X', 'X', 'O', 'X', 'X', 'O', 'X')
('O', 'X', 'X', 'O', 'X', 'X', 'X', 'O')
('O', 'X', 'X', 'O', 'X', 'X', 'X', 'X')
('O', 'X', 'X', 'X', 'O', 'O', 'O', 'O')
('O', 'X', 'X', 'X', 'O', 'O', 'O', 'X')
('O', 'X', 'X', 'X', 'O', 'O', 'X', 'O')
('O', 'X', 'X', 'X', 'O', 'O', 'X', 'X')
('O', 'X', 'X', 'X', 'O', 'X', 'O', 'O')
('O', 'X', 'X', 'X', 'O', 'X', 'O', 'X')
('O', 'X', 'X', 'X', 'O', 'X', 'X', 'O')
('O', 'X', 'X', 'X', 'O', 'X', 'X', 'X')
('O', 'X', 'X', 'X', 'X', 'O', 'O', 'O')
('O', 'X', 'X', 'X', 'X', 'O', 'O', 'X')
('O', 'X', 'X', 'X', 'X', 'O', 'X', 'O')
('O', 'X', 'X', 'X', 'X', 'O', 'X', 'X')
('O', 'X', 'X', 'X', 'X', 'X', 'O', 'O')
('O', 'X', 'X', 'X', 'X', 'X', 'O', 'X')
('O', 'X', 'X', 'X', 'X', 'X', 'X', 'O')
('O', 'X', 'X', 'X', 'X', 'X', 'X', 'X')
('X', 'O', 'O', 'O', 'O', 'O', 'O', 'O')
('X', 'O', 'O', 'O', 'O', 'O', 'O', 'X')
('X', 'O', 'O', 'O', 'O', 'O', 'X', 'O')
('X', 'O', 'O', 'O', 'O', 'O', 'X', 'X')
('X', 'O', 'O', 'O', 'O', 'X', 'O', 'O')
('X', 'O', 'O', 'O', 'O', 'X', 'O', 'X')
('X', 'O', 'O', 'O', 'O', 'X', 'X', 'O')
('X', 'O', 'O', 'O', 'O', 'X', 'X', 'X')
('X', 'O', 'O', 'O', 'X', 'O', 'O', 'O')
('X', 'O', 'O', 'O', 'X', 'O', 'O', 'X')
('X', 'O', 'O', 'O', 'X', 'O', 'X', 'O')
('X', 'O', 'O', 'O', 'X', 'O', 'X', 'X')
('X', 'O', 'O', 'O', 'X', 'X', 'O', 'O')
('X', 'O', 'O', 'O', 'X', 'X', 'O', 'X')
('X', 'O', 'O', 'O', 'X', 'X', 'X', 'O')
('X', 'O', 'O', 'O', 'X', 'X', 'X', 'X')
('X', 'O', 'O', 'X', 'O', 'O', 'O', 'O')
('X', 'O', 'O', 'X', 'O', 'O', 'O', 'X')
('X', 'O', 'O', 'X', 'O', 'O', 'X', 'O')
('X', 'O', 'O', 'X', 'O', 'O', 'X', 'X')
('X', 'O', 'O', 'X', 'O', 'X', 'O', 'O')
('X', 'O', 'O', 'X', 'O', 'X', 'O', 'X')
('X', 'O', 'O', 'X', 'O', 'X', 'X', 'O')
('X', 'O', 'O', 'X', 'O', 'X', 'X', 'X')
('X', 'O', 'O', 'X', 'X', 'O', 'O', 'O')
('X', 'O', 'O', 'X', 'X', 'O', 'O', 'X')
('X', 'O', 'O', 'X', 'X', 'O', 'X', 'O')
('X', 'O', 'O', 'X', 'X', 'O', 'X', 'X')
('X', 'O', 'O', 'X', 'X', 'X', 'O', 'O')
('X', 'O', 'O', 'X', 'X', 'X', 'O', 'X')
('X', 'O', 'O', 'X', 'X', 'X', 'X', 'O')
('X', 'O', 'O', 'X', 'X', 'X', 'X', 'X')
('X', 'O', 'X', 'O', 'O', 'O', 'O', 'O')
('X', 'O', 'X', 'O', 'O', 'O', 'O', 'X')
('X', 'O', 'X', 'O', 'O', 'O', 'X', 'O')
('X', 'O', 'X', 'O', 'O', 'O', 'X', 'X')
('X', 'O', 'X', 'O', 'O', 'X', 'O', 'O')
('X', 'O', 'X', 'O', 'O', 'X', 'O', 'X')
('X', 'O', 'X', 'O', 'O', 'X', 'X', 'O')
('X', 'O', 'X', 'O', 'O', 'X', 'X', 'X')
('X', 'O', 'X', 'O', 'X', 'O', 'O', 'O')
('X', 'O', 'X', 'O', 'X', 'O', 'O', 'X')
('X', 'O', 'X', 'O', 'X', 'O', 'X', 'O')
('X', 'O', 'X', 'O', 'X', 'O', 'X', 'X')
('X', 'O', 'X', 'O', 'X', 'X', 'O', 'O')
('X', 'O', 'X', 'O', 'X', 'X', 'O', 'X')
('X', 'O', 'X', 'O', 'X', 'X', 'X', 'O')
('X', 'O', 'X', 'O', 'X', 'X', 'X', 'X')
('X', 'O', 'X', 'X', 'O', 'O', 'O', 'O')
('X', 'O', 'X', 'X', 'O', 'O', 'O', 'X')
('X', 'O', 'X', 'X', 'O', 'O', 'X', 'O')
('X', 'O', 'X', 'X', 'O', 'O', 'X', 'X')
('X', 'O', 'X', 'X', 'O', 'X', 'O', 'O')
('X', 'O', 'X', 'X', 'O', 'X', 'O', 'X')
('X', 'O', 'X', 'X', 'O', 'X', 'X', 'O')
('X', 'O', 'X', 'X', 'O', 'X', 'X', 'X')
('X', 'O', 'X', 'X', 'X', 'O', 'O', 'O')
('X', 'O', 'X', 'X', 'X', 'O', 'O', 'X')
('X', 'O', 'X', 'X', 'X', 'O', 'X', 'O')
('X', 'O', 'X', 'X', 'X', 'O', 'X', 'X')
('X', 'O', 'X', 'X', 'X', 'X', 'O', 'O')
('X', 'O', 'X', 'X', 'X', 'X', 'O', 'X')
('X', 'O', 'X', 'X', 'X', 'X', 'X', 'O')
('X', 'O', 'X', 'X', 'X', 'X', 'X', 'X')
('X', 'X', 'O', 'O', 'O', 'O', 'O', 'O')
('X', 'X', 'O', 'O', 'O', 'O', 'O', 'X')
('X', 'X', 'O', 'O', 'O', 'O', 'X', 'O')
('X', 'X', 'O', 'O', 'O', 'O', 'X', 'X')
('X', 'X', 'O', 'O', 'O', 'X', 'O', 'O')
('X', 'X', 'O', 'O', 'O', 'X', 'O', 'X')
('X', 'X', 'O', 'O', 'O', 'X', 'X', 'O')
('X', 'X', 'O', 'O', 'O', 'X', 'X', 'X')
('X', 'X', 'O', 'O', 'X', 'O', 'O', 'O')
('X', 'X', 'O', 'O', 'X', 'O', 'O', 'X')
('X', 'X', 'O', 'O', 'X', 'O', 'X', 'O')
('X', 'X', 'O', 'O', 'X', 'O', 'X', 'X')
('X', 'X', 'O', 'O', 'X', 'X', 'O', 'O')
('X', 'X', 'O', 'O', 'X', 'X', 'O', 'X')
('X', 'X', 'O', 'O', 'X', 'X', 'X', 'O')
('X', 'X', 'O', 'O', 'X', 'X', 'X', 'X')
('X', 'X', 'O', 'X', 'O', 'O', 'O', 'O')
('X', 'X', 'O', 'X', 'O', 'O', 'O', 'X')
('X', 'X', 'O', 'X', 'O', 'O', 'X', 'O')
('X', 'X', 'O', 'X', 'O', 'O', 'X', 'X')
('X', 'X', 'O', 'X', 'O', 'X', 'O', 'O')
('X', 'X', 'O', 'X', 'O', 'X', 'O', 'X')
('X', 'X', 'O', 'X', 'O', 'X', 'X', 'O')
('X', 'X', 'O', 'X', 'O', 'X', 'X', 'X')
('X', 'X', 'O', 'X', 'X', 'O', 'O', 'O')
('X', 'X', 'O', 'X', 'X', 'O', 'O', 'X')
('X', 'X', 'O', 'X', 'X', 'O', 'X', 'O')
('X', 'X', 'O', 'X', 'X', 'O', 'X', 'X')
('X', 'X', 'O', 'X', 'X', 'X', 'O', 'O')
('X', 'X', 'O', 'X', 'X', 'X', 'O', 'X')
('X', 'X', 'O', 'X', 'X', 'X', 'X', 'O')
('X', 'X', 'O', 'X', 'X', 'X', 'X', 'X')
('X', 'X', 'X', 'O', 'O', 'O', 'O', 'O')
('X', 'X', 'X', 'O', 'O', 'O', 'O', 'X')
('X', 'X', 'X', 'O', 'O', 'O', 'X', 'O')
('X', 'X', 'X', 'O', 'O', 'O', 'X', 'X')
('X', 'X', 'X', 'O', 'O', 'X', 'O', 'O')
('X', 'X', 'X', 'O', 'O', 'X', 'O', 'X')
('X', 'X', 'X', 'O', 'O', 'X', 'X', 'O')
('X', 'X', 'X', 'O', 'O', 'X', 'X', 'X')
('X', 'X', 'X', 'O', 'X', 'O', 'O', 'O')
('X', 'X', 'X', 'O', 'X', 'O', 'O', 'X')
('X', 'X', 'X', 'O', 'X', 'O', 'X', 'O')
('X', 'X', 'X', 'O', 'X', 'O', 'X', 'X')
('X', 'X', 'X', 'O', 'X', 'X', 'O', 'O')
('X', 'X', 'X', 'O', 'X', 'X', 'O', 'X')
('X', 'X', 'X', 'O', 'X', 'X', 'X', 'O')
('X', 'X', 'X', 'O', 'X', 'X', 'X', 'X')
('X', 'X', 'X', 'X', 'O', 'O', 'O', 'O')
('X', 'X', 'X', 'X', 'O', 'O', 'O', 'X')
('X', 'X', 'X', 'X', 'O', 'O', 'X', 'O')
('X', 'X', 'X', 'X', 'O', 'O', 'X', 'X')
('X', 'X', 'X', 'X', 'O', 'X', 'O', 'O')
('X', 'X', 'X', 'X', 'O', 'X', 'O', 'X')
('X', 'X', 'X', 'X', 'O', 'X', 'X', 'O')
('X', 'X', 'X', 'X', 'O', 'X', 'X', 'X')
('X', 'X', 'X', 'X', 'X', 'O', 'O', 'O')
('X', 'X', 'X', 'X', 'X', 'O', 'O', 'X')
('X', 'X', 'X', 'X', 'X', 'O', 'X', 'O')
('X', 'X', 'X', 'X', 'X', 'O', 'X', 'X')
('X', 'X', 'X', 'X', 'X', 'X', 'O', 'O')
('X', 'X', 'X', 'X', 'X', 'X', 'O', 'X')
('X', 'X', 'X', 'X', 'X', 'X', 'X', 'O')
('X', 'X', 'X', 'X', 'X', 'X', 'X', 'X')


问:
Changing default encoding of Python?
I have many "can't encode" and "can't decode" problems with Python when I run my applications from the console. But in the Eclipse PyDev IDE, the default character encoding is set to UTF-8, and I'm fine.

I searched around for setting the default encoding, and people say that Python deletes the sys.setdefaultencoding function on startup, and we can not use it.

So what's the best solution for it?

答:
You could change the encoding of your entire operating system. On Ubuntu you can do this with</p>

```<code>sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales
</code>```

Title: Changing default encoding of Python?

Body:
You could change the encoding of your entire operating system. On Ubuntu you can do this with

sudo apt install locales
sudo locale-gen en_US en_US.UTF-8
sudo dpkg-reconfigure locales


答:
You should use itertools.product(...) instead:

from itertools import product

Res=list(product(["o", "x"], repeat=8))
```

Title: Using itertools combination and permutation functions to count for repeated elements


问:
AdaptiveTriggers not working in UNO platform web assembly?
I have been trying to make some changes to the UI in my code depending on the screen size. As I started to code in UWP everything worked as it should, but when changing to the web assembly no changes happened when changing the size of the window, it only takes the first visual state of MinWindowWidth="0".

Here some test code that I ran.
testing code

Am I missing something?

答:
Try to write it like this

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="SizeGroup">
        <VisualState x:Name="Large">
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="1000"/>
            </VisualState.StateTriggers>
            <VisualState.Setters>
                <Setter Target="MainContent.Background"
                        Value="Blue"/>
            </VisualState.Setters>
        </VisualState>
        <VisualState x:Name="Small">
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="0"/>
            </VisualState.StateTriggers>
            <VisualState.Setters>
                <Setter Target="MainContent.Background"
                        Value="Red"/>
            </VisualState.Setters>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>
```

The order declared in XAML is important, so you should declare the largest MinWindowWidth first and then the smaller ones. In your case the small one with Value 0 is evaluated first and always true.

You can track the bug here

Body:
Try to write it like this

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="SizeGroup">
        <VisualState x:Name="Large">
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="1000"/>
            </VisualState.StateTriggers>
            <VisualState.Setters>
                <Setter Target="MainContent.Background"
                        Value="Blue"/>
            </VisualState.Setters>
        </VisualState>
        <VisualState x:Name="Small">
            <VisualState.StateTriggers>
                <AdaptiveTrigger MinWindowWidth="0"/>
            </VisualState.StateTriggers>
            <VisualState.Setters>
                <Setter Target="MainContent.Background"
                        Value="Red"/>
            </VisualState.Setters>
        </VisualState>
    </VisualStateGroup>
</VisualStateManager.VisualStateGroups>

The order declared in XAML is important, so you should declare the largest MinWindowWidth first and then the smaller ones. In your case the small one with Value 0 is evaluated first and always true.

You can track the bug here


问:
Can't download deployed sources with OWNER account
I have an app deployed to google cloud platform. I downloaded google cloud cli and logged in with gcloud auth login.

Then I tried to download project with the

```<code>C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\appcfg.py -A hello-world download_app hello-world
</code>```

but it ended up with error

```<code>08:27 PM Host: appengine.google.com
08:27 PM Fetching file list...
Error 403: --- begin server output ---
You do not have permission to modify this app
</code>```

I also checked the permissions in the "Over granted permissions" sidebar , but I do not know what to look for..

I do not have the original source code of java app, I want to download compiled classes to decompile it. I tried it with other test account and there was no problem with download. Maybe because I deployed the app and then downloaded it?

答:
Okay, so I managed to do it.

First thing, if you want to download the deployed source code, and you have the OWNER account, and it is not working on you computer with gcloud utils, you can do it this way

Log into google cloud console through web browser

Open cloud shell

download the source code with this command inside the web browser shell appcfg.py -A your-project-name download_app folder-where-to-download

optionally tar the file/folder to compress it

COPY THE FILE TO YOUR BUCKET WITH THIS COMMAND gsutil cp filename.tar.gz  gs://your-projects-bucket-name/

Visit https://console.cloud.google.com/storage/browser/your-project-name.appspot.com?project=your-project-name

File should be there available to download

Body:
I have an app deployed to google cloud platform. I downloaded google cloud cli and logged in with gcloud auth login.

Then I tried to download project with the

C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\appcfg.py -A hello-world download_app hello-world

but it ended up with error

08:27 PM Host: appengine.google.com
08:27 PM Fetching file list...
Error 403: --- begin server output ---
You do not have permission to modify this app

I also checked the permissions in the "Over granted permissions" sidebar , but I do not know what to look for..

I do not have the original source code of java app, I want to download compiled classes to decompile it. I tried it with other test account and there was no problem with download. Maybe because I deployed the app and then downloaded it?


问:
How to remove the top bar from flutter date picker

So, basically I want to completely remove the top bar in bluish color which shows the current date and year and start the calendar interface from the white background but I can't figure out how to do it.

答:
Flutter is an open source project which allows you to modify their entire code.

You should take a look at the class _DatePickerDialog and _DatePickerHeader.

Copy the entire code from date_picker.dart and, at line 1020, remove header and that's it.

```<code>         return Container(
            color: theme.dialogBackgroundColor,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                header, // this one is the header
                Flexible(child: picker),
                actions,
              ],
            ),
          )
</code>```

Most likely you should change Flexible for Expanded over your Column.

Here is the official docs showDatePicker

Body:
Flutter is an open source project which allows you to modify their entire code.

You should take a look at the class _DatePickerDialog and _DatePickerHeader.

Copy the entire code from date_picker.dart and, at line 1020, remove header and that's it.

         return Container(
            color: theme.dialogBackgroundColor,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                header, // this one is the header
                Flexible(child: picker),
                actions,
              ],
            ),
          )

Most likely you should change Flexible for Expanded over your Column.

Here is the official docs showDatePicker


问:
Ending external programs with Python
I'm writing a program that needs to be able to kill certain processes. The two lines I'm currently using work; however, the second line os.system(task) launches command prompt for a split second whilst it's ending a process. Are there any equivalent lines which do not launch command prompt?

Snippet :

```<code>task = 'taskkill /im ' + taskname + ' /f'
os.system(task)
</code>```

This is in Windows 7 if you couldn't have guessed.

答:
Try using subprocess.check_call instead of os.system.  This won't launch the process in a console window.

```<code>import subprocess
taskname = '...'
task = 'taskkill /im ' + taskname + ' /f'
subprocess.check_call(task, shell=True)
</code>```

Title: Ending external programs with Python

Body:
I'm writing a program that needs to be able to kill certain processes. The two lines I'm currently using work; however, the second line os.system(task) launches command prompt for a split second whilst it's ending a process. Are there any equivalent lines which do not launch command prompt?

Snippet :

task = 'taskkill /im ' + taskname + ' /f'
os.system(task)

This is in Windows 7 if you couldn't have guessed.

Body:
Try using subprocess.check_call instead of os.system.  This won't launch the process in a console window.

import subprocess
taskname = '...'
task = 'taskkill /im ' + taskname + ' /f'
subprocess.check_call(task, shell=True)


问:
How to write re_path url in django for reading special character?
I am working with Django URL pattern for my project. I am sending a String containing special characters and numbers. While reading a string in python function it won't get the ? in a function.

html

```<code>{% for user_name in userSet%}
<a class="dropdown-item" href="/slackNotification/{{user_name}}/{{data.question}}">{{ user_name }}</a>
{% endfor %}
</code>```

url

```<code>path('slackNotification/<str:slack_user_name>/<str:question>',views.slackNotification)
</code>```

When I get the all details through URL then string whichever I received in the python code it won't contain ? mark even though my input contains Special characters and numbers.

input: What is your name?
output: What is your name(question mark not available;)

Question
I have tried this:

```<code>re_path(r'^slackNotification/<str:slack_user_name>/(?P<question>\w+)',views.slackNotification)
</code>```

Output
The current path didn't match any of the url

I want to know the exact regular expression for my requirement ??

答: Along with the above solution please refer Url decode UTF-8 in Python link for more information on urllib.parse.quote and urllib.parse.unquote </p>

Body:
I am working with Django URL pattern for my project. I am sending a String containing special characters and numbers. While reading a string in python function it won't get the ? in a function.

html

{% for user_name in userSet%}
{{ user_name }}
{% endfor %}

url

path('slackNotification/<str:slack_user_name>/<str:question>',views.slackNotification)

When I get the all details through URL then string whichever I received in the python code it won't contain ? mark even though my input contains Special characters and numbers.

input: What is your name?
output: What is your name(question mark not available;)

Question
I have tried this:

re_path(r'^slackNotification/<str:slack_user_name>/(?P<question>\w+)',views.slackNotification)

Output
The current path didn't match any of the url

I want to know the exact regular expression for my requirement ??


问:
How do I change font size for Tkinter Scrolling Text
I am using this code to make a scrolling text window using Tkinter with python 3.5, and I was curious what I could do to change the font size and color of the scrolling text.</p>

```<code> import tkinter as tk

 root = tk.Tk()
 deli = 100           # milliseconds of delay per character
 svar = tk.StringVar()
 labl = tk.Label(root, textvariable=svar, height=5)

 def shif():
     shif.msg = shif.msg[1:] + shif.msg[0]
     svar.set(shif.msg)
     root.after(deli, shif)

shif.msg = 'Text example: Blah, Blah Blah'
shif()
labl.pack()
root.mainloop()
</code>```

答:
```<code>def create_scrolltext(self):
        F_font = ('bold', 30)
        scroll_w = 30
        scroll_h = 10
        scrollText = scrolledtext.ScrolledText(self, width=scroll_w, height=scroll_h, wrap = tk.WORD, font=F_font)
        scrollText.grid(column=0, columnspan=3)
</code>```

Body:
I am using this code to make a scrolling text window using Tkinter with python 3.5, and I was curious what I could do to change the font size and color of the scrolling text.

 import tkinter as tk

 root = tk.Tk()
 deli = 100           # milliseconds of delay per character
 svar = tk.StringVar()
 labl = tk.Label(root, textvariable=svar, height=5)

 def shif():
     shif.msg = shif.msg[1:] + shif.msg[0]
     svar.set(shif.msg)
     root.after(deli, shif)

shif.msg = 'Text example: Blah, Blah Blah'
shif()
labl.pack()
root.mainloop()


问:
setInterval function difference Date.now()
I need a function that returns every 5000 milliseconds the difference between the result of the current Date.now () method and the previous one. I am trying to make a for to store the result in each iteration and then do the subtraction but I am not able to make it work.

let fecha = (Date.now())
setInterval(function () {
  let resultado = Date.now() - fecha
  //for() {}
  console.log(resultado)
 }, 5000);```

答:
You need to keep the current timestamp around for each iteration, otherwise you will always compare the current timestamp to the initial one, not the previous one:

let fecha = (Date.now())
setInterval(function () {
  let now = Date.now()
  let resultado = now - fecha
  fecha = now

  console.log(resultado)
 }, 5000);```

If your issue is that it's not exactly 5000 milliseconds, but roughly -- that's just how the JavaScript runtime works.

setInterval does not guarantee execution every n milliseconds, just execution at least n milliseconds apart, whenever it is able to schedule the next function execution.

Body:
You need to keep the current timestamp around for each iteration, otherwise you will always compare the current timestamp to the initial one, not the previous one:

let fecha = (Date.now())
setInterval(function () {
  let now = Date.now()
  let resultado = now - fecha
  fecha = now

  console.log(resultado)
 }, 5000);

If your issue is that it's not exactly 5000 milliseconds, but roughly -- that's just how the JavaScript runtime works.

setInterval does not guarantee execution every n milliseconds, just execution at least n milliseconds apart, whenever it is able to schedule the next function execution.


问:
recover all line from an attribute in a database in json
To simplify my problem,  I have a base in json, and I recover all of my lines of json to put informations in a base.
It seems easy for moments,  but problem is that my json is not correctly written

So i did a code to recover all my json lines,  but it doesn't work on all lines, like "biographie".

I show you

```<code>{"name": "Nazamiu0304 Rau0304majiu0304", "personal_name": "Nazamiu0304 Rau0304majiu0304", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:00:41.270799"}, "key": "/authors/OL1001461A", "type": {"key": "/type/author"}, "revision": 2}
{"name": "Nazamiu0304 Rau0304majiu0304", "personal_name": "Nazamiu0304 Rau0304majiu0304", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:00:41.270799"}, "key": "/authors/OL1001461A", "type": {"key": "/type/author"}, "revision": 2}
</code>```

you see, you have name,personal name ...

sometimes you have other informations,

```<code>{"bio": {"type": "/type/text", "value": "> "Eversley, William Pinder, B.C.L. Queen's Coll., Oxon, M.A., a member of the South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench Walk, Temple, E.C." rn> ...[in Foster's _Men at the Bar_][1]rnrnrn  rnrn[1]: https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar""}, "name": "William Pinder Eversley", "created": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "death_date": "1918", "photos": [6897255, 6897254], "last_modified": {"type": "/type/datetime", "value": "2018-07-31T15:39:07.982159"}, "latest_revision": 6, "key": "/authors/OL1003081A", "birth_date": "1851", "personal_name": "William Pinder Eversley", "type": {"key": "/type/author"}, "revision": 6}

{"name": "Valerie Meyer", "personal_name": "Valerie Meyer", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:22:33.63997"}, "key": "/authors/OL1004062A", "type": {"key": "/type/author"}, "revision": 2}
</code>```

You can see i have a lot of problem with the element "bio":  because he is not written correctely at all,  the quota are not interpreted correctely and "<"  too  so I got this code to change the structure of bio to exploit it.

Here my code to change structure of bio

import re
import json
import pprint

bio_regex = re.compile(
    r"""
("bio":\s*{)   # bio field start
(.*?)          # content
(},)           # bio field end
(?=\s*(?:"\w+"|}))  # followed by another one or the json end
""",
    flags=re.VERBOSE | re.DOTALL)

value_regex = re.compile(
    r"""
("value":\s*")   # value field start
(.*?)            # content
("\s*\Z)         # value field end + end of string
""",
    flags=re.VERBOSE | re.DOTALL)

def normalize_value(mo):
    start, content, end = mo.group(1, 2, 3)
    content = content.replace('"', '\\"')
    return start + content + end

def normalize_bio(mo):
    start, content, end = mo.group(1, 2, 3)
    content = value_regex.sub(normalize_value, content)
    return start + content + end

messy_json = """
{
  "bio":{
    "type":"/type/text",
    "value":"> "Eversley, William Pinder, B.C.L. Queen's Coll., Oxon, M.A., a member of the South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench Walk, Temple, E.C." rn> ...[in Foster's Men at the Bar][1]rnrnrn rnrn[1]: https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar""
  },
  "name":"William Pinder Eversley",
  "created":{
    "type":"/type/datetime",
    "value":"2008-04-01T03:28:50.625462"
  },
  "death_date":"1918",
  "photos":[
    6897255,
    6897254
  ],
  "last_modified":{
    "type":"/type/datetime",
    "value":"2018-07-31T15:39:07.982159"
  },
  "latest_revision":6,
  "key":"/authors/OL1003081A",
  "birth_date":"1851",
  "personal_name":"William Pinder Eversley",
  "type":{
    "key":"/type/author"
  },
  "revision":6
}"""

result = bio_regex.sub(normalize_bio, messy_json)
obj = json.loads(result)
```

<p>Here is the result:</p>

```
{'bio': {'type': '/type/text',
         'value': '> "Eversley, William Pinder, B.C.L. Queen\'s Coll., Oxon, M.A., a member of the '
                  "South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of "
                  'the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest '
                  "son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench "
                  'Walk, Temple, E.C." rn> ...[in Foster\'s Men at the Bar][1]rnrnrn rnrn[1]: '
                  'https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar"'},
 'birth_date': '1851',
 'created': {'type': '/type/datetime', 'value': '2008-04-01T03:28:50.625462'},
 'death_date': '1918',
 'key': '/authors/OL1003081A',
 'last_modified': {'type': '/type/datetime', 'value': '2018-07-31T15:39:07.982159'},
 'latest_revision': 6,
 'name': 'William Pinder Eversley',
 'personal_name': 'William Pinder Eversley',
 'photos': [6897255, 6897254],
 'revision': 6,
 'type': {'key': '/type/author'}}

```

The problem here is that this script is good if I put my entire line in my code,  but i would like to recover my 1000000 lines of bio with the good structure,  I can't do that 1 per 1,  I tried a lot of thing with a loop to recover 1 per 1 but it puts me always an error,  I need know how recuperate it witch a loop  .
I need upgrade my code to take all lines of database from line bio and not only 1 per 1

Thanks in advance and thanks to listen me!

答:
For exemple, I wanted say that : I have a file ,  openlibraryjson.json :

with these lines :

{"name": "Ismail Ibrahim Dr.", "title": "Dr.", "personal_name": "Ismail Ibrahim", "last_modified": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "key": "/authors/OL100304A", "type": {"key": "/type/author"}, "revision": 1}
{"bio": {"type": "/type/text", "value": "> "Eversley, William Pinder, B.C.L. Queen's Coll., Oxon, M.A., a member of the South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench Walk, Temple, E.C." rn> ...[in Foster's Men at the Bar][1]rnrnrn  rnrn[1]: https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar""}, "name": "William Pinder Eversley", "created": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "death_date": "1918", "photos": [6897255, 6897254], "last_modified": {"type": "/type/datetime", "value": "2018-07-31T15:39:07.982159"}, "latest_revision": 6, "key": "/authors/OL1003081A", "birth_date": "1851", "personal_name": "William Pinder Eversley", "type": {"key": "/type/author"}, "revision": 6}
{"name": "Valerie Meyer", "personal_name": "Valerie Meyer", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:22:33.63997"}, "key": "/authors/OL1004062A", "type": {"key": "/type/author"}, "revision": 2}
{"bio": {"type": "/type/text", "value": "[Deutsch] Deutscher Orientalist und Theologe.rn[English] German orientalist and biblical scholar."}, "name": "August Dillmann", "links": [{"url": "http://de.wikipedia.org/wiki/August_Dillmann", "type": {"key": "/type/link"}, "title": "Wikipedia (Deutsch)"}, {"url": "http://en.wikipedia.org/wiki/August_Dillmann", "type": {"key": "/type/link"}, "title": "Wikipedia (English)"}], "personal_name": "August Dillmann", "death_date": "4 July 1894.", "alternate_names": ["Christian Friedrich August Dillmann", "Ch. F. A. Dillmann", "Friedrich August Dillmann", "F. A. Dillmann", "Augustus Dillmann", "August Dillmann", "A. Dillmann"], "created": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "photos": [6676274], "last_modified": {"type": "/type/datetime", "value": "2017-03-31T12:45:57.925108"}, "latest_revision": 8, "key": "/authors/OL1179559A", "birth_date": "25 April 1823", "revision": 8, "type": {"key": "/type/author"}, "remote_ids": {"viaf": "45046685", "wikidata": "Q75216"}}
{"last_modified": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "type": {"key": "/type/author"}, "name": "Physikertagung (1966 Munich, Germany)", "key": "/authors/OL1179696A", "revision": 1}

I would like take only line bio and treat them to put them functionnal,  for it I tried to open my file, and I Treat name,personal_name ... with a loop,  it works but not for bio because it's not written correctly,  so I skip bio in my script for moment  But now i would like to don't skip bio and work with bio in the same way that for name,personal_name ...

Like it  :

with open('openlibrary(3).json') as file:
    for i in range(101):
        line = file.readline()
        if "bio" in line:
            line.replace("\'", "’")
            continue
        content_json = json.loads(line)
        if not "personal_name" in line:
           #print('NULL')
           ligne.append("NULL")
           continue
        try:
            #print(content_json['name'])
            ligne.append(content_json['personal_name'])
        except IndexError:
            print('NULL')
        if not "personal_name" in line:
            # print('NULL')
            personal_nom.append("NULL")
            continue
        try:
            # print(content_json['name'])
            personal_nom.append(content_json['personal_name'])
        except IndexError:
            print('NULL')

I just put some code here to show a bit what i did for name,personal_name...

Thanks you again for listen me and aswer me !!!!

Body:
To simplify my problem,  I have a base in json, and I recover all of my lines of json to put informations in a base.
It seems easy for moments,  but problem is that my json is not correctly written

So i did a code to recover all my json lines,  but it doesn't work on all lines, like "biographie".

I show you

{"name": "Nazamiu0304 Rau0304majiu0304", "personal_name": "Nazamiu0304 Rau0304majiu0304", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:00:41.270799"}, "key": "/authors/OL1001461A", "type": {"key": "/type/author"}, "revision": 2}
{"name": "Nazamiu0304 Rau0304majiu0304", "personal_name": "Nazamiu0304 Rau0304majiu0304", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:00:41.270799"}, "key": "/authors/OL1001461A", "type": {"key": "/type/author"}, "revision": 2}

you see, you have name,personal name ...

sometimes you have other informations,

{"bio": {"type": "/type/text", "value": "> "Eversley, William Pinder, B.C.L. Queen's Coll., Oxon, M.A., a member of the South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench Walk, Temple, E.C." rn> ...[in Foster's _Men at the Bar_][1]rnrnrn  rnrn[1]: https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar""}, "name": "William Pinder Eversley", "created": {"type": "/type/datetime", "value": "2008-04-01T03:28:50.625462"}, "death_date": "1918", "photos": [6897255, 6897254], "last_modified": {"type": "/type/datetime", "value": "2018-07-31T15:39:07.982159"}, "latest_revision": 6, "key": "/authors/OL1003081A", "birth_date": "1851", "personal_name": "William Pinder Eversley", "type": {"key": "/type/author"}, "revision": 6}

{"name": "Valerie Meyer", "personal_name": "Valerie Meyer", "last_modified": {"type": "/type/datetime", "value": "2008-08-20T18:22:33.63997"}, "key": "/authors/OL1004062A", "type": {"key": "/type/author"}, "revision": 2}

You can see i have a lot of problem with the element "bio":  because he is not written correctely at all,  the quota are not interpreted correctely and "<"  too  so I got this code to change the structure of bio to exploit it.

Here my code to change structure of bio

import re
import json
import pprint

bio_regex = re.compile(
    r"""
("bio":\s*{)   # bio field start
(.*?)          # content
(},)           # bio field end
(?=\s*(?:"\w+"|}))  # followed by another one or the json end
""",
    flags=re.VERBOSE | re.DOTALL)

value_regex = re.compile(
    r"""
("value":\s*")   # value field start
(.*?)            # content
("\s*\Z)         # value field end + end of string
""",
    flags=re.VERBOSE | re.DOTALL)

def normalize_value(mo):
    start, content, end = mo.group(1, 2, 3)
    content = content.replace('"', '\\"')
    return start + content + end

def normalize_bio(mo):
    start, content, end = mo.group(1, 2, 3)
    content = value_regex.sub(normalize_value, content)
    return start + content + end

messy_json = """
{
  "bio":{
    "type":"/type/text",
    "value":"> "Eversley, William Pinder, B.C.L. Queen's Coll., Oxon, M.A., a member of the South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench Walk, Temple, E.C." rn> ...[in Foster's Men at the Bar][1]rnrnrn rnrn[1]: https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar""
  },
  "name":"William Pinder Eversley",
  "created":{
    "type":"/type/datetime",
    "value":"2008-04-01T03:28:50.625462"
  },
  "death_date":"1918",
  "photos":[
    6897255,
    6897254
  ],
  "last_modified":{
    "type":"/type/datetime",
    "value":"2018-07-31T15:39:07.982159"
  },
  "latest_revision":6,
  "key":"/authors/OL1003081A",
  "birth_date":"1851",
  "personal_name":"William Pinder Eversley",
  "type":{
    "key":"/type/author"
  },
  "revision":6
}"""

result = bio_regex.sub(normalize_bio, messy_json)
obj = json.loads(result)

Here is the result:

{'bio': {'type': '/type/text',
         'value': '> "Eversley, William Pinder, B.C.L. Queen\'s Coll., Oxon, M.A., a member of the '
                  "South-eastern circuit, reporter for Law Times in Queen's Bench division, a student of "
                  'the Inner Temple 14 April, 1874 (then aged 23), called to the bar 25 April, 1877 (eldest '
                  "son of William Eversley, Esq., of London); born u2060, 1851. rn> rn> 7, King's Bench "
                  'Walk, Temple, E.C." rn> ...[in Foster\'s Men at the Bar][1]rnrnrn rnrn[1]: '
                  'https://en.wikisource.org/wiki/Men-at-the-Bar/Eversley,_William_Pinder "Men at the Bar"'},
 'birth_date': '1851',
 'created': {'type': '/type/datetime', 'value': '2008-04-01T03:28:50.625462'},
 'death_date': '1918',
 'key': '/authors/OL1003081A',
 'last_modified': {'type': '/type/datetime', 'value': '2018-07-31T15:39:07.982159'},
 'latest_revision': 6,
 'name': 'William Pinder Eversley',
 'personal_name': 'William Pinder Eversley',
 'photos': [6897255, 6897254],
 'revision': 6,
 'type': {'key': '/type/author'}}

The problem here is that this script is good if I put my entire line in my code,  but i would like to recover my 1000000 lines of bio with the good structure,  I can't do that 1 per 1,  I tried a lot of thing with a loop to recover 1 per 1 but it puts me always an error,  I need know how recuperate it witch a loop  .
I need upgrade my code to take all lines of database from line bio and not only 1 per 1

Thanks in advance and thanks to listen me!


问:
Bitcask ok for simple and high performant file store?
I am looking for a simple way to store and retrieve millions of xml files. Currently everything is done in a filesystem, which has some performance issues.

Our requirements are:

Ability to store millions of xml-files in a batch-process. XML files may be up to a few megs large, most in the 100KB-range.

Very fast random lookup by id (e.g. document URL)

Accessible by both Java and Perl

Available on the most important Linux-Distros and Windows

I did have a look at several NoSQL-Platforms (e.g. CouchDB, Riak and others), and while those systems look great, they seem almost like beeing overkill:

No clustering required

No daemon ("service") required

No clever search functionality required

Having delved deeper into Riak, I have found Bitcask (see intro), which seems like exactly what I want. The basics described in the intro are really intriguing. But unfortunately there is no means to access a bitcask repo via java (or is there?)

Soo my question boils down to

is the following assumption right: the Bitcask model (append-only writes, in-memory key management) is the right way to store/retrieve millions of documents

are there any viable alternatives to Bitcask available via Java? (BerkleyDB comes to mind...)

(for riak specialists) Is Riak much overhead implementation/management/resource wise compared to "naked" Bitcask?

答:
Bitcask can be appropriate for this case (large values) depending on whether or not there is a great deal of overwriting.  In particular, there is not reason to merge files unless there is a great deal of wasted space, which only occurs when new values arrive with the same key as old values.

Bitcask is particularly good for this batch load case as it will sequentially write the incoming data stream straight to disk.  Lookups will take one seek in most cases, although the file cache will help you if there is any temporal locality.

I am not sure on the status of a Java version/wrapper.


问:
Best way to syncing two different database
I have two database(SQL Server) one database has 2.5 million records and the other one is empty, i want to transfer data from first one to the second one and after that every time first database has been changed the second database must sync. And we must do it in offline way with excel file for example(there is no online way between them) , Can anyone show me a guideline to do this?</p>

答:
There are different ways to do that but I think the easiest could be replication, you can use Transactional replication or snapshot replication.

https://learn.microsoft.com/en-us/sql/relational-databases/replication/transactional/transactional-replication?view=sql-server-ver15


问:
Distinct pointer types lacks a cast in c
I am using the ST32 I-cube example code and trying to initiate the ADC with the following code:

```<code>ADC_HandleTypeDef hadc;

void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) {

  if(hadc->Instance==ADC){

  GPIO_InitTypeDef GPIO_InitStruct={0};

  /*##-1- Enable peripherals and GPIO Clocks #################################*/
  /* Enable GPIO clock ****************************************/
  __HAL_RCC_GPIOA_CLK_ENABLE();
  /* ADC1 Periph clock enable */

  /*##- 2- Configure peripheral GPIO #########################################*/
  /* ADC3 Channel8 GPIO pin configuration */
  GPIO_InitStruct.Pin = GPIO_PIN_0;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
.........
}
</code>```

The compiler is giving me a warning of "comparison of distinct pointer types lacks a cast" on the line :

if(hadc->Instance==ADC){

What i am doing wrong?

Appreciate the help!

答:
I'm almost certain that ADC is not a valid instance, you should be using ADC1 (or 2 or whatever) instead.

Looking in one of the STM32 header files shows:

```<code>// stm32f030x6.h
...
#define ADC1       ((ADC_TypeDef *) ADC1_BASE)
#define ADC        ((ADC_Common_TypeDef *) ADC_BASE) /* Kept for legacy purpose */
...
</code>```

This suggest to me you might have been looking at an old example, which remains so it's not an undefined symbol, but ADC1 has the type it's looking for while ADC does not.

Body:
I am using the ST32 I-cube example code and trying to initiate the ADC with the following code:

ADC_HandleTypeDef hadc;

void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) {

  if(hadc->Instance==ADC){

  GPIO_InitTypeDef GPIO_InitStruct={0};

  /*##-1- Enable peripherals and GPIO Clocks #################################*/
  /* Enable GPIO clock ****************************************/
  __HAL_RCC_GPIOA_CLK_ENABLE();
  /* ADC1 Periph clock enable */

  /*##- 2- Configure peripheral GPIO #########################################*/
  /* ADC3 Channel8 GPIO pin configuration */
  GPIO_InitStruct.Pin = GPIO_PIN_0;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
.........
}

The compiler is giving me a warning of "comparison of distinct pointer types lacks a cast" on the line :

if(hadc->Instance==ADC){

What i am doing wrong?

Appreciate the help!

Body:
I'm almost certain that ADC is not a valid instance, you should be using ADC1 (or 2 or whatever) instead.

Looking in one of the STM32 header files shows:

// stm32f030x6.h
...
#define ADC1       ((ADC_TypeDef *) ADC1_BASE)
#define ADC        ((ADC_Common_TypeDef *) ADC_BASE) /* Kept for legacy purpose */
...

This suggest to me you might have been looking at an old example, which remains so it's not an undefined symbol, but ADC1 has the type it's looking for while ADC does not.


问:
C# Iterating through list of objects
First post on here so go easy on me!

I'm trying to deserialize a json document into a list of objects.

So far I've got two classes - one which contains the data structure:

```<code> class Server
{
    public string hostname { get; set; }
    public string ipAddress { get; set; }
    public string monitoring { get; set; }
    public int pollingInterval { get; set; }

}
</code>```

The other that contains the collection

```<code>    class ServerCollection
{
    public List<Server> servers { get; set; }

}
</code>```

In the applicaion I do a simple ReadAllText and I'm deserializing the object like so

```<code>private ServerCollection _servers;
string json = File.ReadAllText(@"c:\users\admin\desktop\server.monitoring\servers.json");
_servers = JsonConvert.DeserializeObject<ServerCollection>(json);
</code>```

I'm struggling to iterate over this using a foreach... Can't think what I'm missing.

```<code>    Severity    Code    Description Project File    Line    Suppression State
Error   CS1579  foreach statement cannot operate on variables of type 'ServerCollection' because 'ServerCollection' does not contain a public instance definition for 'GetEnumerator'   Server.Monitoring.Service.Core  C:\Code\Admin\Server.Monitoring\Server.Monitoring.Service.Core\GetSystemHealth.cs   25  Active
</code>```

Any ideas on what I've missed?

Thanks in advance!

答:
```<code>class ServerCollection
{
    public List<Server> servers { get; set; }

}
</code>```

Is not a collection but Servers is, you need to iterate over that.

```<code>foreach (var server in _servers.servers)
{
    //do something with  server
}
</code>```

Title: C# Iterating through list of objects

Body:
First post on here so go easy on me!

I'm trying to deserialize a json document into a list of objects.

So far I've got two classes - one which contains the data structure:

 class Server
{
    public string hostname { get; set; }
    public string ipAddress { get; set; }
    public string monitoring { get; set; }
    public int pollingInterval { get; set; }

}

The other that contains the collection

    class ServerCollection
{
    public List<Server> servers { get; set; }

}

In the applicaion I do a simple ReadAllText and I'm deserializing the object like so

private ServerCollection _servers;
string json = File.ReadAllText(@"c:\users\admin\desktop\server.monitoring\servers.json");
_servers = JsonConvert.DeserializeObject<ServerCollection>(json);

I'm struggling to iterate over this using a foreach... Can't think what I'm missing.

    Severity    Code    Description Project File    Line    Suppression State
Error   CS1579  foreach statement cannot operate on variables of type 'ServerCollection' because 'ServerCollection' does not contain a public instance definition for 'GetEnumerator'   Server.Monitoring.Service.Core  C:\Code\Admin\Server.Monitoring\Server.Monitoring.Service.Core\GetSystemHealth.cs   25  Active

Any ideas on what I've missed?

Thanks in advance!

Body:
class ServerCollection
{
    public List<Server> servers { get; set; }

}

Is not a collection but Servers is, you need to iterate over that.

foreach (var server in _servers.servers)
{
    //do something with  server
}


答:
JDBC tinyint equivalent Java type is Byte.
Here is the hibernate documentation. Datatype mapping

JBoss tool will be helpful if you are using eclipse/STS to generate entities directly from the tables without datatype conflict.

Title: Spring Boot with JPA - wrong column type encountered in column

Body:
I'm using Spring Boot Starter Data Jpa (2.1.9.RELEASE) and I'm trying to map this table:

CREATE TABLE `foo` (
  `id` int(11) NOT NULL,
  `woo` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

The Entity is mapped as follows:

@Entity
@Table(name = "foo")
public class Foo {

    @Id
    @Column(name = "id")
    private Integer id;

    @Column(name = "woo")
    private Integer woo;

    public Integer getId() {
        return id;
    }

    public Integer getWoo() {
        return woo;
    }

}

When I start the application I get the following error:

Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: wrong column type encountered in column [woo] in table [foo]; found [tinyint (Types#TINYINT)], but expecting [integer (Types#INTEGER)]

My properties are:

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto=validate

I tried to do the same mapping using vanilla Jpa and Hibernate (not managed by Spring) and it works fine.

Can anyone point me in the right direction?

Here's a link to the maven project, in case anyone want to try it directly.


问:
C socket get IP address from filedescriptor returned from accept
I know this question seems typical and multiple times answered but I think if you read the details it is not so common (I did not find it).

The point is that I am developing a unix service in c that opens a socket and waits for connections, when I have a connection I create a new process to treat it, so there can be multiple connections opened at the same time.

```<code>int newfd = accept(sockfd, (struct sockaddr *)&clientaddr, (socklen_t*)&clientaddr_size);
</code>```

Later on (after and inside some other methods and code) the child process save the connection information to the BBDD and I need also, in that precise moment, to get the IP address that opened that connection being treated.

As there can be multiple connections at the same time and the variable struct sockaddr_in clientaddr that I pass to the accept method is shared for all the process I am not sure that later on is a good idea to get the IP address information from that way because then I could get the IP address from another connection opened.

I would like to be able to access the IP address from the file descriptor int newfd that I get from the accept method (the returned integer). Is it possible? Or I misunderstood the file descriptor function?

答: Statefull connection is uniquely identified by two end points Peer(address:port)<=>My(address:port). Both getpeername() and getsockname() are needed to get this information.</p>

Body:
I know this question seems typical and multiple times answered but I think if you read the details it is not so common (I did not find it).

The point is that I am developing a unix service in c that opens a socket and waits for connections, when I have a connection I create a new process to treat it, so there can be multiple connections opened at the same time.

int newfd = accept(sockfd, (struct sockaddr *)&clientaddr, (socklen_t*)&clientaddr_size);

Later on (after and inside some other methods and code) the child process save the connection information to the BBDD and I need also, in that precise moment, to get the IP address that opened that connection being treated.

As there can be multiple connections at the same time and the variable struct sockaddr_in clientaddr that I pass to the accept method is shared for all the process I am not sure that later on is a good idea to get the IP address information from that way because then I could get the IP address from another connection opened.

I would like to be able to access the IP address from the file descriptor int newfd that I get from the accept method (the returned integer). Is it possible? Or I misunderstood the file descriptor function?


答:
Your ServerCollection class does not implement the IEnumerable interface. You have two options:

Have ServerCollection implement that interface (i.e., public class ServerCollection : IEnumerable<Server> and add the necessary methods)

Loop over _servers.servers instead

The second option is the easier one to get you going, but implementing the interface may have other benefits down the road

Title: C# Iterating through list of objects


问:
Deliver apk android install to iframe the website
I want to make an application for my website but I don't want it to be really an application. I want to deliver and apk that can be installed on android device and just I frames the website and show the site in responsive mode. Is it easy to do that or any online tool for that!? </p>

答: what is your email? If you want, send me your app logo that you want and website link. I can send you .apk app if you want. My email is graspery@gmail.com</p>