问:
Getting patterns out of a binary string
I have a binary string of length N which is a power of 2 (N = 2^n).

I need to extract specific patterns of length L which is a power of 2 (L = 2^l).

In a full binary tree, these patterns should

start with a left leaf node (even index) and

end with a right leaf node (odd index).

These patterns should include leaves of an entire subtree.
Patterns I need to extract are,

```<code>(1). 0 0 --- 0  (All zero)
(2). 1 1 --- 1  (All one)
(3). 0 0 --- 1  (Only the last right leaf is one).
</code>```

For example, if I have a binary string of N=16, (n=4) such as
 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 ,  I need to extract

indices 0 to 7 as pattern (3),

indices 8 to 11 as pattern (2) and

last 4 indices as pattern (1).

I need this as a part of a channel decoding algorithm, to prune the binary tree. Is there an efficient method to do this in Matlab?

答:
I guess that the most simple solution will be to use a regular expression with regexp

```<code>%binary string example
s = '0000000111110000'

%Get the start Index (SI) and the end Index (EI)
[SI,EI] = regexp(s,'0+$')       %pattern 1
[SI,EI] = regexp(s,'0+1')       %pattern 2
[SI,EI] = regexp(s,'(?<!0)1+')  %pattern 3
</code>```

Noticed that index on matlab start with 1 and not 0.

You can also use multiple regular expression at once:

```<code>[SI,EI] = regexp(s,{'0+$','0+1','(?<!0)1+'})
</code>```

Result:

```<code>SI =
{
  [1,1] =  13
  [1,2] =  1
  [1,3] =  9
}
EI =
{
  [1,1] =  16
  [1,2] =  8
  [1,3] =  12
}
</code>```

Title: Getting patterns out of a binary string

Body:
I have a binary string of length N which is a power of 2 (N = 2^n).

I need to extract specific patterns of length L which is a power of 2 (L = 2^l).

In a full binary tree, these patterns should

start with a left leaf node (even index) and

end with a right leaf node (odd index).

These patterns should include leaves of an entire subtree.
Patterns I need to extract are,

(1). 0 0 --- 0  (All zero)
(2). 1 1 --- 1  (All one)
(3). 0 0 --- 1  (Only the last right leaf is one).

For example, if I have a binary string of N=16, (n=4) such as
 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 ,  I need to extract

indices 0 to 7 as pattern (3),

indices 8 to 11 as pattern (2) and

last 4 indices as pattern (1).

I need this as a part of a channel decoding algorithm, to prune the binary tree. Is there an efficient method to do this in Matlab?

Body:
I guess that the most simple solution will be to use a regular expression with regexp

%binary string example
s = '0000000111110000'

%Get the start Index (SI) and the end Index (EI)
[SI,EI] = regexp(s,'0+$')       %pattern 1
[SI,EI] = regexp(s,'0+1')       %pattern 2
[SI,EI] = regexp(s,'(?<!0)1+')  %pattern 3

Noticed that index on matlab start with 1 and not 0.

You can also use multiple regular expression at once:

[SI,EI] = regexp(s,{'0+$','0+1','(?<!0)1+'})

Result:

SI =
{
  [1,1] =  13
  [1,2] =  1
  [1,3] =  9
}
EI =
{
  [1,1] =  16
  [1,2] =  8
  [1,3] =  12
}


来源: stackexchange

问:
Spark Scala to count length in dataframe fields
New to Scala.

I have created a substring function in scala which requires "pos" and "len", I want pos to be hardcoded, however for the length it should count it from the dataframe. How would I go about doing this?

Here is my code:

```<code>val A = DF.select(col("example_ref"), substring(col("example_ref"),11, 21))
</code>```

Thanks in advance.

EDIT:

So added this code:

```<code>val A = DF.select($"example_ref",substring($"example_ref",11,length($"example_ref")))
</code>```

However I get the following errors:

```<code>Type Mismatch, expected: String, actual: Column
Type Mismatch, expected: Int, actual: Column
</code>```

答:
You can create an UDF to get the length of a column and then encapsulate the substring function in an expr function

```<code>val colLength = udf { (col: String) => col.size }
</code>```

And then use it in your code

```<code>val A = DF.select(col("example_ref"), expr("substring(col(example_ref),11, colLength(col(example_ref)))"))
</code>```

PS. I like most the dollar syntax to get the columns

```<code>val A = DF.select($"example_ref", expr("substring(example_ref,11, colLength(example_ref))"))
</code>```

EDIT

As pointed out in comments there is already a function to do that so you don't even need to define the UDF:

```<code>import org.apache.spark.sql.functions.length
val A = DF.select($"example_ref", expr("substring(example_ref,11, length(example_ref))"))
</code>```

QUICK EXAMPLE

INPUT

```<code>scala> val df = sc.parallelize(List((1, "abc"),(2, "bcd"),(3, "cde"))).toDF("number", "mycolumn")
df: org.apache.spark.sql.DataFrame = [number: int, mycolumn: string]

scala> df.show
+------+--------+
|number|mycolumn|
+------+--------+
|     1|     abc|
|     2|     bcd|
|     3|     cde|
+------+--------+
</code>```

OUTPUT

```<code>df.select(expr("substring(mycolumn, 2, length(mycolumn))")).show
+----------------------------------------+
|substring(mycolumn, 2, length(mycolumn))|
+----------------------------------------+
|                                      bc|
|                                      cd|
|                                      de|
+----------------------------------------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
New to Scala.

I have created a substring function in scala which requires "pos" and "len", I want pos to be hardcoded, however for the length it should count it from the dataframe. How would I go about doing this?

Here is my code:

val A = DF.select(col("example_ref"), substring(col("example_ref"),11, 21))

Thanks in advance.

EDIT:

So added this code:

val A = DF.select($"example_ref",substring($"example_ref",11,length($"example_ref")))

However I get the following errors:

Type Mismatch, expected: String, actual: Column
Type Mismatch, expected: Int, actual: Column

Body:
You can create an UDF to get the length of a column and then encapsulate the substring function in an expr function

val colLength = udf { (col: String) => col.size }

And then use it in your code

val A = DF.select(col("example_ref"), expr("substring(col(example_ref),11, colLength(col(example_ref)))"))

PS. I like most the dollar syntax to get the columns

val A = DF.select($"example_ref", expr("substring(example_ref,11, colLength(example_ref))"))

EDIT

As pointed out in comments there is already a function to do that so you don't even need to define the UDF:

import org.apache.spark.sql.functions.length
val A = DF.select($"example_ref", expr("substring(example_ref,11, length(example_ref))"))

QUICK EXAMPLE

INPUT

scala> val df = sc.parallelize(List((1, "abc"),(2, "bcd"),(3, "cde"))).toDF("number", "mycolumn")
df: org.apache.spark.sql.DataFrame = [number: int, mycolumn: string]

scala> df.show
+------+--------+
|number|mycolumn|
+------+--------+
|     1|     abc|
|     2|     bcd|
|     3|     cde|
+------+--------+

OUTPUT

df.select(expr("substring(mycolumn, 2, length(mycolumn))")).show
+----------------------------------------+
|substring(mycolumn, 2, length(mycolumn))|
+----------------------------------------+
|                                      bc|
|                                      cd|
|                                      de|
+----------------------------------------+


问:
Insert Row between range of numbers in Excel
My Excel have 1 Column and 10 Rows of sequential numbers. I want to create a macro which could start from top value of column then insert 2 rows with the first value of list and then move on to second value and do same and so on.</p>

```<code>Values Column
1
2
3

Result Column
1
1
1
2
2
2
3
3
3
</code>```

答:
I think this will do:

Sub insertRows()
Dim ws As Worksheet: Set ws = ActiveSheet
Dim lastRow As Long: lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Dim R As Long

    For R = lastRow To 2 Step -1
        ws.Rows(R & ":" & R + 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        ws.Range(ws.Cells(R, 1), ws.Cells(R + 1, 1)) = ws.Cells(R + 2, 1).Value
    Next R

End Sub
```

PS: this is working its up from the bottom... not top to bottom.

Body:
My Excel have 1 Column and 10 Rows of sequential numbers. I want to create a macro which could start from top value of column then insert 2 rows with the first value of list and then move on to second value and do same and so on.

Values Column
1
2
3

Result Column
1
1
1
2
2
2
3
3
3

Body:
I think this will do:

Sub insertRows()
Dim ws As Worksheet: Set ws = ActiveSheet
Dim lastRow As Long: lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Dim R As Long

    For R = lastRow To 2 Step -1
        ws.Rows(R & ":" & R + 1).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        ws.Range(ws.Cells(R, 1), ws.Cells(R + 1, 1)) = ws.Cells(R + 2, 1).Value
    Next R

End Sub

PS: this is working its up from the bottom... not top to bottom.


问:
Getting "Refused to apply inline style because it violates the following Content Security Policy" error
I am getting the below error while running the application

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/ 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs='". Either the 'unsafe-inline' keyword, a hash ('sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ='), or a nonce ('nonce-...') is required to enable inline execution.

Below is the code currently I am using

```<code>const string modernizrHash1 = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
            const string modernizrHash2 = "sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=";
            app.UseCsp(options => options
                .DefaultSources(s => s.Self())
                .ScriptSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/"))
                .StyleSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/", modernizrHash1, modernizrHash2))
                .FontSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/"))
                .ImageSources(s => s.Self().CustomSources("data:"))
            );
</code>```

答:
You are getting this error because the inline styles (which can be hashed to sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=) aren't allowed, as per your Content Security Policy and the error that is returned.

I would recommend two possible steps, either:

Move away from inline styles (as they can be insecure) and will require you to change your CSP each time that the inline styles change.

Add the supplied SHA to the StyleSources for your CSP. But Be aware that this will have to be maintained and updated for each inline style added across all pages in your application.

UPDATE based on comments below answer

Note: There is no issue when i am running it in IE browser, only in the chrome and firefox i am getting the issue

Taking a look at Can I Use shows that IE has only partial support for Content Security Policy, which would explain why you aren't seeing this error in the console. i.e. Internet Explorer doesn't support CSP, so it isn't applying it.

I have fixed the issue by changing the hash keys shown in the browsers console error, I have replaced the console error hash key with my code hash key, but not sure whether this is the permanent solution or not

This is not really a permanent solution. If (and when) your inline styles change, you will have to change the hash in your CSP in order for the styles to be applied again.

Which leads me on to:

Could you please guide me how the hash keys are getting generated and how i can fix this permanently

Looking at the code in your original question:

const string modernizrHash1 = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
const string modernizrHash2 = "sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=";
// other things
.StyleSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/", modernizrHash1, modernizrHash2))
```

<p>You are telling the browser (via the Content Security Policy that you are generating) that it is only permitted to load styles from:</p>

<ul>
<li>self (the origin domain of your site)</li>
<li>https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/</li>
</ul>

<p>and those which match the following hashes:</p>

<ul>
<li>sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=</li>
<li>sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=</li>
</ul>

<p>You mention that you've also included the hash:</p>

<ul>
<li>sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=</li>
</ul>

<p>When the browser starts to render the page, it will look at the resources that the page requires in order to render and will compare it to the list in the Content Security Policy. If a resource (inline styles and inline javascript are classed as a resource) is not in the list, then the browser will do a simple SHA-2 of the contents of the resource and compares it to any of the hashes listed in the CSP.</p>

<p>Note: the same thing can be achieved by the use of a nonce</p>

<p>If the resource isn't from an allowed source, or it's hash does not match those listed in the CSP, then the browser will actively refuse it.</p>

<p>Because the SHA-2 algorithm uses the content of the resource to generate the hash, when the contents of it changes the calculated value of the hash will be different.</p>

<p>For example, the inline style here:</p>

<pre class="lang-html prettyprint-override"><code><p style="color: red;">hello, world</p>
</code>```

might hash to F1FF77E5DDBB1AF52EB51C98F725927143221549385937595112128987CF39E4 (which is the hash of "color:red")

whereas the following inline style:

hello, world

```

might has to 2F262B22412B633D12B27FA9F94A3B0495821CB8341CFF0A88C80E3FED5DC9E8 (which is the hash of "color:green")

As you can see, there is a massive difference in the hashed styles. This is by design (in the algorithm).

To stop alleviate this problem, I would swap the inline styles for a css file describing how the content of the page should be styled. As long as the css file is served from the same origin as your HTML, then the self rule will cover it.

CSP is a pretty complex topic to pick up (but easy to master, once you have learned the basics). I would recommend taking a look at the MDN page for Content Security Policy for more information on how it works and how you can use it to secure your web applications.

Body:
I am getting the below error while running the application

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self' https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/ 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' 'sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs='". Either the 'unsafe-inline' keyword, a hash ('sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ='), or a nonce ('nonce-...') is required to enable inline execution.

Below is the code currently I am using

const string modernizrHash1 = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
            const string modernizrHash2 = "sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=";
            app.UseCsp(options => options
                .DefaultSources(s => s.Self())
                .ScriptSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/"))
                .StyleSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/", modernizrHash1, modernizrHash2))
                .FontSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/"))
                .ImageSources(s => s.Self().CustomSources("data:"))
            );

Body:
You are getting this error because the inline styles (which can be hashed to sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=) aren't allowed, as per your Content Security Policy and the error that is returned.

I would recommend two possible steps, either:

Move away from inline styles (as they can be insecure) and will require you to change your CSP each time that the inline styles change.

Add the supplied SHA to the StyleSources for your CSP. But Be aware that this will have to be maintained and updated for each inline style added across all pages in your application.

UPDATE based on comments below answer

Note: There is no issue when i am running it in IE browser, only in the chrome and firefox i am getting the issue

Taking a look at Can I Use shows that IE has only partial support for Content Security Policy, which would explain why you aren't seeing this error in the console. i.e. Internet Explorer doesn't support CSP, so it isn't applying it.

I have fixed the issue by changing the hash keys shown in the browsers console error, I have replaced the console error hash key with my code hash key, but not sure whether this is the permanent solution or not

This is not really a permanent solution. If (and when) your inline styles change, you will have to change the hash in your CSP in order for the styles to be applied again.

Which leads me on to:

Could you please guide me how the hash keys are getting generated and how i can fix this permanently

Looking at the code in your original question:

const string modernizrHash1 = "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=";
const string modernizrHash2 = "sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=";
// other things
.StyleSources(s => s.Self().CustomSources("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/", modernizrHash1, modernizrHash2))

You are telling the browser (via the Content Security Policy that you are generating) that it is only permitted to load styles from:

self (the origin domain of your site)

https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/

and those which match the following hashes:

sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=

sha256-5uIP+HBVRu0WW8ep6d6+YVfhgkl0AcIabZrBS5JJAzs=

You mention that you've also included the hash:

sha256-4Su6mBWzEIFnH4pAGMOuaeBrstwJN4Z3pq/s1Kn4/KQ=

When the browser starts to render the page, it will look at the resources that the page requires in order to render and will compare it to the list in the Content Security Policy. If a resource (inline styles and inline javascript are classed as a resource) is not in the list, then the browser will do a simple SHA-2 of the contents of the resource and compares it to any of the hashes listed in the CSP.

Note: the same thing can be achieved by the use of a nonce

If the resource isn't from an allowed source, or it's hash does not match those listed in the CSP, then the browser will actively refuse it.

Because the SHA-2 algorithm uses the content of the resource to generate the hash, when the contents of it changes the calculated value of the hash will be different.

For example, the inline style here:

<p style="color: red;">hello, world</p>

might hash to F1FF77E5DDBB1AF52EB51C98F725927143221549385937595112128987CF39E4 (which is the hash of "color:red")

whereas the following inline style:

<p style="color: green;">hello, world</p>

might has to 2F262B22412B633D12B27FA9F94A3B0495821CB8341CFF0A88C80E3FED5DC9E8 (which is the hash of "color:green")

As you can see, there is a massive difference in the hashed styles. This is by design (in the algorithm).

To stop alleviate this problem, I would swap the inline styles for a css file describing how the content of the page should be styled. As long as the css file is served from the same origin as your HTML, then the self rule will cover it.

CSP is a pretty complex topic to pick up (but easy to master, once you have learned the basics). I would recommend taking a look at the MDN page for Content Security Policy for more information on how it works and how you can use it to secure your web applications.


问:
How to detect intersection of a UIBezierPath and erase it
I am making an iOS drawing app and would like to add functionality where erasing a UIBezierPath will erase the whole path and not just overlay the segment with a white color.

I have an array of UIBezierPaths stored, but I am not sure how efficient it is to loop through the entire array for each touch point, detect if it intersects with the current touch point, and remove it from the array.

Any suggestions?

答:
If I understand correctly you need to loop through path at least. They are independent after all.

An UIBezierPaths has method contains which would tell you if a point is inside the path. If that is usable then what you need to do is simply

```<code>paths = paths.filter { !$0.contains(touchPoint) }
</code>```

But since this is drawing app it is safe to assume you are using stroke and not fill which will most likely not work with contains the way you want it to.

You could do the intersection manually and it should have relatively good performance up until you have too many points. But when you have too many points I wager drawing performance will be more of your concern. Still the intersection may be a bit problematic with including some stroke line width; user would need to cross the center of your line to detect a hit.

There is a way though to convert stroked path to filled path. Doing that will then enable you to use contains method. The method is called replacePathWithStrokedPath but the thing is that it only exists on CGContext (At least I have never managed to find an equivalent on UIBezierPath). So procedure to do so includes creating a context. For instance something like this will work:

```<code>static func convertStrokePathToFillPath(_ path: UIBezierPath) throws -> UIBezierPath {
    UIGraphicsBeginImageContextWithOptions(CGSize(width: 1.0, height: 1.0), true, 1.0)
    guard let context = UIGraphicsGetCurrentContext() else { throw NSError(domain: "convertStrokePathToFillPath", code: 500, userInfo: ["dev_message":"Could not generate image context"]) }

    context.addPath(path.cgPath)
    context.setLineWidth(path.lineWidth)
    // TODO: apply all possible settings from path to context
    context.replacePathWithStrokedPath()

    guard let returnedPath = context.path else { throw NSError(domain: "convertStrokePathToFillPath", code: 500, userInfo: ["dev_message":"Could not get path from context"]) }
    UIGraphicsEndImageContext()

    return UIBezierPath(cgPath: returnedPath)
}
</code>```

So the result should look something like:

```<code>static func filterPaths(_ paths: [UIBezierPath], containingPoint point: CGPoint) -> [UIBezierPath] {
    return paths.filter { !(try! convertStrokePathToFillPath($0).contains(point)) }
}
</code>```

Body:
If I understand correctly you need to loop through path at least. They are independent after all.

An UIBezierPaths has method contains which would tell you if a point is inside the path. If that is usable then what you need to do is simply

paths = paths.filter { !$0.contains(touchPoint) }

But since this is drawing app it is safe to assume you are using stroke and not fill which will most likely not work with contains the way you want it to.

You could do the intersection manually and it should have relatively good performance up until you have too many points. But when you have too many points I wager drawing performance will be more of your concern. Still the intersection may be a bit problematic with including some stroke line width; user would need to cross the center of your line to detect a hit.

There is a way though to convert stroked path to filled path. Doing that will then enable you to use contains method. The method is called replacePathWithStrokedPath but the thing is that it only exists on CGContext (At least I have never managed to find an equivalent on UIBezierPath). So procedure to do so includes creating a context. For instance something like this will work:

static func convertStrokePathToFillPath(_ path: UIBezierPath) throws -> UIBezierPath {
    UIGraphicsBeginImageContextWithOptions(CGSize(width: 1.0, height: 1.0), true, 1.0)
    guard let context = UIGraphicsGetCurrentContext() else { throw NSError(domain: "convertStrokePathToFillPath", code: 500, userInfo: ["dev_message":"Could not generate image context"]) }

    context.addPath(path.cgPath)
    context.setLineWidth(path.lineWidth)
    // TODO: apply all possible settings from path to context
    context.replacePathWithStrokedPath()

    guard let returnedPath = context.path else { throw NSError(domain: "convertStrokePathToFillPath", code: 500, userInfo: ["dev_message":"Could not get path from context"]) }
    UIGraphicsEndImageContext()

    return UIBezierPath(cgPath: returnedPath)
}

So the result should look something like:

static func filterPaths(_ paths: [UIBezierPath], containingPoint point: CGPoint) -> [UIBezierPath] {
    return paths.filter { !(try! convertStrokePathToFillPath($0).contains(point)) }
}


问:
Python Mysqldb cursor has no attribute 'fetchAll'
I keep getting the error "AttributeError: 'Cursor' object has no attribute 'fetchAll'".  My rowCount is 451 and all queries are working.

I've looked into this problem and most mistakes involve calling fetchAll() on the return value of cursor.execute(), but this is not what I'm doing here.

```<code>#initialize cursors
presswiseCursor = presswiseConnection.cursor()
localCursor = localConnection.cursor()

#products
#initialize table
localCursor.execute("DROP TABLE IF EXISTS products;")
localCursor.execute("CREATE TABLE products (id INT NOT NULL, description VARCHAR(255));")
#get data from presswise
rowCount = presswiseCursor.execute("SELECT DISTINCT id, description FROM list_product;")
print(rowCount)
rows = presswiseCursor.fetchAll()
#add data to local
for row in rows:
    localCursor.execute(f'INSERT INTO products (id, description) VALUES({row[0]}{row[1]})')
</code>```

I would like to iterate over the results of the query and have used this exact technique before.  What's wrong with my code?

答:
use fetchall() instead of fetchAll() in python3.
Thank you.</p>

Body:
I keep getting the error "AttributeError: 'Cursor' object has no attribute 'fetchAll'".  My rowCount is 451 and all queries are working.

I've looked into this problem and most mistakes involve calling fetchAll() on the return value of cursor.execute(), but this is not what I'm doing here.

#initialize cursors
presswiseCursor = presswiseConnection.cursor()
localCursor = localConnection.cursor()

#products
#initialize table
localCursor.execute("DROP TABLE IF EXISTS products;")
localCursor.execute("CREATE TABLE products (id INT NOT NULL, description VARCHAR(255));")
#get data from presswise
rowCount = presswiseCursor.execute("SELECT DISTINCT id, description FROM list_product;")
print(rowCount)
rows = presswiseCursor.fetchAll()
#add data to local
for row in rows:
    localCursor.execute(f'INSERT INTO products (id, description) VALUES({row[0]}{row[1]})')

I would like to iterate over the results of the query and have used this exact technique before.  What's wrong with my code?


问:
how to print a sorted list which contains a tuple formed by a tuple and a value int
I have this list, I wanna sorted my tuples based on the int value

```<code>list = [((u'Wyndham', u'Grand'), 1), ((u'Pittsburgh', u'My'), 1), ((u'Poor', u'Terrible'), 1), ((u'PLACE', u'IN'), 1), ((u'Poor', u'Everything'), 1), ((u'Junior', u'Suite'), 1), ((u'WE', u'HAD'), 1), ((u'Wyndham', u'People'), 1), ((u'United', u'States'), 1), ((u'NIGHTMARE\U0001f623\U0001f623\U0001f623', u'Dirty'), 1), ((u'A', u'FAKE'), 1), ((u'SEPERATE', u'TIMES'), 1), ((u'DO', u'NOT'), 1), ((u'WORST', u'PLACE'), 1), ((u'Burger', u'King'), 1), ((u'FINAL', u'AFTER'), 1), ((u'STAY', u'THERE'), 1), ((u'Hotel', u'California'), 1), ((u'Don', u'\u2019'), 4), ((u'THERE', u'Nothing'), 1), ((u'HOTEL', u'CALIFORNIA'), 1), ((u'Santa', u'Monica'), 4), ((u'Universal', u'Studios'), 1)]
</code>```

I have tried this:

```<code>sorted ( list, key=lambda x: x[ 1 ], reverse=True )
</code>```

but it doesn't work.

Thanks for your help!

Body:
I have this list, I wanna sorted my tuples based on the int value

list = [((u'Wyndham', u'Grand'), 1), ((u'Pittsburgh', u'My'), 1), ((u'Poor', u'Terrible'), 1), ((u'PLACE', u'IN'), 1), ((u'Poor', u'Everything'), 1), ((u'Junior', u'Suite'), 1), ((u'WE', u'HAD'), 1), ((u'Wyndham', u'People'), 1), ((u'United', u'States'), 1), ((u'NIGHTMARE\U0001f623\U0001f623\U0001f623', u'Dirty'), 1), ((u'A', u'FAKE'), 1), ((u'SEPERATE', u'TIMES'), 1), ((u'DO', u'NOT'), 1), ((u'WORST', u'PLACE'), 1), ((u'Burger', u'King'), 1), ((u'FINAL', u'AFTER'), 1), ((u'STAY', u'THERE'), 1), ((u'Hotel', u'California'), 1), ((u'Don', u'\u2019'), 4), ((u'THERE', u'Nothing'), 1), ((u'HOTEL', u'CALIFORNIA'), 1), ((u'Santa', u'Monica'), 4), ((u'Universal', u'Studios'), 1)]

I have tried this:

sorted ( list, key=lambda x: x[ 1 ], reverse=True )

but it doesn't work.

Thanks for your help!

Body:
You can try:

sorted(list, key=lambda x: x[1], reverse=True )

Output:

[(('Don', '’'), 4), (('Santa', 'Monica'), 4), (('Wyndham', 'Grand'), 1), (('Pittsburgh', 'My'), 1), (('Poor', 'Terrible'), 1), (('PLACE', 'IN'), 1), (('Poor', 'Everything'), 1), (('Junior', 'Suite'), 1), (('WE', 'HAD'), 1), (('Wyndham', 'People'), 1), (('United', 'States'), 1), (('NIGHTMARE', 'Dirty'), 1), (('A', 'FAKE'), 1), (('SEPERATE', 'TIMES'), 1), (('DO', 'NOT'), 1), (('WORST', 'PLACE'), 1), (('Burger', 'King'), 1), (('FINAL', 'AFTER'), 1), (('STAY', 'THERE'), 1), (('Hotel', 'California'), 1), (('THERE', 'Nothing'), 1), (('HOTEL', 'CALIFORNIA'), 1), (('Universal', 'Studios'), 1)]


问:
How to add my own image with message like emoticons
okay...

I have asked this question about this but there is a new thing that i want to ask..

like emoticons I want to add my own image  with the iphone message ...

I am thankful if anybody can give me the idea about how to do this???

is this possible??

答:
When you receive the message you need to decode the characters and display corresponding image for that character.

For example if you receive message :-) it is ':','-' and ')' then display an smiley image... similarly different emotions for different messages.

 You need to maintain the list of character set and corresponding image for that set of characters

ContentLicense: CC BY-SA 3.0


问:
Python module has no attribute while the attribute exists
Taking help from here, I was writing my own package. I have a folder filter which contains __init__.py (completely empty) and pca.py. pca.py has a class pca and that class has a method performPCA which takes two arguments. Then, I have this code:

```<code>from filter import pca
....
pca.performPCA(x,2)
</code>```

When I run this, I'm getting an error

```<code>AttributeError: module 'filter.pca' has no attribute 'performPCA'
</code>```

I know this question has an answer here, but I have everything that answer asks (the only difference is that my __init__.py is empty, which I think is totally fine). Please tell me where am I wrong. Thanks!

test.py goes as:

```<code>from filter import pca
print(pca)
import pandas as pd

x=pd.read_csv('Assignment-DS_gene_data.csv')
meta=pd.read_csv('Assignment-DS_Meta_data_sheet_.csv')
x.rename(columns={'Unnamed: 0':'col1'}, inplace=True )
del x['symbol']
del x['col1']
p=pca.pca2
#print(p)
xNew=p.performPCA(x,2)
</code>```

pca.py goes as:

```<code>import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D

class pca2:
    #Choose this method if only projected data is required
    def perfromPCA(self,data,nComp):
        pcaModel = PCA(n_components=nComp)
        principalComponents = pcaModel.fit_transform(data)
        colNames = []
        for i in range(1,nComp+1):
            colNames.append('PC '+str(i))
        principalDf = pd.DataFrame(data = principalComponents
             , columns = colNames)
        return principalDf

    #Choose this method if plot and projected data both are required
    #For this, nComp can either be 2 or 3
    def performPCAPlot(self,data,nComp,metaData,column):
        principalDf = performPCA(data,nComp)
        if nComp == 2:
            plt.scatter(principalDf,data=metaData['column'])
            #plt.xlabel('PC1')
            #plt.ylabel('PC2')
            plt.show()
        else:
            fig = plt.figure()
            #to do
        return principalDf
</code>```

答:
Create an object first and then call the function on that object.

```<code>myPCA = pca()
myPCA.performPCA(x,2)
</code>```

Edit

You are creating a python package by adding the _ init _.py file in the filter directory further reading subsection 6.4

You can import and use it like this (working for me with python 3.7.0)

```<code>from filter.pca import pca

myPCA = pca()
myPCA.performPCA(2,2)

</code>```

or after renaming the class to pca2:

```<code>from filter.pca import pca2

myPCA = pca2()
myPCA.performPCA(2,2)

</code>```

Body:
Taking help from here, I was writing my own package. I have a folder filter which contains __init__.py (completely empty) and pca.py. pca.py has a class pca and that class has a method performPCA which takes two arguments. Then, I have this code:

from filter import pca
....
pca.performPCA(x,2)

When I run this, I'm getting an error

AttributeError: module 'filter.pca' has no attribute 'performPCA'

I know this question has an answer here, but I have everything that answer asks (the only difference is that my __init__.py is empty, which I think is totally fine). Please tell me where am I wrong. Thanks!

test.py goes as:

from filter import pca
print(pca)
import pandas as pd

x=pd.read_csv('Assignment-DS_gene_data.csv')
meta=pd.read_csv('Assignment-DS_Meta_data_sheet_.csv')
x.rename(columns={'Unnamed: 0':'col1'}, inplace=True )
del x['symbol']
del x['col1']
p=pca.pca2
#print(p)
xNew=p.performPCA(x,2)

pca.py goes as:

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D

class pca2:
    #Choose this method if only projected data is required
    def perfromPCA(self,data,nComp):
        pcaModel = PCA(n_components=nComp)
        principalComponents = pcaModel.fit_transform(data)
        colNames = []
        for i in range(1,nComp+1):
            colNames.append('PC '+str(i))
        principalDf = pd.DataFrame(data = principalComponents
             , columns = colNames)
        return principalDf

    #Choose this method if plot and projected data both are required
    #For this, nComp can either be 2 or 3
    def performPCAPlot(self,data,nComp,metaData,column):
        principalDf = performPCA(data,nComp)
        if nComp == 2:
            plt.scatter(principalDf,data=metaData['column'])
            #plt.xlabel('PC1')
            #plt.ylabel('PC2')
            plt.show()
        else:
            fig = plt.figure()
            #to do
        return principalDf

Body:
Create an object first and then call the function on that object.

myPCA = pca()
myPCA.performPCA(x,2)

Edit

You are creating a python package by adding the _ init _.py file in the filter directory further reading subsection 6.4

You can import and use it like this (working for me with python 3.7.0)

from filter.pca import pca

myPCA = pca()
myPCA.performPCA(2,2)

or after renaming the class to pca2:

from filter.pca import pca2

myPCA = pca2()
myPCA.performPCA(2,2)


问:
SceneKit smooth camera movement
What is the standard method for smooth camera movement within SceneKit (OpenGL)?
Manually changing x,y isn't smooth enough, yet using CoreAnimation creates "pulsing" movement. The docs on SceneKit seem to be very limited so any examples would be appreciated, I'm currently doing this:</p>

```<code>- (void)keyDown:(NSEvent *)theEvent {
    int key = [theEvent keyCode];
    int x = cameraNode.position.x;
    int y = cameraNode.position.y;
    int z = cameraNode.position.z;
    int speed = 4;
    if (key==123) {//left
        x-=speed;
    } else if (key==124) {//right
        x+=speed;
    } else if (key==125) {//down
        y-=speed;
    } else if (key==126) {//up
        y+=speed;
    }
    //move the camera
    [SCNTransaction begin];
    [SCNTransaction setAnimationDuration: 1.0];
    // Change properties
    cameraNode.position = SCNVector3Make(x, y, z);
    [SCNTransaction commit];
}
</code>```

答:
I move camera using this code:</p>

```<code>let lerpX = (heroNode.position.x - followCamera.position.x) * 0.05
let lerpZ = (heroNode.position.z - followCamera.position.z) * 0.05
followCamera.position.x += lerpX
followCamera.position.z += lerpZ
</code>```

Title: SceneKit smooth camera movement

Body:
What is the standard method for smooth camera movement within SceneKit (OpenGL)?
Manually changing x,y isn't smooth enough, yet using CoreAnimation creates "pulsing" movement. The docs on SceneKit seem to be very limited so any examples would be appreciated, I'm currently doing this:

- (void)keyDown:(NSEvent *)theEvent {
    int key = [theEvent keyCode];
    int x = cameraNode.position.x;
    int y = cameraNode.position.y;
    int z = cameraNode.position.z;
    int speed = 4;
    if (key==123) {//left
        x-=speed;
    } else if (key==124) {//right
        x+=speed;
    } else if (key==125) {//down
        y-=speed;
    } else if (key==126) {//up
        y+=speed;
    }
    //move the camera
    [SCNTransaction begin];
    [SCNTransaction setAnimationDuration: 1.0];
    // Change properties
    cameraNode.position = SCNVector3Make(x, y, z);
    [SCNTransaction commit];
}

Body:
I move camera using this code:

let lerpX = (heroNode.position.x - followCamera.position.x) * 0.05
let lerpZ = (heroNode.position.z - followCamera.position.z) * 0.05
followCamera.position.x += lerpX
followCamera.position.z += lerpZ


问:
how to open only one db connection for all the queries
The question is:
Is there any problem if i open the db connection once every 100 ms in a timer?
I think the best way is to open once the connection and then do the query all the times needed. Right?

My code is:

```<code> Friend conexion As MySqlConnection
    Private cmd As New MySqlCommand
    Private dr As MySqlDataReader
    Private ConnectionString = "server=localhost; uid=root; pwd=; database=myblahdb;"

  conexion = New MySqlConnection()
  conexion.ConnectionString = ConnectionString
conexion.Open()

 Dim cmd As New MySqlCommand
       With cmd
            .CommandText = "select blah blah"
            .CommandType = CommandType.Text
            .Connection = conexion
        End With
        dr = cmd.ExecuteReader

        If dr.HasRows Then
            dr.Read()
            //do stuff
        End If

        cmd.Dispose()
        dr.Close()
        dr.Dispose()
        conexion.Close()
        conexion.Dispose()
</code>```

答:
moving this to form_load in order to do on start

```<code>conexion = New MySqlConnection()
conexion.ConnectionString = ConnectionString
conexion.Open()
</code>```

and doing this on exit

```<code> conexion.Close()
 conexion.Dispose()
</code>```

is the solution

Body:
The question is:
Is there any problem if i open the db connection once every 100 ms in a timer?
I think the best way is to open once the connection and then do the query all the times needed. Right?

My code is:

 Friend conexion As MySqlConnection
    Private cmd As New MySqlCommand
    Private dr As MySqlDataReader
    Private ConnectionString = "server=localhost; uid=root; pwd=; database=myblahdb;"

  conexion = New MySqlConnection()
  conexion.ConnectionString = ConnectionString
conexion.Open()

 Dim cmd As New MySqlCommand
       With cmd
            .CommandText = "select blah blah"
            .CommandType = CommandType.Text
            .Connection = conexion
        End With
        dr = cmd.ExecuteReader

        If dr.HasRows Then
            dr.Read()
            //do stuff
        End If

        cmd.Dispose()
        dr.Close()
        dr.Dispose()
        conexion.Close()
        conexion.Dispose()

Body:
moving this to form_load in order to do on start

conexion = New MySqlConnection()
conexion.ConnectionString = ConnectionString
conexion.Open()

and doing this on exit

 conexion.Close()
 conexion.Dispose()

is the solution


问:
How to check if a List<List<int>> contains a List<int>
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

```<code>List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();
</code>```

I have already tried

```<code>MaterList.Contains, MasterList.Any
</code>```

but nothing is helping

e.g.

```<code>MasterList(1)=1,2,3
MasterList(2)=4,5
</code>```

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

答:
I tested following and it works :</p>

```<code>           List<List<int>> masterList = new List<List<int>>() {
                new List<int>() { 1, 2, 3},
                new List<int>() { 1, 2},
                new List<int>() { 1, 2, 3, 4},
                new List<int>() { 1, 2, 5},
                new List<int>() { 1, 3, 7},
                new List<int>() { 2, 3, 4},
                new List<int>() { 1, 5, 8},
                new List<int>() { 1, 4, 9}
            };

            List<int> newList = new List<int>() { 1,2,5};
            Boolean contains = masterList.Any(x => (x.Count() == newList.Count()) && (x.Select((y, i) => y == newList[i]).All(y => y)));
</code>```

Body:
I have a List<List<int>> in which I would like to insert a new List<int>. I would like to check before adding the new List<int> if it already exists in the List<List<int>>.

For e.g.

List<List<int>> MasterList = new List<List<int>>();
List<int> childList = new List<int>();

I have already tried

MaterList.Contains, MasterList.Any

but nothing is helping

e.g.

MasterList(1)=1,2,3
MasterList(2)=4,5

but when I see 1,2,3 or 4,5 is coming again then do not want to enter it as they are already there somewhere in MasterList

Body:
I tested following and it works :

           List<List<int>> masterList = new List<List<int>>() {
                new List<int>() { 1, 2, 3},
                new List<int>() { 1, 2},
                new List<int>() { 1, 2, 3, 4},
                new List<int>() { 1, 2, 5},
                new List<int>() { 1, 3, 7},
                new List<int>() { 2, 3, 4},
                new List<int>() { 1, 5, 8},
                new List<int>() { 1, 4, 9}
            };

            List<int> newList = new List<int>() { 1,2,5};
            Boolean contains = masterList.Any(x => (x.Count() == newList.Count()) && (x.Select((y, i) => y == newList[i]).All(y => y)));


问:
Run a macro when a pivot table changes
Is there any way to detect when a pivot table changes, filters are set, in VBA?

I have a macro I would like to automatically run when the user changes the filters of the pivot table.

答:
The other answer is almost elegant, but the PivotTableUpdate event is not raised, if some captions are changed:

If you need an event for any change within your pivot table, use following instead within your worksheet's code module:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.PivotTables(1).TableRange2) Is Nothing Then
        MsgBox "Pivot's TableRange2 Changed"
    End If
End Sub
</code>```

Title: Run a macro when a pivot table changes

Body:
The other answer is almost elegant, but the PivotTableUpdate event is not raised, if some captions are changed:

If you need an event for any change within your pivot table, use following instead within your worksheet's code module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.PivotTables(1).TableRange2) Is Nothing Then
        MsgBox "Pivot's TableRange2 Changed"
    End If
End Sub


问:
Refreshing a page without constant refreshing
I am currently making a simple clock in and out system for staff. The warehouse has a TV with a list of names on the right of people who have not signed in, and a list of names on the left of those who are signed in. When they clock in on the scanning device downstairs I need the TV/dashboard upstairs to update and move their name onto the appropriate side.

I have made the function that logs the details into the database.  And I know I could use code such:

```<code><meta http-equiv="refresh" content="3;url=thecurrentpagesurl" />
</code>```

And doing that would refresh the page run a function that checks for changes and updates the display accordingly, however I was wondering if there was a way of "listening" for a change without having to spam the server to often. Ideally I want the dashboard to update in real time.

Using meta refresh I can refresh the page use a function to check for db changes and update the html on the dashboard accordingly. Is there a less resource intensive or more efficient way of doing this?

(I'm not a JavaScript expert but I have enough understanding to use some at a basic level).

Edit

This question has asked before and I have looked at the other answers which is why I came to the conclusion about the meta refresh aspect, but what I wanted to know if there was a more efficient way of doing it given my specific set up.

答: I decided to run the refresh at set times, so what I did was use php date function to calculate the time, if the time is between 7-9 (the earliest staff clock in) or 5-7 (the latest anyone clocks out) it will run the meta refresh that way it doesnt check all day while everyones at work singed in. Thanks again ! </p>

Body:
I am currently making a simple clock in and out system for staff. The warehouse has a TV with a list of names on the right of people who have not signed in, and a list of names on the left of those who are signed in. When they clock in on the scanning device downstairs I need the TV/dashboard upstairs to update and move their name onto the appropriate side.

I have made the function that logs the details into the database.  And I know I could use code such:

<meta http-equiv="refresh" content="3;url=thecurrentpagesurl" />

And doing that would refresh the page run a function that checks for changes and updates the display accordingly, however I was wondering if there was a way of "listening" for a change without having to spam the server to often. Ideally I want the dashboard to update in real time.

Using meta refresh I can refresh the page use a function to check for db changes and update the html on the dashboard accordingly. Is there a less resource intensive or more efficient way of doing this?

(I'm not a JavaScript expert but I have enough understanding to use some at a basic level).

Edit

This question has asked before and I have looked at the other answers which is why I came to the conclusion about the meta refresh aspect, but what I wanted to know if there was a more efficient way of doing it given my specific set up.


问:
Ruby two strings in an IF condition
In my rails project I've if statement with string conditions which doesn't work.

```<code>  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end
</code>```

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

答:
Try like this,</p>

```<code>if ['CEO','founder'].include?(shop.details['company_role'])
  'Other'
else
  shop.details['customer_kind']
end
</code>```

Title: Ruby two strings in an IF condition

Body:
In my rails project I've if statement with string conditions which doesn't work.

  if shop.details['company_role'] == 'CEO' || 'founder'
        'Other'
      else
        shop.details['customer_kind']
      end
  end

When I've case with company_role = founder it didn't return me 'Other' but customer_kind

Body:
Try like this,

if ['CEO','founder'].include?(shop.details['company_role'])
  'Other'
else
  shop.details['customer_kind']
end


问:
linux find regex
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

```<code>find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'
</code>```

Bash, Ubuntu

答:
Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

Title: linux find regex

Body:
I'm having trouble using the regex of the find command. Probably something I don't understand about escaping on the command line.

Why are these not the same?

find -regex '.*[1234567890]'
find -regex '.*[[:digit:]]'

Bash, Ubuntu


问:
replace '\n' in javascript
I'm trying to do replace in JavaScript using:

```<code>r = "I\nam\nhere";
s = r.replace("\n"," ");
</code>```

But instead of giving me

I am here

as the value of s,
It returns the same.

Where's the problem??

答:
Just use \\\n to replace it will work.

```<code>r.replace("\\\n"," ");
</code>```

Title: replace '\n' in javascript

Body:
I'm trying to do replace in JavaScript using:

r = "I\nam\nhere";
s = r.replace("\n"," ");

But instead of giving me

I am here

as the value of s,
It returns the same.

Where's the problem??

Body:
Just use \\\n to replace it will work.

r.replace("\\\n"," ");


问:
Check if substring exists in variable
```<code>{% set x%}some string to check{% endset %}
{{ 'to' in x }}
</code>```

will always return 0.

In documentation I couldn't find any similar example.

Solution

```<code>{% if 'to' in x~'' %}
</code>```

答:
If you assign the variable using the classic way instead of the capture mode, the code should works:

So use this:

```<code>{% set x='some string to check'  %}
</code>```

instead of:

```<code>{% set x%}some string to check{% endset %}
</code>```

See an example in this working feed
hope this help

Title: Check if substring exists in variable

Body:
{% set x%}some string to check{% endset %}
{{ 'to' in x }}

will always return 0.

In documentation I couldn't find any similar example.

Solution

{% if 'to' in x~'' %}

Body:
If you assign the variable using the classic way instead of the capture mode, the code should works:

So use this:

{% set x='some string to check'  %}

instead of:

{% set x%}some string to check{% endset %}

See an example in this working feed
hope this help


问:
How to deploy elasticsearch with docker swarm?
I create 3 virtual machine use docker-machine,there are:

```<code>NAME       ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER     ERRORS
cluster    -        virtualbox   Running   tcp://192.168.99.101:2376           v18.09.5
cluster2   -        virtualbox   Running   tcp://192.168.99.102:2376           v18.09.5
master     -        virtualbox   Running   tcp://192.168.99.100:2376           v18.09.5
</code>```

and then I create a docker swarm in master machine:

```<code> docker-machine ssh master "docker swarm init ----advertise-addr 192.168.99.100"
</code>```

and in cluster and cluster2 join master:

```<code>docker-machine ssh cluster "docker swarm join --advertise-addr 192.168.99.101 --token xxxx 192.168.99.100:2377"

docker-machine ssh cluster2 "docker swarm join --advertise-addr 192.168.99.102 --token xxxx 192.168.99.100:2377"
</code>```

the docker node ls info:

```<code>ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
r4a6y9wie4zp3pl4wi4e6wqp8     cluster             Ready               Active                                  18.09.5
sg9gq6s3k6vty7qap7co6eppn     cluster2            Ready               Active                                  18.09.5
xb6telu8cn3bfmume1kcektkt *   master              Ready               Active              Leader              18.09.5
</code>```

there is deploy config swarm.yml:

```<code>version: "3.3"

services:
  elasticsearch:
    image: elasticsearch:7.0.0
    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      - cluster.name=elk
      - network.host=_eth1:ipv4_
      - network.bind_host=_eth1:ipv4_
      - network.publish_host=_eth1:ipv4_
      - discovery.seed_hosts=192.168.99.100,192.168.99.101
      - cluster.initial_master_nodes=192.168.99.100,192.168.99.101
      - bootstrap.memory_lock=false
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    networks:
      - backend
    deploy:
      mode: replicated
      replicas: 3
      #endpoint_mode: dnsrr
      restart_policy:
        condition: none
      resources:
        limits:
          cpus: "1.0"
          memory: "1024M"
        reservations:
          memory: 20M
networks:
  backend:
    # driver: overlay
    # attachable: true
</code>```

i pull elasticsearch image to virtual machie:

```<code>docker-machine ssh master "docker image pull elasticsearch:7.0.0"
docker-machine ssh cluster "docker image pull elasticsearch:7.0.0"
docker-machine ssh cluster2 "docker image pull elasticsearch:7.0.0"
</code>```

before run i run this command fix some elasticearch bootstrap error:

```<code>docker-machine ssh master "sudo sysctl -w vm.max_map_count=262144"
docker-machine ssh cluster "sudo sysctl -w vm.max_map_count=262144"
docker-machine ssh cluster2 "sudo sysctl -w vm.max_map_count=262144"
</code>```

and then i run `docker stack deploy -c swarm.yml es, the elasticsearch cluster cannot work.

```<code>docker-machine ssh master
docker service logs es_elasticsearch -f
</code>```

show:

```<code>es_elasticsearch.1.uh1x0s9qr7mb@cluster    | {"type": "server", "timestamp": "2019-04-25T16:28:47,143+0000", "level": "WARN", "component": "o.e.c.c.ClusterFormationFailureHelper", "cluster.name": "elk", "node.name": "e8dba5562417",  "message": "master not discovered yet, this node has not previously joined a bootstrapped (v7+) cluster, and this node must discover master-eligible nodes [192.168.99.100, 192.168.99.101] to bootstrap a cluster: have discovered []; discovery will continue using [192.168.99.100:9300, 192.168.99.101:9300] from hosts providers and [{e8dba5562417}{Jy3t0AAkSW-jY-IygOCjOQ}{z7MYIf5wTfOhCX1r25wNPg}{10.255.0.46}{10.255.0.46:9300}{ml.machine_memory=1037410304, xpack.installed=true, ml.max_open_jobs=20}] from last-known cluster state; node term 0, last-accepted version 0 in term 0"  }
es_elasticsearch.2.swswlwmle9e9@cluster2    | {"type": "server", "timestamp": "2019-04-25T16:28:47,389+0000", "level": "WARN", "component": "o.e.c.c.ClusterFormationFailureHelper", "cluster.name": "elk", "node.name": "af5d88a04b42",  "message": "master not discovered yet, this node has not previously joined a bootstrapped (v7+) cluster, and this node must discover master-eligible nodes [192.168.99.100, 192.168.99.101] to bootstrap a cluster: have discovered []; discovery will continue using [192.168.99.100:9300, 192.168.99.101:9300] from hosts providers and [{af5d88a04b42}{zhxMeNMAQN2evKDlsA33qA}{fpYPTvJ6STmyqrgxlMkD_w}{10.255.0.47}{10.255.0.47:9300}{ml.machine_memory=1037410304, xpack.installed=true, ml.max_open_jobs=20}] from last-known cluster state; node term 0, last-accepted version 0 in term 0"  }
es_elasticsearch.3.x8ouukovhh80@master    | {"type": "server", "timestamp": "2019-04-25T16:28:48,818+0000", "level": "WARN", "component": "o.e.c.c.ClusterFormationFailureHelper", "cluster.name": "elk", "node.name": "0e7e4d96b31a",  "message": "master not discovered yet, this node has not previously joined a bootstrapped (v7+) cluster, and this node must discover master-eligible nodes [192.168.99.100, 192.168.99.101] to bootstrap a cluster: have discovered []; discovery will continue using [192.168.99.100:9300, 192.168.99.101:9300] from hosts providers and [{0e7e4d96b31a}{Xs9966RjTEWvEbuj4-ySYA}{-eV4lvavSHq6JhoW0qWu6A}{10.255.0.48}{10.255.0.48:9300}{ml.machine_memory=1037410304, xpack.installed=true, ml.max_open_jobs=20}] from last-known cluster state; node term 0, last-accepted version 0 in term 0"  }

</code>```

I guess the cluster formation failed may be due to network configuration error. I don't know how to fix it, I try many times modify the config, fail and fail again.

答:
Trying to manually specify all the specific IP's and bindings is tricky because of the swarm overlaying network.
Instead, simply make your ES nodes discoverable and let Swarm take care of the node discovery and communication. To make them discoverable, we can use a predictable name like the Swarm node hostname.

Try change your environment settings in the swarm.yml file as follows:

    environment:
    - network.host=0.0.0.0
    - discovery.seed_hosts=elasticsearch #Service name, to let Swarm handle discovery
    - cluster.initial_master_nodes=master,cluster,cluster2 #Swarm nodes host names
    - node.name={{.Node.Hostname}} #To create a predictable node name
```

This of course assumes that we already known the swarm hostnames, which you pointed out in the screenshot above. Without knowing these values, we would have no way of having a predictable set of node names to look for. In that case, you could create 1 ES node entry with a particular node name, and then another entry which references the first entry's node name as the cluster.initial_master_nodes.

Body:
I create 3 virtual machine use docker-machine,there are:

NAME       ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER     ERRORS
cluster    -        virtualbox   Running   tcp://192.168.99.101:2376           v18.09.5
cluster2   -        virtualbox   Running   tcp://192.168.99.102:2376           v18.09.5
master     -        virtualbox   Running   tcp://192.168.99.100:2376           v18.09.5

and then I create a docker swarm in master machine:

 docker-machine ssh master "docker swarm init ----advertise-addr 192.168.99.100"

and in cluster and cluster2 join master:

docker-machine ssh cluster "docker swarm join --advertise-addr 192.168.99.101 --token xxxx 192.168.99.100:2377"

docker-machine ssh cluster2 "docker swarm join --advertise-addr 192.168.99.102 --token xxxx 192.168.99.100:2377"

the docker node ls info:

ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS      ENGINE VERSION
r4a6y9wie4zp3pl4wi4e6wqp8     cluster             Ready               Active                                  18.09.5
sg9gq6s3k6vty7qap7co6eppn     cluster2            Ready               Active                                  18.09.5
xb6telu8cn3bfmume1kcektkt *   master              Ready               Active              Leader              18.09.5

there is deploy config swarm.yml:

version: "3.3"

services:
  elasticsearch:
    image: elasticsearch:7.0.0
    ports:
      - "9200:9200"
      - "9300:9300"
    environment:
      - cluster.name=elk
      - network.host=_eth1:ipv4_
      - network.bind_host=_eth1:ipv4_
      - network.publish_host=_eth1:ipv4_
      - discovery.seed_hosts=192.168.99.100,192.168.99.101
      - cluster.initial_master_nodes=192.168.99.100,192.168.99.101
      - bootstrap.memory_lock=false
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    networks:
      - backend
    deploy:
      mode: replicated
      replicas: 3
      #endpoint_mode: dnsrr
      restart_policy:
        condition: none
      resources:
        limits:
          cpus: "1.0"
          memory: "1024M"
        reservations:
          memory: 20M
networks:
  backend:
    # driver: overlay
    # attachable: true

i pull elasticsearch image to virtual machie:

docker-machine ssh master "docker image pull elasticsearch:7.0.0"
docker-machine ssh cluster "docker image pull elasticsearch:7.0.0"
docker-machine ssh cluster2 "docker image pull elasticsearch:7.0.0"

before run i run this command fix some elasticearch bootstrap error:

docker-machine ssh master "sudo sysctl -w vm.max_map_count=262144"
docker-machine ssh cluster "sudo sysctl -w vm.max_map_count=262144"
docker-machine ssh cluster2 "sudo sysctl -w vm.max_map_count=262144"

and then i run `docker stack deploy -c swarm.yml es, the elasticsearch cluster cannot work.

docker-machine ssh master
docker service logs es_elasticsearch -f

show:

es_elasticsearch.1.uh1x0s9qr7mb@cluster    | {"type": "server", "timestamp": "2019-04-25T16:28:47,143+0000", "level": "WARN", "component": "o.e.c.c.ClusterFormationFailureHelper", "cluster.name": "elk", "node.name": "e8dba5562417",  "message": "master not discovered yet, this node has not previously joined a bootstrapped (v7+) cluster, and this node must discover master-eligible nodes [192.168.99.100, 192.168.99.101] to bootstrap a cluster: have discovered []; discovery will continue using [192.168.99.100:9300, 192.168.99.101:9300] from hosts providers and [{e8dba5562417}{Jy3t0AAkSW-jY-IygOCjOQ}{z7MYIf5wTfOhCX1r25wNPg}{10.255.0.46}{10.255.0.46:9300}{ml.machine_memory=1037410304, xpack.installed=true, ml.max_open_jobs=20}] from last-known cluster state; node term 0, last-accepted version 0 in term 0"  }
es_elasticsearch.2.swswlwmle9e9@cluster2    | {"type": "server", "timestamp": "2019-04-25T16:28:47,389+0000", "level": "WARN", "component": "o.e.c.c.ClusterFormationFailureHelper", "cluster.name": "elk", "node.name": "af5d88a04b42",  "message": "master not discovered yet, this node has not previously joined a bootstrapped (v7+) cluster, and this node must discover master-eligible nodes [192.168.99.100, 192.168.99.101] to bootstrap a cluster: have discovered []; discovery will continue using [192.168.99.100:9300, 192.168.99.101:9300] from hosts providers and [{af5d88a04b42}{zhxMeNMAQN2evKDlsA33qA}{fpYPTvJ6STmyqrgxlMkD_w}{10.255.0.47}{10.255.0.47:9300}{ml.machine_memory=1037410304, xpack.installed=true, ml.max_open_jobs=20}] from last-known cluster state; node term 0, last-accepted version 0 in term 0"  }
es_elasticsearch.3.x8ouukovhh80@master    | {"type": "server", "timestamp": "2019-04-25T16:28:48,818+0000", "level": "WARN", "component": "o.e.c.c.ClusterFormationFailureHelper", "cluster.name": "elk", "node.name": "0e7e4d96b31a",  "message": "master not discovered yet, this node has not previously joined a bootstrapped (v7+) cluster, and this node must discover master-eligible nodes [192.168.99.100, 192.168.99.101] to bootstrap a cluster: have discovered []; discovery will continue using [192.168.99.100:9300, 192.168.99.101:9300] from hosts providers and [{0e7e4d96b31a}{Xs9966RjTEWvEbuj4-ySYA}{-eV4lvavSHq6JhoW0qWu6A}{10.255.0.48}{10.255.0.48:9300}{ml.machine_memory=1037410304, xpack.installed=true, ml.max_open_jobs=20}] from last-known cluster state; node term 0, last-accepted version 0 in term 0"  }

I guess the cluster formation failed may be due to network configuration error. I don't know how to fix it, I try many times modify the config, fail and fail again.

Body:
Trying to manually specify all the specific IP's and bindings is tricky because of the swarm overlaying network.
Instead, simply make your ES nodes discoverable and let Swarm take care of the node discovery and communication. To make them discoverable, we can use a predictable name like the Swarm node hostname.

Try change your environment settings in the swarm.yml file as follows:

    environment:
    - network.host=0.0.0.0
    - discovery.seed_hosts=elasticsearch #Service name, to let Swarm handle discovery
    - cluster.initial_master_nodes=master,cluster,cluster2 #Swarm nodes host names
    - node.name={{.Node.Hostname}} #To create a predictable node name

This of course assumes that we already known the swarm hostnames, which you pointed out in the screenshot above. Without knowing these values, we would have no way of having a predictable set of node names to look for. In that case, you could create 1 ES node entry with a particular node name, and then another entry which references the first entry's node name as the cluster.initial_master_nodes.


问:
Merging two multidimensional arrays in Javascript by value
I have two arrays:

```<code>var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]
</code>```

I need to merge them by email so the resulting array will look like, without duplicate email:

```<code>var mergedarray =
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]
</code>```

My brain hurts looking at those multimultidimensions..Any advice?

答:
Create a Map of array2 for faster search and use Array.prototype.map on first array or vice-versa.

var array1 = [['email1', 'object1'], ['email2', 'object2'], ['email3', 'object3'], ['email4', 'object4']]
var array2 = [['email1', [['a1', 'b1']]], ['email3', [['a3', 'b3']]], ['email4', [['a4', 'b4'], ['a4a', 'b4a']]]]

let map2 = new Map(array2);

let out = array1.map(([key, val]) => [key, val, map2.get(key) || []]);
console.log(out)```

Body:
I have two arrays:

var array1 = [['email1', object1],['email2', object2],['email3', object3],['email4',object4]]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]

I need to merge them by email so the resulting array will look like, without duplicate email:

var mergedarray =
[['email1', object1, [['a1', 'b1']]],['email2', object2],['email3', object3, ['a3', 'b3']],['email4',object4,[['a4','b4'],['a4a','b4a']]]]

My brain hurts looking at those multimultidimensions..Any advice?


问:
How to overwrite style sheets for embedded Tweets
I am trying to overwrite CSS for embedded Tweets. For example I just tried to change font-size, but it doesn't work.

jsfiddle

css

```<code>twitterwidget, blockquote, .Tweet, blockquote.Tweet, .twitter-tweet, twitterwidget.twitter-tweet, p, blockquote p, blockquote.Tweet p, twitterwidget.twitter-tweet p{
  font-size: 26px !important;
}
</code>```

答:
In case someone else is searching

I have implemented a simple solution in my project recently, you can customize all kinds of styles to have it fit in seamlessly with your website branding. Hope it helps.

```<code> jQuery('.twitter-block').delegate('#twitter-widget-0','DOMSubtreeModified propertychange', function() {
    //function call to override the base twitter styles
    customizeTweetMedia();
});

var customizeTweetMedia = function() {

    overrides font styles and removes the profile picture and media from twitter feed
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-media').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('img.Avatar').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-avatar.Identity-avatar').remove();

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-family', "'Proxima Nova', lato, sans-serif");

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-family', "'Proxima Nova', lato, sans-serif");

    //also call the function on dynamic updates in addition to page load
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-TweetList').bind('DOMSubtreeModified propertychange', function() {
        customizeTweetMedia(this);
    });
}
</code>```

Link to my complete example

Body:
I am trying to overwrite CSS for embedded Tweets. For example I just tried to change font-size, but it doesn't work.

jsfiddle

css

twitterwidget, blockquote, .Tweet, blockquote.Tweet, .twitter-tweet, twitterwidget.twitter-tweet, p, blockquote p, blockquote.Tweet p, twitterwidget.twitter-tweet p{
  font-size: 26px !important;
}

Body:
In case someone else is searching

I have implemented a simple solution in my project recently, you can customize all kinds of styles to have it fit in seamlessly with your website branding. Hope it helps.

 jQuery('.twitter-block').delegate('#twitter-widget-0','DOMSubtreeModified propertychange', function() {
    //function call to override the base twitter styles
    customizeTweetMedia();
});

var customizeTweetMedia = function() {

    overrides font styles and removes the profile picture and media from twitter feed
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-media').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('img.Avatar').css('display', 'none');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-avatar.Identity-avatar').remove();

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-Tweet-text').css('font-family', "'Proxima Nova', lato, sans-serif");

    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-size', '12px');
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('span.TweetAuthor-screenName').css('font-family', "'Proxima Nova', lato, sans-serif");

    //also call the function on dynamic updates in addition to page load
    jQuery('.twitter-block').find('.twitter-timeline').contents().find('.timeline-TweetList').bind('DOMSubtreeModified propertychange', function() {
        customizeTweetMedia(this);
    });
}

Link to my complete example


问:
Pix2pix program terminates after giving Thread warning of Tensorflow
I am trying to run https://github.com/eriklindernoren/Keras-GAN/blob/master/pix2pix/pix2pix.py

```<code>python pix2pix.py
</code>```

Execution terminates giving following message

```<code>Using TensorFlow backend.
WARNING:tensorflow:From C:\Users\kulkarni\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
2019-05-29 14:43:23.767965: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2019-05-29 14:43:23.770965: I tensorflow/core/common_runtime/process_util.cc:71] Creating new thread pool with default inter op setting: 4. Tune using inter_op_parallelism_threads for best performance.
</code>```

Tried following solution given at Why Keras model on "bare" CPU is faster? but no luck.

I am running this on Windows 7 Intel i3 CPU 64-bit machine.

How to do proper settings to get the code running?

答:
It's not throwing any error. So I'm guessing the script isn't finding the training dataset. Try downloading the dataset and try running it again.</p>

```<code>bash download_dataset.sh facades
python pix2pix.py
</code>```

Body:
I am trying to run https://github.com/eriklindernoren/Keras-GAN/blob/master/pix2pix/pix2pix.py

python pix2pix.py

Execution terminates giving following message

Using TensorFlow backend.
WARNING:tensorflow:From C:\Users\kulkarni\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
2019-05-29 14:43:23.767965: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2019-05-29 14:43:23.770965: I tensorflow/core/common_runtime/process_util.cc:71] Creating new thread pool with default inter op setting: 4. Tune using inter_op_parallelism_threads for best performance.

Tried following solution given at Why Keras model on "bare" CPU is faster? but no luck.

I am running this on Windows 7 Intel i3 CPU 64-bit machine.

How to do proper settings to get the code running?

Body:
It's not throwing any error. So I'm guessing the script isn't finding the training dataset. Try downloading the dataset and try running it again.

bash download_dataset.sh facades
python pix2pix.py


答:
You can map over the second array and check if the first element is in any of the arrays in the first array, and then push the second element if that returns true:

var array1 = [['email1', 'object1'],['email2', 'object2'],['email3', 'object3'],['email4','object4']]
var array2 = [['email1',[['a1','b1']]],['email3',[['a3','b3']]], ['email4',[['a4','b4'],['a4a','b4a']]]]

array2.forEach((arr2, i2) => {
  array1.map((arr1, i1) => {
    if (arr1[0] == arr2[0]) {
      array1[i1].push(array2[i2][1])
    }
  })
})

console.log(array1)```

Title: Merging two multidimensional arrays in Javascript by value


问:
How to stop programme from reading if -1 is entered, and calculate average accordingly
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

```<code>int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);
</code>```

答:
The break will simply stop the execution of the innermost loop.
In your case, this is your while loop.

You can convert the while into an if statement and the break will have the intended effects -- it will take you out of the for loop, effectively stopping to read numbers!

I would also restructure your code slightly for clarity, and to make it less messy for edge cases:

for (i=0; i<10; i++) {
    do {
      printf("Enter number %d: ",i+1);
      scanf("%d", &ages[i]);
    } while (ages[i] < -1 || ages[i] > 150);
    if (ages[i] == -1){
        break;
    }
}
```

Body:
I'm a beginner in C, and my task is to:
Write a program that reads in an array of up to 10 integers representing peoples ages in years and calculates and prints the maximum age and the minimum age and the average age. Your program should stop reading when either the 10th number is entered or the user enters -1. If the user enters any other negative number or a value above 150, they should be warned and prompted again for a valid age.

My code can find the maximum and minimum numbers and calculate the average, as well as ensuring the value is between 0 to 150. However I can't get the programme to stop if -1 is entered. My average, minimum, and maximum also just consider that 10 values are entered, so I need help in counting the amount of values entered by the user before (/if) -1 is entered, so they can be accurate.

int ages[10];
int i, j;
double sum=0;

for (i=0; i<10; i++){
    printf("Enter number %d: ",i+1);
    scanf("%d", &ages[i]);
    if (ages[i]<-2 || ages[i]>150){
        printf("Invalid number, enter again: ");
            scanf("%d",&ages[i]);
        while (ages[i]==-1){
            break;
        }
    }
}

for (i=0; i<10; i++){
    sum=sum+ages[i];
}
printf("Average: %f \n", (sum/10));
int min=ages[0];
int max=ages[0];

for (j=0; j<10;j++){
    if (ages[j]>max){
       max=ages[j];
    }
    else if (ages[j]<min){
        min=ages[j];
    }
}
printf("Minimum: %d. Maximum: %d. \n", min, max);


问:
Cordova Facebook plugin: set APP_ID, APP_NAME in config.xml
1. What we want to achieve

Install a pre-configured cordova app using fb cordova plugin ( cordova-plugin-facebook4 - https://github.com/jeduan/cordova-plugin-facebook4 )

2. Problem

The problem derives from the "pre-configured" part.
As a default, the plugin required to being install passing it some configurations like APP_NAME / APP_ID values, as documentation at < https://ionicframework.com/docs/native/facebook > specified.

This is a problem for us because our application creation flow process is based mainly onto the Cordova's configuration config.xml where clearly all plugins are listed.

3. Question

Our need is to be able to pass some configuration directly inside the config.xml file, like for other plugins here below shown:

```<code><plugin name="cordova-plugin-camera" spec="2.4.1">
    <variable name="CAMERA_USAGE_DESCRIPTION" value="Allow the app to use your camera" />
    <variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="Allow the app to access your photos" />
</plugin>
</code>```

In the previous lines, variables for cordova-plugin-camera is the way to configure the plugin.

4. Alternative solutions not adopted

Reading around, some solution required to change plugin.xml file of facebook-plugin.

The problem of this solution is the cost for the forked plugin maintenance.

5. Question-based on 4.

Avoiding to fork plugin for configuration setting purpose, can be HOOKS approach usefull? I mean, can we replace "preference" tag inside plugin.xml at some build / prepare / plugin install time as wrote in the second answer at the following link < Cordova Facebook plugin : missing variables APP_ID, APP_NAME > ?

thanks for reading!!

答:
You can specify the APP_ID and APP_NAME in the config XML as following:-

Under Android Platforms:-

```<code><config-file parent="/resources" target="./res/values/strings.xml">
    <string name="fb_app_id">574355309670137</string>
    <string name="fb_app_name">HUB App</string>
</config-file>
</code>```

And outside the platform and at the bottom(when installed fb plugin) it would be defined as below:-

```<code><plugin name="cordova-plugin-facebook4" spec="^3.1.0">
    <variable name="APP_ID" value="574355309670137" />
    <variable name="APP_NAME" value="HUB App" />
</plugin>
</code>```

Please let me know if you have any questions.

Body:
1. What we want to achieve

Install a pre-configured cordova app using fb cordova plugin ( cordova-plugin-facebook4 - https://github.com/jeduan/cordova-plugin-facebook4 )

2. Problem

The problem derives from the "pre-configured" part.
As a default, the plugin required to being install passing it some configurations like APP_NAME / APP_ID values, as documentation at < https://ionicframework.com/docs/native/facebook > specified.

This is a problem for us because our application creation flow process is based mainly onto the Cordova's configuration config.xml where clearly all plugins are listed.

3. Question

Our need is to be able to pass some configuration directly inside the config.xml file, like for other plugins here below shown:

<plugin name="cordova-plugin-camera" spec="2.4.1">
    <variable name="CAMERA_USAGE_DESCRIPTION" value="Allow the app to use your camera" />
    <variable name="PHOTOLIBRARY_USAGE_DESCRIPTION" value="Allow the app to access your photos" />
</plugin>

In the previous lines, variables for cordova-plugin-camera is the way to configure the plugin.

4. Alternative solutions not adopted

Reading around, some solution required to change plugin.xml file of facebook-plugin.

The problem of this solution is the cost for the forked plugin maintenance.

5. Question-based on 4.

Avoiding to fork plugin for configuration setting purpose, can be HOOKS approach usefull? I mean, can we replace "preference" tag inside plugin.xml at some build / prepare / plugin install time as wrote in the second answer at the following link < Cordova Facebook plugin : missing variables APP_ID, APP_NAME > ?

thanks for reading!!

Body:
You can specify the APP_ID and APP_NAME in the config XML as following:-

Under Android Platforms:-

<config-file parent="/resources" target="./res/values/strings.xml">
    <string name="fb_app_id">574355309670137</string>
    <string name="fb_app_name">HUB App</string>
</config-file>

And outside the platform and at the bottom(when installed fb plugin) it would be defined as below:-

<plugin name="cordova-plugin-facebook4" spec="^3.1.0">
    <variable name="APP_ID" value="574355309670137" />
    <variable name="APP_NAME" value="HUB App" />
</plugin>

Please let me know if you have any questions.


问:
Remove textDecorationLine from nested text
I'm new to React Native and I tried to create a text with an inline text as follows:

```<code><Text style={{textDecorationLine: 'line-through'}}>
    $75.00{'     '}
    <Text style={{textDecorationLine: 'none'}>$50</Text>
</Text>
</code>```

The problem is that it renders

<s>$75.00     $50.00</s>

and not

<s>$75.00</s>     $50.00

I've seen that there's a workaround in html, is there a similar solution for React Native?

Note: I tried to make the strikethrough appear in a code section but this feature seems to not work anymore.

答:
You can write your code in following way</p>

```<code><Text>
      <Text style={{textDecorationLine: 'line-through'}}>$75.00</Text>
      <Text style={{textDecorationLine: 'none'}}>$50</Text>
</Text>
</code>```

Body:
I'm new to React Native and I tried to create a text with an inline text as follows:

<Text style={{textDecorationLine: 'line-through'}}>
    $75.00{'     '}
    <Text style={{textDecorationLine: 'none'}>$50</Text>
</Text>

The problem is that it renders

<s>$75.00     $50.00</s>

and not

<s>$75.00</s>     $50.00

I've seen that there's a workaround in html, is there a similar solution for React Native?

Note: I tried to make the strikethrough appear in a code section but this feature seems to not work anymore.

Body:
You can write your code in following way

<Text>
      <Text style={{textDecorationLine: 'line-through'}}>$75.00</Text>
      <Text style={{textDecorationLine: 'none'}}>$50</Text>
</Text>


答:
In your described environment your current approach is not bad.

Here are some ideas/options on which you can read up and improve your application if needed:

Use Ajax and just refresh the content of your lists. You can combine this with neat animations. But this is still not real-time. This is especially easy when using jQuery or similar libraries.

You could use Ajax with longpolling, This means that the Ajax-Request will be hold open on the server-side until any change is happening (or a possible timeout). When a request got an response just open another ajax request with longpolling and wait for more changes. This is not realtime, but it gets really close to it. In some environments this can stress the server since each open request will occupy resources or block sockets/threads etc.

Another more modern version is to use the Websockets. This is the most complex approach, but the communication is in realtime. The Browser-view and Server are establishing a tcp connection and keeping that open to communicate over it. There are also some good open-source libraries for Websockets.

In your described situation i would go with your current solution and also take look into the first two ideas. They are not that complex and can give the feel of "realtime" updates.

Title: Refreshing a page without constant refreshing

Body:
I am currently making a simple clock in and out system for staff. The warehouse has a TV with a list of names on the right of people who have not signed in, and a list of names on the left of those who are signed in. When they clock in on the scanning device downstairs I need the TV/dashboard upstairs to update and move their name onto the appropriate side.

I have made the function that logs the details into the database.  And I know I could use code such:

<meta http-equiv="refresh" content="3;url=thecurrentpagesurl" />

And doing that would refresh the page run a function that checks for changes and updates the display accordingly, however I was wondering if there was a way of "listening" for a change without having to spam the server to often. Ideally I want the dashboard to update in real time.

Using meta refresh I can refresh the page use a function to check for db changes and update the html on the dashboard accordingly. Is there a less resource intensive or more efficient way of doing this?

(I'm not a JavaScript expert but I have enough understanding to use some at a basic level).

Edit

This question has asked before and I have looked at the other answers which is why I came to the conclusion about the meta refresh aspect, but what I wanted to know if there was a more efficient way of doing it given my specific set up.


问:
Get build result of a Azure DevOps build using Rest API
I am trying to get the result of a Azure DevOps build i.e Succeeded / Failed via the REST API, so that I can use the result to queue the next build or not.

I have used the below powershell script to get the build details. But the status only provides the information if the build 'Completed' or not, we do not get the information if the build succeeded or not.

```<code>$Urinew = "https://<Org>/<project>/_apis/build/builds/"
$Uri2 = $Urinew+$buildId+"?api-version=5.0"
$responseFromGet = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri2 -Headers @{Authorization=("Basic {0}" -f $base64authinfo)}
Write-host $responseFromGet
$status = $responseFromGet.status
</code>```

I have tried to use this link to get the build result. Tried to get the build definition too, but that also does not provide the information of the build Result. I tried the logs too, again same issue.
Any help is appreciated.

答: The status is what the current status of the build (in progress, completed etc. ), the result status is in the property result , check your responseFromGet.result.

Body:
I am trying to get the result of a Azure DevOps build i.e Succeeded / Failed via the REST API, so that I can use the result to queue the next build or not.

I have used the below powershell script to get the build details. But the status only provides the information if the build 'Completed' or not, we do not get the information if the build succeeded or not.

$Urinew = "https://<Org>/<project>/_apis/build/builds/"
$Uri2 = $Urinew+$buildId+"?api-version=5.0"
$responseFromGet = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri2 -Headers @{Authorization=("Basic {0}" -f $base64authinfo)}
Write-host $responseFromGet
$status = $responseFromGet.status

I have tried to use this link to get the build result. Tried to get the build definition too, but that also does not provide the information of the build Result. I tried the logs too, again same issue.
Any help is appreciated.


问:
Format csv file with column creation in Spark scala
I have a csv file, as below

It has 6 rows with top row as header, while header read as "Students Marks"
dataframe is treating them as one columns, now i want to separate both columns with data. "student" and "marks" are separated by space.

```<code>df.show()
_______________
##Student Marks##
---------------
A   10;20;10;20
A   20;20;30;10
B   10;10;10;10
B   20;20;20;10
B   30;30;30;20
</code>```

Now i want to transform this csv table into two columns, with student and Marks, Also for every student the marks with add up, something like below

```<code>Student | Marks
A       | 30;40;40;30
B       | 60;60;60;40
</code>```

I have tried with below but it is throwing an error

```<code>df.withColumn("_tmp", split($"Students Marks","\\ ")).select($"_tmp".getItem(0).as("col1"),$"_tmp".getItem(1).as("col2")).drop("_tmp")
</code>```

答:
You can read the csv file with the delimiteryou want and calculate result as below

```<code>    val df = spark.read
      .option("header", true)
      .option("delimiter", " ")
      .csv("path to csv")
</code>```

After You get the dataframe df

```<code>val resultDF = df.withColumn("split", split($"Marks", ";"))
  .withColumn("a", $"split"(0))
  .withColumn("b", $"split"(1))
  .withColumn("c", $"split"(2))
  .withColumn("d", $"split"(3))
  .groupBy("Student")
  .agg(concat_ws(";", array(
     Seq(sum($"a"), sum($"b"), sum($"c"), sum($"d")): _*)
  ).as("Marks"))

resultDF.show(false)
</code>```

Output:

```<code>+-------+-------------------+
|Student|Marks              |
+-------+-------------------+
|B      |60.0;60.0;60.0;40.0|
|A      |30.0;40.0;40.0;30.0|
+-------+-------------------+
</code>```

Body:
I have a csv file, as below

It has 6 rows with top row as header, while header read as "Students Marks"
dataframe is treating them as one columns, now i want to separate both columns with data. "student" and "marks" are separated by space.

df.show()
_______________
##Student Marks##
---------------
A   10;20;10;20
A   20;20;30;10
B   10;10;10;10
B   20;20;20;10
B   30;30;30;20

Now i want to transform this csv table into two columns, with student and Marks, Also for every student the marks with add up, something like below

Student | Marks
A       | 30;40;40;30
B       | 60;60;60;40

I have tried with below but it is throwing an error

df.withColumn("_tmp", split($"Students Marks","\\ ")).select($"_tmp".getItem(0).as("col1"),$"_tmp".getItem(1).as("col2")).drop("_tmp")

Body:
You can read the csv file with the delimiteryou want and calculate result as below

    val df = spark.read
      .option("header", true)
      .option("delimiter", " ")
      .csv("path to csv")

After You get the dataframe df

val resultDF = df.withColumn("split", split($"Marks", ";"))
  .withColumn("a", $"split"(0))
  .withColumn("b", $"split"(1))
  .withColumn("c", $"split"(2))
  .withColumn("d", $"split"(3))
  .groupBy("Student")
  .agg(concat_ws(";", array(
     Seq(sum($"a"), sum($"b"), sum($"c"), sum($"d")): _*)
  ).as("Marks"))

resultDF.show(false)

Output:

+-------+-------------------+
|Student|Marks              |
+-------+-------------------+
|B      |60.0;60.0;60.0;40.0|
|A      |30.0;40.0;40.0;30.0|
+-------+-------------------+


问:
Scraping with Python?
I'd like to grab all the index words and its definitions from here. Is it possible to scrape web content with Python?

Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'.

```<code>http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&arid=14179&sphra=undefined
</code>```

what are the modules used? Is there any tutorial available?

I do not know how many words indexed in the dictionary. I`m absolute beginner in the programming.

答:
You can get data from the web using the built-in urllib or urllib2, but the parsing itself is the most important part. May I suggest the wonderful BeautifulSoup? It can deal with just about anything.
http://www.crummy.com/software/BeautifulSoup/

The documentation is built like a tutorial. Sorta:
http://www.crummy.com/software/BeautifulSoup/documentation.html

In your case, you probably need to use wildcards to see all entries in the dictionary. You can do something like this:

```<code>import urllib2

def getArticles(query, start_index, count):
    xml = urllib2.urlopen('http://pali.hum.ku.dk/cgi-bin/cpd/pali?' +
                          'acti=xsea&tsearch=%s&rfield=entr&recf=%d&recc=%d' %
                          (query, start_index, count))

    # TODO:
    # parse xml code here (using BeautifulSoup or an xml parser like Python's
    # own xml.etree. We should at least have the name and ID for each article.
    # article = (article_name, article_id)

    return (article_names # a list of parsed names from XML

def getArticleContent(article):
    xml = urllib2.urlopen('http://pali.hum.ku.dk/cgi-bin/cpd/pali?' +
                          'acti=xart&arid=%d&sphra=undefined' % article_id)

    # TODO: parse xml
    return parsed_article
</code>```

Now you can loop over things. For instance, to get all articles starting in 'ana', use the wildcard 'ana*', and loop until you get no results:

```<code>query = 'ana*'
article_dict = {}
i = 0
while (true):
    new_articles = getArticles(query, i, 100)
    if len(new_articles) == 0:
        break

    i += 100
    for article_name, article_id in new_articles:
        article_dict[article_name] = getArticleContent(article_id)
</code>```

Once done, you'll have a dictionary of the content of all articles, referenced by names. I omitted the parsing itself, but it's quite simple in this case, since everything is XML. You might not even need to use BeautifulSoup (even though it's still handy and easy to use for XML).

A word of warning though:
You should check the site's usage policy (and maybe robots.txt) before trying to heavily scrap articles. If you're just getting a few articles for yourself they may not care (the dictionary copyright owner, if it's not public domain, may care though), but if you're going to scrape the entire dictionary, this is going to be some heavy usage.

Title: Scraping with Python?

Body:
I'd like to grab all the index words and its definitions from here. Is it possible to scrape web content with Python?

Firebug exploration shows the following URL returns my desirable contents including both index and its definition as to 'a'.

http://pali.hum.ku.dk/cgi-bin/cpd/pali?acti=xart&arid=14179&sphra=undefined

what are the modules used? Is there any tutorial available?

I do not know how many words indexed in the dictionary. I`m absolute beginner in the programming.

Body:
You can get data from the web using the built-in urllib or urllib2, but the parsing itself is the most important part. May I suggest the wonderful BeautifulSoup? It can deal with just about anything.
http://www.crummy.com/software/BeautifulSoup/

The documentation is built like a tutorial. Sorta:
http://www.crummy.com/software/BeautifulSoup/documentation.html

In your case, you probably need to use wildcards to see all entries in the dictionary. You can do something like this:

import urllib2

def getArticles(query, start_index, count):
    xml = urllib2.urlopen('http://pali.hum.ku.dk/cgi-bin/cpd/pali?' +
                          'acti=xsea&tsearch=%s&rfield=entr&recf=%d&recc=%d' %
                          (query, start_index, count))

    # TODO:
    # parse xml code here (using BeautifulSoup or an xml parser like Python's
    # own xml.etree. We should at least have the name and ID for each article.
    # article = (article_name, article_id)

    return (article_names # a list of parsed names from XML

def getArticleContent(article):
    xml = urllib2.urlopen('http://pali.hum.ku.dk/cgi-bin/cpd/pali?' +
                          'acti=xart&arid=%d&sphra=undefined' % article_id)

    # TODO: parse xml
    return parsed_article

Now you can loop over things. For instance, to get all articles starting in 'ana', use the wildcard 'ana*', and loop until you get no results:

query = 'ana*'
article_dict = {}
i = 0
while (true):
    new_articles = getArticles(query, i, 100)
    if len(new_articles) == 0:
        break

    i += 100
    for article_name, article_id in new_articles:
        article_dict[article_name] = getArticleContent(article_id)

Once done, you'll have a dictionary of the content of all articles, referenced by names. I omitted the parsing itself, but it's quite simple in this case, since everything is XML. You might not even need to use BeautifulSoup (even though it's still handy and easy to use for XML).

A word of warning though:
You should check the site's usage policy (and maybe robots.txt) before trying to heavily scrap articles. If you're just getting a few articles for yourself they may not care (the dictionary copyright owner, if it's not public domain, may care though), but if you're going to scrape the entire dictionary, this is going to be some heavy usage.


问:
How to limit the textfield entry to 2 decimal places in swift 4?
I have a textfield and  I want to limit the entry to max 2 decimal places.

number like 12.34 is allowed but not 12.345

How do I do it?

答:
Only Two decimal point allow and only one "." allow</p>

```<code> func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

                    let text: NSString = textField.text! as NSString
                    let resultString = text.replacingCharacters(in: range, with: string)

        //Check the specific textField
         if textField == costTextField {
             let textArray = resultString.components(separatedBy: ".")
             if textArray.count > 2 { //Allow only one "."
                return false
             }
           if textArray.count == 2 {
              let lastString = textArray.last
             if lastString!.count > 2 { //Check number of decimal places
                   return false
               }
            }
          }
           return true
       }
</code>```

Body:
Only Two decimal point allow and only one "." allow

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

                    let text: NSString = textField.text! as NSString
                    let resultString = text.replacingCharacters(in: range, with: string)

        //Check the specific textField
         if textField == costTextField {
             let textArray = resultString.components(separatedBy: ".")
             if textArray.count > 2 { //Allow only one "."
                return false
             }
           if textArray.count == 2 {
              let lastString = textArray.last
             if lastString!.count > 2 { //Check number of decimal places
                   return false
               }
            }
          }
           return true
       }


问:
Highcharts - Adding a point with addPoint stretches time
When you spam click Add Point on the JSFiddle below, you will see that it does not respect the time interval, and instead it stretches the time.

https://jsfiddle.net/ouc2x3ng/1/

I have read this: https://www.highcharts.com/demo/spline-irregular-time, and I can't see what is so special that makes it work.

答:
You need to disable the ordinal property for xAxis, which is enabled in Highstock by default:

```<code>xAxis: {
    ordinal: false
},
</code>```

Live demo: https://jsfiddle.net/BlackLabel/apscbLjn/

API Reference: https://api.highcharts.com/highstock/xAxis.ordinal

Body:
You need to disable the ordinal property for xAxis, which is enabled in Highstock by default:

xAxis: {
    ordinal: false
},

Live demo: https://jsfiddle.net/BlackLabel/apscbLjn/

API Reference: https://api.highcharts.com/highstock/xAxis.ordinal