问:
Help convert .asp to .php
How can I rewrite this from .asp to .php?

```<code><%
' Url of the webpage we want to retrieve
thisURL = "pagerequest.jsp"

' Creation of the xmlHTTP object
Set GetConnection = CreateObject("Microsoft.XMLHTTP")

' Connection to the URL
GetConnection.Open "get", thisURL, False
GetConnection.Send

' ResponsePage now have the response of the remote web server
ResponsePage = GetConnection.responseText

' We write out now the content of the ResponsePage var
Response.ContentType = "text/xml"
Response.write (ResponsePage)

Set GetConnection = Nothing
</code>```

%>

答:
Well, the translated code is (no error checking, just dirt simple functionality):

```<code>$url = 'http://server/pagerequest.jsp';
$text = file_get_contents($url);
header('Content-Type: text/xml');
echo $text;
</code>```

Note that the $url needs to be fully qualified...

EDIT: for a more robust solution:

```<code>function getUrl($url) {
    if (ini_get('allow_url_fopen')) {
        return file_get_contents($url);
    } elseif (function_exists('curl_init')) {
        $c = curl_init($url);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        return curl_exec($c);
    } else {
        $parts = parse_url($url);
        if (!isset($parts['host'])) {
            throw new Exception('You need a host!');
        }
        $port = isset($parts['port']) ? $parts['port'] : 80;
        $f = fsockopen($parts['host'], $port, $errno, $errstr, 30);
        if (!$f) {
            throw new Exception('Error: ['.$errno.'] '.$errstr);
        }
        $out = "GET $url HTTP/1.1\r\n";
        $out .= "Host: {$parts['host']}\r\n";
        $out .= "Connection: close\r\n\r\n";
        fwrite($f, $out);
        $data = '';
        while (!feof($f)) {
            $data .= fgets($f, 128);
        }
        list($headers, $data) = explode("\r\n\r\n", $data, 2);
        // Do some validation on the headers to check for redirect/error
        return $data;
    }
 }
</code>```

Usage:

```<code>$url = 'http://server/pagerequest.jsp';
$text = getUrl($url);
header('Content-Type: text/xml');
echo $text;
</code>```

Title: Help convert .asp to .php

Body:
How can I rewrite this from .asp to .php?

<%
' Url of the webpage we want to retrieve
thisURL = "pagerequest.jsp"

' Creation of the xmlHTTP object
Set GetConnection = CreateObject("Microsoft.XMLHTTP")

' Connection to the URL
GetConnection.Open "get", thisURL, False
GetConnection.Send

' ResponsePage now have the response of the remote web server
ResponsePage = GetConnection.responseText

' We write out now the content of the ResponsePage var
Response.ContentType = "text/xml"
Response.write (ResponsePage)

Set GetConnection = Nothing

%>

Body:
Well, the translated code is (no error checking, just dirt simple functionality):

$url = 'http://server/pagerequest.jsp';
$text = file_get_contents($url);
header('Content-Type: text/xml');
echo $text;

Note that the $url needs to be fully qualified...

EDIT: for a more robust solution:

function getUrl($url) {
    if (ini_get('allow_url_fopen')) {
        return file_get_contents($url);
    } elseif (function_exists('curl_init')) {
        $c = curl_init($url);
        curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
        return curl_exec($c);
    } else {
        $parts = parse_url($url);
        if (!isset($parts['host'])) {
            throw new Exception('You need a host!');
        }
        $port = isset($parts['port']) ? $parts['port'] : 80;
        $f = fsockopen($parts['host'], $port, $errno, $errstr, 30);
        if (!$f) {
            throw new Exception('Error: ['.$errno.'] '.$errstr);
        }
        $out = "GET $url HTTP/1.1\r\n";
        $out .= "Host: {$parts['host']}\r\n";
        $out .= "Connection: close\r\n\r\n";
        fwrite($f, $out);
        $data = '';
        while (!feof($f)) {
            $data .= fgets($f, 128);
        }
        list($headers, $data) = explode("\r\n\r\n", $data, 2);
        // Do some validation on the headers to check for redirect/error
        return $data;
    }
 }

Usage:

$url = 'http://server/pagerequest.jsp';
$text = getUrl($url);
header('Content-Type: text/xml');
echo $text;


来源: stackexchange

问:
Does Css3 keyframe animations start after document is ready loaded?
Does Css3 keyframe animations start after every element in the document is loaded? This is a vital question because it would be a problem if an animation started before the whole page had been properly loaded.</p>

答:
Also when the display property changes from none to visible.
Sample Code

```<code>function showDiv() {
</code>```

document.getElementById("myDiv").style.display="block";
}

ContentLicense: CC BY-SA 3.0

Body:
Also when the display property changes from none to visible.
Sample Code

function showDiv() {

document.getElementById("myDiv").style.display="block";
}


问:
Execute jstack with different user cause Full GC
I start tomcat with tomcat user, and execute jstack with root user. I checked the gc log, find Full GC occur.

I search and find sudo -u tomcat jstack -l <pid> will solve the issue. But why jstack with root user will cause full gc?

Environment:

```<code>[root@bogon ~]# cat /etc/redhat-release
CentOS release 6.8 (Final)
[root@bogon ~]# java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)
[root@bogon ~]# service tomcat version
vagrant: Display Tomcat Version
Using CATALINA_BASE:   /apps/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /apps/tomcat/temp
Using JRE_HOME:        /usr/java/jdk1.8.0_65/
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Server version: Apache Tomcat/8.5.11
Server built:   Jan 10 2017 21:02:52 UTC
Server number:  8.5.11.0
OS Name:        Linux
OS Version:     2.6.32-642.15.1.el6.x86_64
Architecture:   amd64
JVM Version:    1.8.0_65-b17
JVM Vendor:     Oracle Corporation

[root@bogon tomcat]# jstack -l 2644
2644: Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding
</code>```

GC logs

```<code>CommandLine flags: -XX:+DisableExplicitGC -XX:GCLogFileSize=2097152 -XX:+HeapDumpOnOutOfMemoryError -XX:InitialHeapSize=1149239296 -XX:InitiatingHeapOccupancyPercent=45 -XX:+ManagementServer -XX:MaxGCPauseMillis=200 -XX:MaxHeapSize=1149239296 -XX:MaxMetaspaceFreeRatio=80 -XX:MetaspaceSize=100663296 -XX:MinMetaspaceFreeRatio=50 -XX:NumberOfGCLogFiles=10 -XX:+PrintClassHistogram -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseG1GC -XX:+UseGCLogFileRotation -XX:+UseStringDeduplication

2017-07-05T20:13:10.591+0800: 38.999: [Full GC (Heap Inspection Initiated GC)  47M->13M(1096M), 0.0710197 secs]
   [Eden: 48.0M(54.0M)->0.0B(54.0M) Survivors: 0.0B->0.0B Heap: 47.5M(1096.0M)->13.2M(1096.0M)], [Metaspace: 15845K->15845K(1062912K)]
 [Times: user=0.04 sys=0.02, real=0.07 secs]

 num     #instances         #bytes  class name
----------------------------------------------
   1:         27256        5409512  [C
   2:          2889        3734776  [B
   3:            28         935336  [J
   4:         26366         632784  java.lang.String
   5:          4464         392832  java.lang.reflect.Method
   6:          2964         338128  java.lang.Class
   7:          9495         303840  java.util.HashMap$Node
   8:          1566         203296  [I
   9:          2576         167120  [Ljava.lang.Object;
  10:           971         120680  [Ljava.util.HashMap$Node;
  11:          3610         115520  java.util.concurrent.ConcurrentHashMap$Node
  12:          3335          69056  [Ljava.lang.Class;
  13:           924          67912  [Ljava.lang.String;
  14:          1697          67880  java.lang.ref.Finalizer
  15:          1608          64320  java.util.LinkedHashMap$Entry
  16:          1232          59136  java.util.HashMap
  17:           652          52160  java.lang.reflect.Constructor
  18:          3243          51888  java.lang.Object
  19:          1453          46496  java.util.Hashtable$Entry
  20:          1027          41080  java.util.TreeMap$Entry
  21:           711          39816  java.util.zip.ZipFile$ZipFileInputStream
  22:           708          39648  java.util.zip.ZipFile$ZipFileInflaterInputStream
  23:           308          37176  [Ljava.lang.reflect.Method;
  24:           764          36672  org.apache.tomcat.util.modeler.AttributeInfo
  25:            56          31968  [Ljava.util.concurrent.ConcurrentHashMap$Node;
  26:           442          31824  java.lang.reflect.Field
  27:            30          31200  [[C
</code>```

答:
In your case GC is caused by -XX:+PrintClassHistogram option. This flag forces heap inspection accompanied by Full GC in response to SIGQUIT signal.

As you can find from this answer, jstack uses SIGQUIT to initiate communication with the target JVM. The same answer explains why jstack works under tomcat user, but not under root.

In short, SIGQUIT (also known as kill -3) plays two roles: to initiate Dynamic Attach and to dump JVM state. If Dynamic Attach fails, then JVM proceeds with heap inspection, and that in turn causes Full GC, because -XX:+PrintClassHistogram option is on.

Body:
I start tomcat with tomcat user, and execute jstack with root user. I checked the gc log, find Full GC occur.

I search and find sudo -u tomcat jstack -l <pid> will solve the issue. But why jstack with root user will cause full gc?

Environment:

[root@bogon ~]# cat /etc/redhat-release
CentOS release 6.8 (Final)
[root@bogon ~]# java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)
[root@bogon ~]# service tomcat version
vagrant: Display Tomcat Version
Using CATALINA_BASE:   /apps/tomcat
Using CATALINA_HOME:   /usr/local/tomcat
Using CATALINA_TMPDIR: /apps/tomcat/temp
Using JRE_HOME:        /usr/java/jdk1.8.0_65/
Using CLASSPATH:       /usr/local/tomcat/bin/bootstrap.jar:/usr/local/tomcat/bin/tomcat-juli.jar
Server version: Apache Tomcat/8.5.11
Server built:   Jan 10 2017 21:02:52 UTC
Server number:  8.5.11.0
OS Name:        Linux
OS Version:     2.6.32-642.15.1.el6.x86_64
Architecture:   amd64
JVM Version:    1.8.0_65-b17
JVM Vendor:     Oracle Corporation

[root@bogon tomcat]# jstack -l 2644
2644: Unable to open socket file: target process not responding or HotSpot VM not loaded
The -F option can be used when the target process is not responding

GC logs

CommandLine flags: -XX:+DisableExplicitGC -XX:GCLogFileSize=2097152 -XX:+HeapDumpOnOutOfMemoryError -XX:InitialHeapSize=1149239296 -XX:InitiatingHeapOccupancyPercent=45 -XX:+ManagementServer -XX:MaxGCPauseMillis=200 -XX:MaxHeapSize=1149239296 -XX:MaxMetaspaceFreeRatio=80 -XX:MetaspaceSize=100663296 -XX:MinMetaspaceFreeRatio=50 -XX:NumberOfGCLogFiles=10 -XX:+PrintClassHistogram -XX:+PrintGC -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseG1GC -XX:+UseGCLogFileRotation -XX:+UseStringDeduplication

2017-07-05T20:13:10.591+0800: 38.999: [Full GC (Heap Inspection Initiated GC)  47M->13M(1096M), 0.0710197 secs]
   [Eden: 48.0M(54.0M)->0.0B(54.0M) Survivors: 0.0B->0.0B Heap: 47.5M(1096.0M)->13.2M(1096.0M)], [Metaspace: 15845K->15845K(1062912K)]
 [Times: user=0.04 sys=0.02, real=0.07 secs]

 num     #instances         #bytes  class name
----------------------------------------------
   1:         27256        5409512  [C
   2:          2889        3734776  [B
   3:            28         935336  [J
   4:         26366         632784  java.lang.String
   5:          4464         392832  java.lang.reflect.Method
   6:          2964         338128  java.lang.Class
   7:          9495         303840  java.util.HashMap$Node
   8:          1566         203296  [I
   9:          2576         167120  [Ljava.lang.Object;
  10:           971         120680  [Ljava.util.HashMap$Node;
  11:          3610         115520  java.util.concurrent.ConcurrentHashMap$Node
  12:          3335          69056  [Ljava.lang.Class;
  13:           924          67912  [Ljava.lang.String;
  14:          1697          67880  java.lang.ref.Finalizer
  15:          1608          64320  java.util.LinkedHashMap$Entry
  16:          1232          59136  java.util.HashMap
  17:           652          52160  java.lang.reflect.Constructor
  18:          3243          51888  java.lang.Object
  19:          1453          46496  java.util.Hashtable$Entry
  20:          1027          41080  java.util.TreeMap$Entry
  21:           711          39816  java.util.zip.ZipFile$ZipFileInputStream
  22:           708          39648  java.util.zip.ZipFile$ZipFileInflaterInputStream
  23:           308          37176  [Ljava.lang.reflect.Method;
  24:           764          36672  org.apache.tomcat.util.modeler.AttributeInfo
  25:            56          31968  [Ljava.util.concurrent.ConcurrentHashMap$Node;
  26:           442          31824  java.lang.reflect.Field
  27:            30          31200  [[C


问:
Is there any reason not to use std::make_shared when constructing objects?
I can't think of any situation where

```<code>std::shared_ptr<Object> obj(new Object("foo", 1));
</code>```

would be preferred to

```<code>auto obj = std::make_shared<Object>("foo", 1);
</code>```

The latter always results in better locality and reduces memory fragmentation. Is there any situation, where you would prefer (or be forced) to use the first form, except interfacing with code returning raw pointers?

答: Modern IDEs have "Find usages" feature. If you use std::make_shared to construct the object, when you search for the places where the constructor of that object is called, IDE won't show up the places where std::make_shared is used.

Body:
I can't think of any situation where

std::shared_ptr<Object> obj(new Object("foo", 1));

would be preferred to

auto obj = std::make_shared<Object>("foo", 1);

The latter always results in better locality and reduces memory fragmentation. Is there any situation, where you would prefer (or be forced) to use the first form, except interfacing with code returning raw pointers?


问:
Make an arrow shape using CSS including text
I need to make an arrow shape including text. I have seen many shapes and arrows on stack overflow but failed to find out this kind of shape. Can anyone help me please?

答:
You can get it by using pseudo elements like before and after

I posted and working example below.

.box {
  width: 200px;
  height: 50px;
  background: tomato;
  text-align: center;
  color: #fff;
  font-size: 13px;
  position: relative;
  display: table;
}

.box span {
  display: table-cell;
  vertical-align: middle;
}

.box:before,
.box:after {
  content: '';
  position: absolute;
}

.box:after {
  border-left: 25px solid tomato;
  border-right: 25px solid transparent;
  border-top: 25px solid transparent;
  border-bottom: 25px solid transparent;
  right: -50px;
  top: 0px;
  width: 0;
  height: 0;
  display: block;
}

.box:before {
  border-left: 26px solid white;
  border-right: 26px solid transparent;
  border-top: 26px solid transparent;
  border-bottom: 26px solid transparent;
  left: 0px;
  top: -1px;
  width: 0;
  height: 0;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <span>Hello</span>
</div></code>```

Body:
You can get it by using pseudo elements like before and after

I posted and working example below.

.box {
  width: 200px;
  height: 50px;
  background: tomato;
  text-align: center;
  color: #fff;
  font-size: 13px;
  position: relative;
  display: table;
}

.box span {
  display: table-cell;
  vertical-align: middle;
}

.box:before,
.box:after {
  content: '';
  position: absolute;
}

.box:after {
  border-left: 25px solid tomato;
  border-right: 25px solid transparent;
  border-top: 25px solid transparent;
  border-bottom: 25px solid transparent;
  right: -50px;
  top: 0px;
  width: 0;
  height: 0;
  display: block;
}

.box:before {
  border-left: 26px solid white;
  border-right: 26px solid transparent;
  border-top: 26px solid transparent;
  border-bottom: 26px solid transparent;
  left: 0px;
  top: -1px;
  width: 0;
  height: 0;
  display: block;
}

<div class="box">
  <span>Hello</span>
</div>


问:
Why it doesn't read in the question marks?
This program runs perfectly, except when I use questiom mars in the input like: what is this??????

It should count the duplicates in a string, and print out the highest number of how many times it was repeated in a row. Any other character is okay (#,*...), But in this case it gives back the numeber: 1. Which is wrong since there are 6 question marks. That's why I suspect there is something wrong between nextLine() function and "?" or Char class and "?". But I can't find the answer anywhere.

```<code>import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

        Scanner scan = new Scanner(System.in);

        String kell = scan.nextLine();
        char [] sor = kell.toCharArray();
        int max = kell.length();
        scan.close();
        int rész = 1;
        int vég = 1;
        boolean egyezett = false;

        for(int i=0; i<max-1; i++)
        {
            if (sor[i]== sor[i+1]){
                rész++;
                egyezett = true;
            }else{
                if (egyezett){
                    if (rész>vég){
                        vég= rész;
                        egyezett = false;
                        rész = 1;
                    } else{
                        egyezett = false;
                        rész = 1;
                    }
                }
            }
        }
        System.out.println(vég);
    }
}
</code>```

答: This doesn't have to do with question marks in particular, but rather the fact that the duplicates occur thru the end of the string. sor[i]== sor[i+1] is always going to be true, resz is always increased, but veg never has a chance of getting assigned resz's value.

Body:
This program runs perfectly, except when I use questiom mars in the input like: what is this??????

It should count the duplicates in a string, and print out the highest number of how many times it was repeated in a row. Any other character is okay (#,*...), But in this case it gives back the numeber: 1. Which is wrong since there are 6 question marks. That's why I suspect there is something wrong between nextLine() function and "?" or Char class and "?". But I can't find the answer anywhere.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

        Scanner scan = new Scanner(System.in);

        String kell = scan.nextLine();
        char [] sor = kell.toCharArray();
        int max = kell.length();
        scan.close();
        int rész = 1;
        int vég = 1;
        boolean egyezett = false;

        for(int i=0; i<max-1; i++)
        {
            if (sor[i]== sor[i+1]){
                rész++;
                egyezett = true;
            }else{
                if (egyezett){
                    if (rész>vég){
                        vég= rész;
                        egyezett = false;
                        rész = 1;
                    } else{
                        egyezett = false;
                        rész = 1;
                    }
                }
            }
        }
        System.out.println(vég);
    }
}


问:
How to delete the canvas from Tkinter after shown the window
I want to create a line in the Tkinter and after changing the height I need to delete the previous line and create a new line with the new height, this is a repeated process.

To this, I read the tutorial of the Tkinter of python and I think the After method might be useful. So, I write my idea but it is not a good method and I cannot create it. Also, I searched about a Shown event in the Tkinter, but I did not find the Shown event in the Tkinter for the window.

Here is my suggested code:

```<code>from tkinter import *
from tkinter import messagebox
import numpy as np
import random
window = Tk()
window.geometry("600x400+650+200")
window.resizable(0, 0)
window.title("Ball Balancing Game - QLearning")

canvas = Canvas()

def uptodate():
    canvas.delete(line1)
    line1 = canvas.create_line(100, 200, 500, h)

# for i in range(len(h) - 1):
#     for j in range(len(h) - 1):
#
#         line1 = canvas.create_line(100, h[i], 500, h[j])
#         line2 = canvas.create_line(100, h[i+1], 500, h[j+1])
#         # lines = canvas.create_line(0,0,600,400)
#         # balls = canvas.create_oval(200, 150, 230, 110, outline="gray", fill="gray", width=6)
#         canvas.pack(fill=BOTH, expand=1)
#         canvas.delete(line1)
#         window.update()
#         window.after()
#         canvas.delete(lines)
#         canvas.update()
#         lines.destroy()
#         i = w.create_line(xy, fill="red")

line = canvas.create_line(100, 200, 500, 200)
canvas.pack(fill=BOTH, expand=1)
window.after(1000, uptodate())
window.mainloop()
</code>```

答:
As Bryan mentioned, you can modify an item on your canvas using the itemconfig or coords methods (see Change the attributes of a tkinter canvas object)

Then, to create an animation loop with the after method, you need to let the animation function call itself multiple times.

Example:

```<code>import tkinter as tk
import numpy as np

window = tk.Tk()

canvas = tk.Canvas(window, width=120, height=100)
canvas.pack(fill="both", expand=1)
line1 = canvas.create_line(30, 50, 100, 50, fill="red", width=2)
count = 0

def update():
    """ This function updates the line coordinates and calls itself 62 times """
    global count
    count += 1
    canvas.coords(line1, 30, 50, 100, 50 + 30*np.sin(count/5))
    if count <= 62:
        window.after(100, update)

# Start the animation
update()

# Launch the app
window.mainloop()
</code>```

Body:
I want to create a line in the Tkinter and after changing the height I need to delete the previous line and create a new line with the new height, this is a repeated process.

To this, I read the tutorial of the Tkinter of python and I think the After method might be useful. So, I write my idea but it is not a good method and I cannot create it. Also, I searched about a Shown event in the Tkinter, but I did not find the Shown event in the Tkinter for the window.

Here is my suggested code:

from tkinter import *
from tkinter import messagebox
import numpy as np
import random
window = Tk()
window.geometry("600x400+650+200")
window.resizable(0, 0)
window.title("Ball Balancing Game - QLearning")

canvas = Canvas()

def uptodate():
    canvas.delete(line1)
    line1 = canvas.create_line(100, 200, 500, h)

# for i in range(len(h) - 1):
#     for j in range(len(h) - 1):
#
#         line1 = canvas.create_line(100, h[i], 500, h[j])
#         line2 = canvas.create_line(100, h[i+1], 500, h[j+1])
#         # lines = canvas.create_line(0,0,600,400)
#         # balls = canvas.create_oval(200, 150, 230, 110, outline="gray", fill="gray", width=6)
#         canvas.pack(fill=BOTH, expand=1)
#         canvas.delete(line1)
#         window.update()
#         window.after()
#         canvas.delete(lines)
#         canvas.update()
#         lines.destroy()
#         i = w.create_line(xy, fill="red")

line = canvas.create_line(100, 200, 500, 200)
canvas.pack(fill=BOTH, expand=1)
window.after(1000, uptodate())
window.mainloop()

Body:
As Bryan mentioned, you can modify an item on your canvas using the itemconfig or coords methods (see Change the attributes of a tkinter canvas object)

Then, to create an animation loop with the after method, you need to let the animation function call itself multiple times.

Example:

import tkinter as tk
import numpy as np

window = tk.Tk()

canvas = tk.Canvas(window, width=120, height=100)
canvas.pack(fill="both", expand=1)
line1 = canvas.create_line(30, 50, 100, 50, fill="red", width=2)
count = 0

def update():
    """ This function updates the line coordinates and calls itself 62 times """
    global count
    count += 1
    canvas.coords(line1, 30, 50, 100, 50 + 30*np.sin(count/5))
    if count <= 62:
        window.after(100, update)

# Start the animation
update()

# Launch the app
window.mainloop()


问:
Parsing decrypted encrypted_data in Telegram
I am trying to implement receiving/sending messages via Secret chat in Telegram (~something like own client), but encountered some problems while interpreting decrypted data. I've read the schema, but can't match it with my data.

To be more concrete: I received a message (sent from the official client) with word "Test12", the decoded result (in hex) was:

3C0000008917E31B0FF1C770B657C36AF705BDACA4BE2C0B2E0000000100000062000000DE91B0360000000038507C7CD5FA6F7C00 00000006 546573743132 00

We can find here the whole message starting from 57 byte (bold), and (if I'm not mistaken) the length (italic). But how can I match other bytes? It is said in schema that message should start from 8 (salt) + 8 (session_id) + 8 (message_id) + 4 (seq_no) + 4 (message_data_length) = 32 byte, not from 57 byte.

Moreover when I try to send longer message (more than ~256 bytes), the "message text" is starting from 60 byte and length is also encoded a little bit strange: FE000400 for 1024-byte message and FE000200 for 512-bytes (what does FE mean?).

So, can anyone please give me a schema or a clue of what I'm doing wrong?

答:
Ok, it seems that I managed to decode most of the message. May be it would be useful for some one:

3C000000 Number of "valuable" bytes (not including padding with random bytes at the end if they are needed)

8917E31B (== 467867529), code of decryptedMessageLayer (layer 17)

0FF1C770B657C36AF705BDACA4BE2C0B serialized random bytes array (should consist of minimum of 15 bytes), OF = 15 - current quantity

2E000000 seems to be the number of a minimum layer

01000000 in_seq_no, (1 - 1) / 2 = 0 messages received, see Sequence numbers

62000000 out_seq_no, 62 / 2 = 49 messages sended, see Sequence numbers (message sender didn't start that chat)

DE91B036 code of decryptedMessage#36b091de

00000000 don't know

38507C7CD5FA6F7C seems to be randomId (may be should be the same as the message is transferred with?)

00000000 don't really know, may be it is ttl

0654657374313200 serialized string: first two bytes (06) mean length. If there are more than 254, DE(=254) is placed instead and length can be found from next 3 bytes (starting from 60 position in my 'mentioned' case). String bytes follow than (mean Test12) and are padded with 0-3 null bytes (00).

After that the result is padded with random bytes (0-15) to make full 16-byted block.


问:
ajax and json_encode() form validation error
I am able to display success and fail messages if the form has validation errors or not but I am not sure how to get the errors to display one under each other in this php code:

```<code>$errors = array();
    $response = array();

    if(empty($_POST['name'])) {

        $errors['name'] = "Name required";
    }

    if(empty($_POST['email'])) {

        $errors['email'] = "Email required";
    }

    $response['errors'] = $errors;

    if($errors) {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $reponse['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";
    }

    echo json_encode($response);
</code>```

The line I need to change is probably:

```<code>$response['message'] = "Fail";
</code>```

答:
Have you tried to add the error message as you detect it

    $errors = array();
        $response = array();

```<code>    if(empty($_POST['name'])) {

        $errors['name'] = "Name required";
       response['message'] = "<div class='alert alert-danger'>Name Required</div>";
    }

    if(empty($_POST['email'])) {

  $errors['email'] = "Email required";
 response['message'] = "<div class='alert alert-danger'>Email Required</div>";
    }

    $response['errors'] = $errors;

    if($errors) {

        $response['success'] = false;
       // $response['message'] = "Fail"; we added the message during the error detection

    } else {

        $response['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";
    }

    echo json_encode($response);
</code>```

Body:
I am able to display success and fail messages if the form has validation errors or not but I am not sure how to get the errors to display one under each other in this php code:

$errors = array();
    $response = array();

    if(empty($_POST['name'])) {

        $errors['name'] = "Name required";
    }

    if(empty($_POST['email'])) {

        $errors['email'] = "Email required";
    }

    $response['errors'] = $errors;

    if($errors) {

        $response['success'] = false;
        $response['message'] = "Fail";

    } else {

        $reponse['success'] = true;
        $response['message'] = "
Article added
";
    }

    echo json_encode($response);

The line I need to change is probably:

$response['message'] = "Fail";

Body:
Have you tried to add the error message as you detect it

    $errors = array();
        $response = array();

    if(empty($_POST['name'])) {

        $errors['name'] = "Name required";
       response['message'] = "<div class='alert alert-danger'>Name Required</div>";
    }

    if(empty($_POST['email'])) {

  $errors['email'] = "Email required";
 response['message'] = "<div class='alert alert-danger'>Email Required</div>";
    }

    $response['errors'] = $errors;

    if($errors) {

        $response['success'] = false;
       // $response['message'] = "Fail"; we added the message during the error detection

    } else {

        $response['success'] = true;
        $response['message'] = "<div class='alert alert-success'>Article added</div>";
    }

    echo json_encode($response);


问:
SQL - all patients who had only dental visits in 2010
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

```<code>AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )
</code>```

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)

答:
```<code>AND pv.PatientVisitId IN (
  SELECT MAX(pv1.PatientVisitID)
  FROM PatientVisit pv1
    JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
    JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
    JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
  WHERE pv1.PatientProfileID = pp.PatientProfileID
    AND pv1.Visit < '2011-01-01'
  HAVING SUM(CASE WHEN df1.ListName LIKE '%Dental%' THEN 1 ELSE 0 END) = COUNT(*)
)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)


问:
How to draw polygon/ convex hull around Partitioned Around Medoids (PAM) clusters in R?
Good Day

Is it possible to produce a plot based on the output of a PAM dissimilarity clustering analysis with polygons drawn around the outer point of the clusters?

I have currently achieved something similar using the function clusplot however am more interested in seeing the clusters demarcated using straight lines.

```<code># Installing packages
library(cluster)
library(fpc)
library(ggplot2)
library(ggfortify)

#Importing Koeberg matrix into R
KoebergAllCSV <- read.csv("C:/R/Koeberg Cluster/KoebergAllCSV.csv", row.names=1, sep=";")

#Checking if data is in the correct format/Checking class/mode of each column
sapply(KoebergAllCSV, mode)
sapply(KoebergAllCSV, class)

#Creating gower dissimilarity matrix using function "daisy"
#specifying variable type(numerics all ratioscaled and log transformed)
#and weighting all columns as 1

Koeberg.Diss = daisy(KoebergAllCSV, metric = "gower", type = list(logratio = c("Mass", "EF")), weights = rep.int(1,5))

attributes(Koeberg.Diss)

#Determine k
pamk(Koeberg.Diss, krange=2:50, criterion="asw", usepam=TRUE, scaling=FALSE, diss=TRUE, critout=FALSE)

#Run cluster analysis using PAM (Partitioning around medoids)

pam_fit= pam(Koeberg.Diss, diss = TRUE, k = 28)

#Export cluster info
KoebergClusInfo = paste("KoebergClusInfo", ".txt")
write.table(pam_fit$clustering, file = KoebergClusInfo, sep=",")

## Default S3 method:
clusplot(Koeberg.Diss, pam_fit$clustering, diss = TRUE,
         stand = FALSE,
         lines = 0, labels= 4, xlim = c(-1,1), plotchar = TRUE, span = TRUE,
         shade = TRUE, color = TRUE, col.p = "black",
         main = "Koeberg gower/pam Clusterplot",
         verbose = getOption("verbose"))
</code>```

I am aware that the function autoplot in ggplot2 accepts objects of class pam however when attempting to use it for my data and replacing the above clusplot function with

```<code>autoplot(pam(pam_fit), frame = TRUE)
</code>```

or

autoplot(pam(Koeberg.Diss, diss = TRUE, k = 28), frame = TRUE)

I get the following errors...

Error in pam(pam_fit) : x is not a numeric dataframe or matrix.

and

Error in as.data.frame.default(x[[i]], optional = TRUE,
  stringsAsFactors = stringsAsFactors) :  cannot coerce class ""waiver""
  to a data.frame Respectively...

I am relatively new to R and posting questions in these forums, so any help would be massively appreciated.

Edit: Got it to work using the fviz_cluster() in the factoextra package

```<code>    # Installing packages
    library(cluster)
    library(fpc)
    library(factoextra)

    #Importing Koeberg matrix into R
    KoebergAllCSV <- read.csv("C:/R/Koeberg Cluster/KoebergAllCSV.csv",
    row.names=1, sep=";")

    #creating gower dissimilarity matrix using daisy
    Koeberg.Gower = as.matrix(daisy(KoebergAllCSV, metric = "gower", type =
    list(logratio = c("Mass", "EF"))))

    attributes(Koeberg.Gower)

    pamk(Koeberg.Gower, krange=2:50, criterion="asw", usepam=TRUE,
    scaling=FALSE, diss=TRUE, critout=FALSE)

    Koeberg.Pam = pam(Koeberg.Gower, 28, diss = TRUE, keep.diss = TRUE)

    fviz_cluster(object = list(data=Koeberg.Gower, cluster =
    Koeberg.Pam$clustering), geom = c("point", "text"), ellipse.type =
    "convex", stand = FALSE)

    fviz_silhouette(silhouette(Koeberg.Pam))
</code>```

Body:
Good Day

Is it possible to produce a plot based on the output of a PAM dissimilarity clustering analysis with polygons drawn around the outer point of the clusters?

I have currently achieved something similar using the function clusplot however am more interested in seeing the clusters demarcated using straight lines.

# Installing packages
library(cluster)
library(fpc)
library(ggplot2)
library(ggfortify)

#Importing Koeberg matrix into R
KoebergAllCSV <- read.csv("C:/R/Koeberg Cluster/KoebergAllCSV.csv", row.names=1, sep=";")

#Checking if data is in the correct format/Checking class/mode of each column
sapply(KoebergAllCSV, mode)
sapply(KoebergAllCSV, class)

#Creating gower dissimilarity matrix using function "daisy"
#specifying variable type(numerics all ratioscaled and log transformed)
#and weighting all columns as 1

Koeberg.Diss = daisy(KoebergAllCSV, metric = "gower", type = list(logratio = c("Mass", "EF")), weights = rep.int(1,5))

attributes(Koeberg.Diss)

#Determine k
pamk(Koeberg.Diss, krange=2:50, criterion="asw", usepam=TRUE, scaling=FALSE, diss=TRUE, critout=FALSE)

#Run cluster analysis using PAM (Partitioning around medoids)

pam_fit= pam(Koeberg.Diss, diss = TRUE, k = 28)

#Export cluster info
KoebergClusInfo = paste("KoebergClusInfo", ".txt")
write.table(pam_fit$clustering, file = KoebergClusInfo, sep=",")

## Default S3 method:
clusplot(Koeberg.Diss, pam_fit$clustering, diss = TRUE,
         stand = FALSE,
         lines = 0, labels= 4, xlim = c(-1,1), plotchar = TRUE, span = TRUE,
         shade = TRUE, color = TRUE, col.p = "black",
         main = "Koeberg gower/pam Clusterplot",
         verbose = getOption("verbose"))

I am aware that the function autoplot in ggplot2 accepts objects of class pam however when attempting to use it for my data and replacing the above clusplot function with

autoplot(pam(pam_fit), frame = TRUE)

or

autoplot(pam(Koeberg.Diss, diss = TRUE, k = 28), frame = TRUE)

I get the following errors...

Error in pam(pam_fit) : x is not a numeric dataframe or matrix.

and

Error in as.data.frame.default(x[[i]], optional = TRUE,
  stringsAsFactors = stringsAsFactors) :  cannot coerce class ""waiver""
  to a data.frame Respectively...

I am relatively new to R and posting questions in these forums, so any help would be massively appreciated.

Edit: Got it to work using the fviz_cluster() in the factoextra package

    # Installing packages
    library(cluster)
    library(fpc)
    library(factoextra)

    #Importing Koeberg matrix into R
    KoebergAllCSV <- read.csv("C:/R/Koeberg Cluster/KoebergAllCSV.csv",
    row.names=1, sep=";")

    #creating gower dissimilarity matrix using daisy
    Koeberg.Gower = as.matrix(daisy(KoebergAllCSV, metric = "gower", type =
    list(logratio = c("Mass", "EF"))))

    attributes(Koeberg.Gower)

    pamk(Koeberg.Gower, krange=2:50, criterion="asw", usepam=TRUE,
    scaling=FALSE, diss=TRUE, critout=FALSE)

    Koeberg.Pam = pam(Koeberg.Gower, 28, diss = TRUE, keep.diss = TRUE)

    fviz_cluster(object = list(data=Koeberg.Gower, cluster =
    Koeberg.Pam$clustering), geom = c("point", "text"), ellipse.type =
    "convex", stand = FALSE)

    fviz_silhouette(silhouette(Koeberg.Pam))

Body:
# Installing packages
library(cluster)
library(fpc)
library(factoextra)

#Importing Koeberg matrix into R
KoebergAllCSV <- read.csv("C:/R/Koeberg Cluster/KoebergAllCSV.csv",
row.names=1, sep=";")

#creating gower dissimilarity matrix using daisy
Koeberg.Gower = as.matrix(daisy(KoebergAllCSV, metric = "gower", type =
list(logratio = c("Mass", "EF"))))

attributes(Koeberg.Gower)

pamk(Koeberg.Gower, krange=2:50, criterion="asw", usepam=TRUE,
scaling=FALSE, diss=TRUE, critout=FALSE)

Koeberg.Pam = pam(Koeberg.Gower, 28, diss = TRUE, keep.diss = TRUE)

fviz_cluster(object = list(data=Koeberg.Gower, cluster =
Koeberg.Pam$clustering), geom = c("point", "text"), ellipse.type =
"convex", stand = FALSE)

fviz_silhouette(silhouette(Koeberg.Pam))

Data used:

"KoebergAllCSV"

structure(list(Mass = c(157000, 775, 197, 15000, 3250, 628, 1815,
2070, 2000, 1218, 614, 536, 379, 235, 800, 672, 1960, 768, 1540,
1790, 3500, 7450, 4030, 2200, 830, 1180, 1310, 955, 590, 1168,
820, 790, 5000, 883, 824, 280, 184, 941, 293, 1250, 3900, 1700,
925, 220, 1040, 510, 690, 600, 539, 1018, 122, 1086, 118, 737,
370, 1236, 5820, 229, 226, 220, 305.5, 94.5, 390, 198, 445, 623,
1100, 377, 340, 418, 326, 202, 139, 47, 35.1, 46.1, 580, 1150,
66, 44, 50, 30, 34.2, 30, 91, 71, 59, 78.9, 110, 405, 19.5, 73,
64, 39, 54, 39, 37, 48, 21.2, 26.3, 24.2, 29, 15.2, 35, 16.1,
16.8, 29.7, 12.5, 55, 612, 630, 865, 22.4, 8.6, 47.3, 32.5, 28.8,
17.3, 38, 23.5, 22, 15.5, 18.1, 34, 23, 13.1, 13, 14.7, 19.1,
14, 18.6, 15.5, 37, 14.5, 24.6, 25, 28.5, 50.8, 52, 68.8, 76.1,
100, 85, 158, 113, 88, 25.6, 13, 10.2, 30.5, 38, 55, 45.5, 30,
52, 11, 17.8, 29, 13, 23.2, 38, 21, 25, 27.3, 427, 1572, 78.9,
15, 61, 212.9, 700, 11.1, 44, 29.6, 124, 3200, 5800, 5300, 950,
62.4, 205, 270, 93, 40.2, 102, 240, 90, 33, 16.6, 39.2, 47, 60.8,
13, 20.8, 8, 11, 165000, 180000, 63600, 11400, 21200, 41000,
11300, 840000, 240000, 320000, 900, 4090, 1250, 19000, 19000,
6400, 2610, 47, 4500, 1258, 238, 55, 113, 9990, 5360, 17800,
110.1973216, 238.1629085, 89.33169378, 245.0708356, 83.49190575,
7.323754897, 17.91558243, 2.259871723, 1.992123644, 78.63046291,
235.6804221, 413.5582987, 486.5966599, 7.418054089, 8.4510848,
8.4510848, 42.83324573, 8.4510848, 3.14445177, 2000, 496.2334891,
119.4158615, 805.4349144, 8.212468482, 25.0905618), Diet = structure(c(4L,
2L, 2L, 6L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 5L, 4L, 5L, 5L, 5L, 5L, 2L, 5L, 5L, 5L, 5L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L,
5L, 5L, 5L, 2L, 2L, 2L, 5L, 1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
1L, 1L, 2L, 2L, 4L, 5L, 5L, 5L, 6L, 5L, 3L, 1L, 1L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 5L, 5L, 5L, 2L, 2L, 2L, 3L, 3L, 5L, 3L, 3L, 5L,
5L, 5L, 5L, 3L, 3L, 5L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 3L,
3L, 5L, 5L, 2L, 2L, 2L, 3L, 2L, 3L, 3L, 5L, 5L, 3L, 3L, 3L, 3L,
3L, 5L, 5L, 2L, 3L, 3L, 2L, 3L, 3L, 1L, 2L, 1L, 2L, 5L, 2L, 5L,
3L, 3L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 2L, 2L, 3L, 5L, 1L, 1L, 1L, 5L, 5L, 2L, 2L, 1L,
1L, 1L, 5L, 2L, 3L, 2L, 2L, 2L, 5L, 2L, 5L, 3L, 5L, 5L, 3L, 3L,
5L, 3L, 3L, 4L, 6L, 6L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L,
4L, 1L, 1L, 1L, 3L, 4L, 4L, 4L, 5L, 6L, 1L, 1L, 1L, 1L, 6L, 1L,
1L, 1L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L,
4L, 1L, 1L, 1L, 3L, 3L), .Label = c("A", "B", "C", "D", "E",
"F"), class = "factor"), Time = structure(c(3L, 3L, 3L, 3L, 3L,
3L, 3L, 1L, 1L, 2L, 3L, 3L, 3L, 1L, 4L, 3L, 3L, 3L, 3L, 3L, 3L,
1L, 2L, 1L, 3L, 3L, 4L, 2L, 3L, 1L, 3L, 2L, 3L, 2L, 3L, 3L, 1L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L,
3L, 1L, 3L, 3L, 3L, 1L, 3L, 1L, 3L, 1L, 1L, 1L, 4L, 3L, 3L, 1L,
3L, 3L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 1L, 3L, 3L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 3L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 4L, 1L, 4L, 4L,
1L, 4L, 1L, 3L, 1L, 4L, 1L, 1L, 1L, 4L, 4L, 1L, 4L, 4L, 3L, 3L,
4L, 4L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
1L, 3L), .Label = c("Cat", "Cr", "Di", "No"), class = "factor"),
    Space = structure(c(5L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 5L, 2L,
    2L, 2L, 5L, 2L, 2L, 2L, 5L, 2L, 5L, 2L, 2L, 5L, 5L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 5L, 1L, 1L, 1L, 5L, 1L, 1L, 1L,
    3L, 1L, 1L, 1L, 1L, 3L, 1L, 1L, 5L, 5L, 5L, 5L, 2L, 2L, 2L,
    2L, 5L, 5L, 4L, 2L, 2L, 2L, 2L, 2L, 5L, 5L, 2L, 2L, 2L, 5L,
    5L, 5L, 5L, 5L, 3L, 3L, 1L, 1L, 3L, 1L, 1L, 1L, 1L, 1L, 1L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 5L, 3L, 3L, 3L, 3L, 5L, 5L, 5L,
    1L, 1L, 5L, 1L, 1L, 1L, 1L, 1L, 1L, 5L, 5L, 1L, 3L, 3L, 3L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 5L, 5L, 5L, 1L,
    3L, 5L, 5L, 3L, 3L, 5L, 5L, 5L, 5L, 3L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 5L, 5L, 2L, 5L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 2L,
    2L, 1L, 1L, 5L, 5L, 2L, 2L, 5L, 2L, 1L, 5L, 3L, 5L, 1L, 3L,
    5L, 5L, 5L, 1L, 3L, 3L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 4L, 5L, 4L, 5L, 5L, 5L, 5L,
    5L, 5L, 5L, 5L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 4L,
    5L, 4L, 4L, 5L, 5L, 5L, 5L, 3L, 5L, 5L, 4L, 5L), .Label = c("Ae",
    "Aq", "Ar", "Fo", "Te"), class = "factor"), EF = c(36274.12643,
    974.5491757, 383.4606456, 15194.1663, 4179.125464, 1043.599331,
    1739.739739, 1902.677158, 1858.620513, 1325.913225, 831.6334703,
    758.1419376, 598.7459669, 432.4008244, 995.8492032, 1104.982804,
    1833.224631, 968.5460848, 1555.574839, 2526.177199, 2720.81891,
    4551.218864, 2995.035921, 1983.25768, 1021.131045, 1297.600326,
    1393.320578, 1123.496167, 809.3558665, 1288.599252, 1012.736663,
    987.3550419, 3468.868783, 1065.095472, 1016.098313, 487.1962293,
    366.0414243, 1112.253632, 502.488525, 1349.53769, 2928.89833,
    1663.891544, 1099.339465, 413.4082553, 1190.663398, 732.8997761,
    900.420823, 818.6726853, 354.4240516, 652.168291, 85.2606497,
    693.8895747, 270.483605, 941.7478954, 589.026282, 1339.226017,
    3846.819879, 533.5361702, 528.1460593, 517.3161179, 666.1149499,
    269.8814521, 803.9152978, 477.0047921, 889.8724349, 1153.045225,
    1786.335023, 783.201274, 723.3180648, 640.0447608, 540.3690726,
    390.0619447, 302.4004117, 144.5066856, 118.4522857, 142.6164524,
    799.9885345, 1275.042111, 182.0952927, 543.7188737, 634.8358004,
    341.8068213, 400.635478, 341.8068213, 1311.800923, 191.3798609,
    168.7094925, 205.6358063, 257.8562828, 626.4208001, 79.37849663,
    195.0348258, 178.3190991, 127.263627, 158.8361858, 127.263627,
    122.7819915, 144.6363257, 82.97394225, 96.07341942, 90.78786186,
    102.6748266, 66.17393783, 116.6808568, 68.813704, 70.83430724,
    104.3536694, 57.93381766, 158.6645733, 816.6280747, 832.8847551,
    1033.247332, 86.13942963, 44.9254345, 143.1986471, 110.9466069,
    102.1927841, 72.26112014, 123.3917674, 88.99374555, 85.0904386,
    67.05928121, 74.51689843, 114.4034188, 87.7017517, 59.81055334,
    59.49970587, 64.68582581, 77.29226408, 62.57493448, 75.91055058,
    67.05928121, 121.1742978, 64.08606129, 91.80560821, 92.81807245,
    101.4677065, 150.3213487, 152.7269268, 184.7538415, 197.8677001,
    238.2502359, 213.3232585, 325.1772534, 258.896799, 218.4145451,
    94.32710718, 59.49970587, 50.45235653, 106.2569217, 123.3917674,
    158.6645733, 139.4700925, 105.0692888, 152.7269268, 53.11049696,
    73.67479581, 102.6748266, 59.49970587, 88.21961721, 123.3917674,
    82.44084978, 92.81807245, 98.54258242, 649.397604, 1577.514936,
    202.7896107, 65.58060147, 170.2384385, 404.275036, 909.2871722,
    53.43834074, 136.3267745, 104.1146163, 265.4017335, 2559.743414,
    3837.812585, 3609.284914, 1119.48705, 196.0571475, 393.9976926,
    605.6763891, 266.5768403, 139.7476799, 286.2283703, 438.6449711,
    224.9201933, 112.1044413, 70.25978867, 126.0282381, 142.5804177,
    169.8586911, 59.49970587, 81.90613014, 42.76953519, 53.11049696,
    44893.11086, 48012.29543, 21505.57155, 5704.435068, 9209.019243,
    15323.26221, 5665.766265, 157697.8254, 59952.20689, 74861.38869,
    616.5285774, 2297.756619, 820.2217331, 23289.68486, 8728.776034,
    3390.680499, 1555.167143, 82.25108625, 2783.313695, 2329.752262,
    567.6985933, 163.9110073, 301.8499294, 4992.739194, 2906.435392,
    8247.673366, 12.81581191, 25.42711978, 10.63408241, 26.08172622,
    10.0137771, 1.178076499, 2.549050089, 0.353356528, 0.31350088,
    9.49371787, 25.19136319, 41.52955076, 47.98985328, 1.091673606,
    1.235456699, 1.235456699, 5.76431571, 1.235456699, 0.483456886,
    112.0018952, 48.83385255, 13.76461928, 75.11335195, 1.274157763,
    3.438909954)), .Names = c("Mass", "Diet", "Time", "Space",
"EF"), class = "data.frame", row.names = c("CommonOstrich", "GreatCrestedGrebe",
"LittleGrebe", "GreatWhitePelican", "White-breastedCormorant",
"ReedCormorant", "AfricanDarter", "GreyHeron", "Black-headedHeron",
"PurpleHeron", "LittleEgret", "Yellow-billedEgret", "CattleEgret",
"Green-backedHeron", "Black-crownedNight-Heron", "HamerkopHamerkop",
"AfricanSacredIbis", "GlossyIbis", "HadedaIbis", "AfricanSpoonbill",
"GreaterFlamingo", "Spur-wingedGoose", "EgyptianGoose", "SouthAfricanShelduck",
"CapeShoveler", "AfricanBlackDuck", "Yellow-billedDuck", "Red-billedTeal",
"CapeTeal", "SouthernPochard", "MaccoaDuck", "White-backedDuck",
"Secretarybird", "PeregrineFalcon", "LannerFalcon", "RockKestrel",
"LesserKestrel", "Yellow-billedKite", "Black-shoulderedKite",
"BootedEagle", "AfricanFish-eagle", "JackalBuzzard", "SteppeBuzzard",
"Rufous-chestedSparrowhawk", "BlackSparrowhawk", "AfricanGoshawk",
"AfricanMarsh-harrier", "BlackHarrier", "Grey-wingedFrancolin",
"CapeSpurfowl", "CommonQuail", "HelmetedGuineafowl", "BlackCrake",
"AfricanPurpleSwamphen", "CommonMoorhen", "Red-knobbedCoot",
"BlueCrane", "CrownedLapwing", "BlacksmithLapwing", "RuffRuff",
"CommonGreenshank", "WoodSandpiper", "PiedAvocet", "Black-wingedStilt",
"WaterThick-knee", "SpottedThick-knee", "KelpGull", "Grey-headedGull",
"Hartlaub'sGull", "SpeckledPigeon", "Red-eyedDove", "CapeTurtle-dove",
"LaughingDove", "NamaquaDove", "Klaas'sCuckoo", "DiderickCuckoo",
"BarnOwl", "SpottedEagle-owl", "Fiery-neckedNightjar", "CommonSwift",
"AfricanBlackSwift", "White-rumpedSwift", "HorusSwift", "LittleSwift",
"AlpineSwift", "SpeckledMousebird", "White-backedMousebird",
"Red-facedMousebird", "PiedKingfisher", "GiantKingfisher", "MalachiteKingfisher",
"EuropeanBee-eater", "AfricanHoopoe", "AcaciaPiedBarbet", "GreaterHoneyguide",
"LesserHoneyguide", "CardinalWoodpecker", "Large-billedLark",
"Grey-backedSparrowlark", "Red-cappedLark", "BarnSwallow", "White-throatedSwallow",
"Pearl-breastedSwallow", "GreaterStripedSwallow", "RockMartin",
"Brown-throatedMartin", "BandedMartin", "Black(Southernrace)Saw-wing",
"Fork-tailedDrongo", "PiedCrow", "CapeCrow", "White-neckedRaven",
"GreyTit", "CapePenduline-tit", "CapeBulbul", "CappedWheatear",
"FamiliarChat", "AfricanStonechat", "CapeRobin-chat", "KarooScrub-robin",
"LesserSwamp-warbler", "AfricanReed-warbler", "LittleRush-warbler",
"CapeGrassbird", "Long-billedCrombec", "Bar-throatedApalis",
"CloudCisticola", "Grey-backedCisticola", "Levaillant'sCisticola",
"AfricanDuskyFlycatcher", "Chestnut-ventedTit-babbler", "Layard'sTit-babbler",
"FiscalFlycatcher", "CapeBatis", "AfricanParadise-flycatcher",
"CapeWagtail", "AfricanPipit", "CapeLongclaw", "Common(Southern)Fiscal",
"SouthernBoubou", "Bokmakierie", "CommonStarling", "WattledStarling",
"Red-wingedStarling", "PiedStarling", "CapeSugarbird", "MalachiteSunbird",
"Orange-breastedSunbird", "SouthernDouble-collaredSunbird", "HouseSparrow",
"CapeSparrow", "CapeWeaver", "SouthernMasked-weaver", "SouthernRedBishop",
"YellowBishop", "CommonWaxbill", "Pin-tailedWhydah", "CapeCanary",
"Black-headedCanary", "BrimstoneCanary", "White-throatedCanary",
"YellowCanary", "Streaky-headedSeedeater", "CapeBunting", "RockDove",
"MallardDuck", "OliveThrush", "CapeWhite-eye", "CapeLong-billedLark",
"Burchell'sCoucal", "SouthernBlackKorhaan", "KarooPrinia", "CapeClapperLark",
"SouthernGrey-headedSparrow", "LittleBittern", "BlackStork",
"Verreaux'sEagle", "MartialEagle", "AfricanHarrier-Hawk", "BlackrumpedButtonquail",
"AfricanRail", "AfricanJacana", "CommonSandpiper", "LittleStint",
"White-wingedTern", "NamaquaSandgrouse", "Red-chestedCuckoo",
"KarooLark", "SandMartin", "SombreGreenbul", "MountainChat",
"Ant-eatingChat", "ZittingCisticola", "SpottedFlycatcher", "FairyFlycatcher",
"DuskySunbird", "RedHartebeest", "BlueWildebeest", "Bontebok",
"CapeGrysbok", "CommonDuiker", "Springbok", "Steenbok", "CommonEland",
"Gemsbok", "PlainsZebra", "YellowMongoose", "LargeGreyMongoose",
"SmallGreyMongoose", "CapePorcupine", "Caracal", "AfricanWildCat",
"Small-spottedGenet", "CapeGoldenMole", "ScrubHare", "CapeDuneMole-Rat",
"VleiRat", "FourStripedGrassMouse", "CapeGerbil", "Black-BackedJackal",
"Bat-earedFox", "AfricanClawlessOtter", "HeraldSnake", "RhombicEgg-eater",
"SpottedHarlequinSnake", "OliveHouseSnake", "SpottedHouseSnake",
"Knox'sDesertLizard", "NamaquaDwarfChameleon", "Austen'sThick-toedGecko",
"OcelatedThick-toedGecko", "CrossedWhipSnake", "CapeWhipSnake",
"Spotted/RhombicSkaapsteker", "MoleSnake", "Short-leggedseps",
"SilveryDwarfBurrowingSkink", "BloubergDwarfBurrowingSkink",
"CapeSkink", "Red-SidedSkink", "VariegatedSkink", "AngulateTortoise",
"Boomslang", "KarooWhipSnake", "CapeCobra", "Delalande'sBeakedBlindSnake",
"CapeGirdledLizard"))


问:
DateTimeFormatter doesn't parse custom date format
I have an issue with java DataTimeFormmater.
I feel that I missed something but cannot figure out what exactly.

```<code>String format = "yyyy-MM-dd'T'HH:mm:ss[.S]'T'zxxx";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

String date = "2017-07-05T12:28:36.4TGMT+03:00";

System.out.println(formatter.format(ZonedDateTime.now()));
System.out.println(formatter.parse(date));
</code>```

The code above produces string of the current ZonedDateTime and attempts to parse date time string with the same date formatter.
Result that it successfully produces 2017-07-05T06:07:51.0TCDT-05:00 but fails to parse 2017-07-05T12:28:36.4TGMT+03:00

My goal is to parse 2017-07-05T12:28:36.4TGMT+03:00 and come up with appropriate DateTimeFormatter.

答:
tl;dr

```<code>OffsetDateTime.parse(
    "2017-07-05T12:28:36.4TGMT+03:00".replace( "TGMT" , "" )
)
</code>```

Details

Your format is bizarre, like a strange misunderstanding or corruption of the standard ISO 8601 formats.

If all your inputs have “TGMT" in the last part, strip that out to comply with ISO 8601.

The java.time classes use standard formats by default when parsing/generating strings. So no need to define a formatting pattern.

```<code>OffsetDateTime odt = OffsetDateTime.parse( "2017-07-05T12:28:36.4TGMT+03:00".replace( "TGMT" , "" ) ) ;
</code>```

And never use the 3-4 letter pseudo-timezones like CMT, EST, and IST. These are not actual time zones, not standardized, and not even unique(!). Real time zone names are in the format of continent/region such as America/Montreal or Pacific/Auckland.

Body:
I have an issue with java DataTimeFormmater.
I feel that I missed something but cannot figure out what exactly.

String format = "yyyy-MM-dd'T'HH:mm:ss[.S]'T'zxxx";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);

String date = "2017-07-05T12:28:36.4TGMT+03:00";

System.out.println(formatter.format(ZonedDateTime.now()));
System.out.println(formatter.parse(date));

The code above produces string of the current ZonedDateTime and attempts to parse date time string with the same date formatter.
Result that it successfully produces 2017-07-05T06:07:51.0TCDT-05:00 but fails to parse 2017-07-05T12:28:36.4TGMT+03:00

My goal is to parse 2017-07-05T12:28:36.4TGMT+03:00 and come up with appropriate DateTimeFormatter.

Body:
tl;dr

OffsetDateTime.parse(
    "2017-07-05T12:28:36.4TGMT+03:00".replace( "TGMT" , "" )
)

Details

Your format is bizarre, like a strange misunderstanding or corruption of the standard ISO 8601 formats.

If all your inputs have “TGMT" in the last part, strip that out to comply with ISO 8601.

The java.time classes use standard formats by default when parsing/generating strings. So no need to define a formatting pattern.

OffsetDateTime odt = OffsetDateTime.parse( "2017-07-05T12:28:36.4TGMT+03:00".replace( "TGMT" , "" ) ) ;

And never use the 3-4 letter pseudo-timezones like CMT, EST, and IST. These are not actual time zones, not standardized, and not even unique(!). Real time zone names are in the format of continent/region such as America/Montreal or Pacific/Auckland.


问:
Mysql order by parent and child
I want to display a result of query sorted by parent and then the child.
Here's my code

```<code>SELECT * FROM
mst_category AS parent
LEFT JOIN mst_category AS child
ON child.category_parent = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_group, COALESCE(parent.category_parent, parent.category_id), parent.category_parent != 0, child.category_id
</code>```

The result of the query :

As you can see some of the children are not sorted by parent id. My question is how to sort it ?

答:
Simplify your order by clause to just what you want the sort order to be:

```<code>SELECT
    parent.category_id as `parent_id`,
    parent.category_group as `parent_group`,
    child.category_id as `child_id`
    child.category_group as `child_group`
FROM mst_category AS parent
LEFT JOIN mst_category AS child
    ON child.category_parent = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_group, child.category_group
</code>```

For 3 levels:

```<code>SELECT
    parent.category_id as `parent_id`,
    parent.category_group as `parent_group`,
    child.category_id as `child_id`
    child.category_group as `child_group`,
    child2.category_id as `child2_id`
    child2.category_group as `child2_group`
FROM mst_category AS parent
LEFT JOIN mst_category AS child
    ON child.category_parent = parent.category_id
LEFT JOIN mst_category AS child2
    ON child2.category_parent = child.category_id
WHERE parent.category_id = 0
GROUP BY parent.category_id, child.category_id, child2_category_id
ORDER BY parent.category_group, child.category_group, child2.category_group
</code>```

Title: Mysql order by parent and child

Body:
I want to display a result of query sorted by parent and then the child.
Here's my code

SELECT * FROM
mst_category AS parent
LEFT JOIN mst_category AS child
ON child.category_parent = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_group, COALESCE(parent.category_parent, parent.category_id), parent.category_parent != 0, child.category_id

The result of the query :

As you can see some of the children are not sorted by parent id. My question is how to sort it ?

Body:
Simplify your order by clause to just what you want the sort order to be:

SELECT
    parent.category_id as `parent_id`,
    parent.category_group as `parent_group`,
    child.category_id as `child_id`
    child.category_group as `child_group`
FROM mst_category AS parent
LEFT JOIN mst_category AS child
    ON child.category_parent = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_group, child.category_group

For 3 levels:

SELECT
    parent.category_id as `parent_id`,
    parent.category_group as `parent_group`,
    child.category_id as `child_id`
    child.category_group as `child_group`,
    child2.category_id as `child2_id`
    child2.category_group as `child2_group`
FROM mst_category AS parent
LEFT JOIN mst_category AS child
    ON child.category_parent = parent.category_id
LEFT JOIN mst_category AS child2
    ON child2.category_parent = child.category_id
WHERE parent.category_id = 0
GROUP BY parent.category_id, child.category_id, child2_category_id
ORDER BY parent.category_group, child.category_group, child2.category_group


问:
How to achieve security level 3 in FIWARE?
I am deploying FIWARE security GEs (i.e., Wilma, AuthzForce, Keyrock) in my computer. Security level 2 (Basic Authorization) is working well, but now I need security level 3 (Advanced Authorization) using XACML.

Long story short, I want a tutorial of implementation security level 3. However, as far as I know, any tutorial or document about security level 3 does not exist.

For now, I create my policy with PAP's API, and change 'custom_policy' option in config.js from 'undefined' to 'policy.js'. And then I create 'policy.js' file into 'PEP/policies', but don't change anything compared with its template file because I don't know what this code does exactly. I think I should make XACML Request form using 'xml' variable. But in my case, PEP gives me the error when I make the XACML Request using 'xml' variable, and return this variable. Here is my error of PEP:

```<code>Error: Root - Error in AZF communication <?xml version="1.0" encoding="UTF-8" standalone="yes"?><error xmlns="http://authzforce.github.io/rest-api-model/xmlns/authz/S" xmlns:ns2="http://www.w3.org/2005/Atom" xmlns:ns3="http://authzforce.github.io/core/xmlns/pdp/5.0" xmlns:ns4="http://authzforce.github.io/pap-dao-flat-file/xmlns/properties/3.6"><message>Invalid parameters: cvc-elt.1: Cannot find the declaration of element 'Request'.</message></error>
</code>```

And here is my 'getPolicy' code (XACML Request) in policy.js. I just made very simple request whether response is permit or not because I'm not sure what I'm doing at that time.:

```<code>exports.getPolicy = function (roles, req, app_id) {
    var xml = xmlBuilder.create('Request', {
            'xmlns': 'urn:oasis:names:tc:xacml:3.0:core:schema:wd-17',
            'CombinedDecision': 'false',
            'ReturnPolicyIdList': 'false'})
    .ele('Attributes', {
            'Category': 'urn:oasis:names:tc:xacml:1.0:subject-category:access-subject'});
</code>```

So, anyone can give me any information about implementation of security level 3?

答:
The error you are getting is really

Invalid parameters: cvc-elt.1: Cannot find the declaration of element
  'Request'.

This is a simple XML validation issue. You need to make sure that the XACML request you send contains the right namespace declaration.

You'll see there is another question on this topic here.

Can you paste your XACML request so we can tell whether it is valid?

Body:
I am deploying FIWARE security GEs (i.e., Wilma, AuthzForce, Keyrock) in my computer. Security level 2 (Basic Authorization) is working well, but now I need security level 3 (Advanced Authorization) using XACML.

Long story short, I want a tutorial of implementation security level 3. However, as far as I know, any tutorial or document about security level 3 does not exist.

For now, I create my policy with PAP's API, and change 'custom_policy' option in config.js from 'undefined' to 'policy.js'. And then I create 'policy.js' file into 'PEP/policies', but don't change anything compared with its template file because I don't know what this code does exactly. I think I should make XACML Request form using 'xml' variable. But in my case, PEP gives me the error when I make the XACML Request using 'xml' variable, and return this variable. Here is my error of PEP:

Error: Root - Error in AZF communication <?xml version="1.0" encoding="UTF-8" standalone="yes"?><error xmlns="http://authzforce.github.io/rest-api-model/xmlns/authz/S" xmlns:ns2="http://www.w3.org/2005/Atom" xmlns:ns3="http://authzforce.github.io/core/xmlns/pdp/5.0" xmlns:ns4="http://authzforce.github.io/pap-dao-flat-file/xmlns/properties/3.6"><message>Invalid parameters: cvc-elt.1: Cannot find the declaration of element 'Request'.</message></error>

And here is my 'getPolicy' code (XACML Request) in policy.js. I just made very simple request whether response is permit or not because I'm not sure what I'm doing at that time.:

exports.getPolicy = function (roles, req, app_id) {
    var xml = xmlBuilder.create('Request', {
            'xmlns': 'urn:oasis:names:tc:xacml:3.0:core:schema:wd-17',
            'CombinedDecision': 'false',
            'ReturnPolicyIdList': 'false'})
    .ele('Attributes', {
            'Category': 'urn:oasis:names:tc:xacml:1.0:subject-category:access-subject'});

So, anyone can give me any information about implementation of security level 3?


问:
Highlight link if in directory
I have a series of links which currently remain highlighted if on the  current url (using query and css).

My question is, what if I want it to remain highlighted not because of the page but if still within that directory? ie. If I click multi links on the page that is still within that directory for that particular link to remain highlighted. Hope that makes sense.

Jquery:

```<code> <script>
  $(function(){
    $('.section li a').each(function() {
      if ($(this).prop('href') == window.location.href) {
        $(this).addClass('current');
      }
    });
  });
  </script>
</code>```

css

```<code>.section li a.current {
  text-decoration: underline;
}
</code>```

答:
All you need to do is add the "current" class to the parent directory as well. This way, both the line and the parent directory is highlighted. </p>

```<code><script>
  $(function(){
    $('.section li a').each(function() {
      if ($(this).prop('href') == window.location.href) {
        $(this).addClass('current');
        $(this).parent().parent().addClass('current');
      }
    });
  });
</script>
</code>```

Title: Highlight link if in directory

Body:
I have a series of links which currently remain highlighted if on the  current url (using query and css).

My question is, what if I want it to remain highlighted not because of the page but if still within that directory? ie. If I click multi links on the page that is still within that directory for that particular link to remain highlighted. Hope that makes sense.

Jquery:

css

.section li a.current {
  text-decoration: underline;
}

Body:
All you need to do is add the "current" class to the parent directory as well. This way, both the line and the parent directory is highlighted.

<script>
  $(function(){
    $('.section li a').each(function() {
      if ($(this).prop('href') == window.location.href) {
        $(this).addClass('current');
        $(this).parent().parent().addClass('current');
      }
    });
  });
</script>


问:
Can we match an exact string using html pattern attribute only?
Lets get to the problem as I allow open registration on my website(any one can open registration page) but I want only those people able to proceed who have a specific code (like "CDCode"). This is in a form and I want to check it on form Submit.

I know it is possible with onfocusout but javascript can be disabled so not a perfect solution.

I want some solution with pure HTML like with pattern attribute. So anyhow we can make pattern attribute match an exact string?

答:
```<code><input type="text" name="test" pattern="CDCode" >
</code>```


问:
MiniZinc type error for trying to print the result
I'm sketching scheduling of bank swizzles in r600g driver (it's inefficient ATM, I'm figuring out the constraints):

```<code>enum CHANS = {x,y,z,w};
enum REGS = {R1, R2, R3, R4}; % for starters

% args
enum OPERANDS = {src1, src2, src3, src4};
array[OPERANDS] of REGS: Regs = [R1, R2, R1, R3];
array[OPERANDS] of CHANS: Chans = [x, x, y, x];
array[OPERANDS] of 1..4: Inst = [1,1,2,2];
array[OPERANDS] of 1..3: Port = [1,2,1,2];

% the rest
array[OPERANDS] of var 1..3: PortOut;
constraint sum(i in PortOut where i = 1)(1) <= 3;
constraint sum(i in PortOut where i = 2)(1) <= 3;
constraint sum(i in PortOut where i = 3)(1) <= 3;

output [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where PortOut[op] == 1]
    ++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where PortOut[op] == 2]
    ++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where PortOut[op] == 3];
solve satisfy;
</code>```

It works with the 3 "output" lines commented out, but otherwise it fails with:

```<code>λ minizinc test.mzn
test.mzn:17:
MiniZinc: type error: invalid type in output item, expected `array[int] opt string'
</code>```

Any ideas?

答:
When you are using decision variables in the output section you (might) have to use fix to use the value of the variable. Here the PortOut[op] need to be fix'ed:

```<code>output [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where fix(PortOut[op]) == 1]
++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where fix(PortOut[op]) == 2]
++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where fix(PortOut[op]) == 3];
</code>```

Body:
I'm sketching scheduling of bank swizzles in r600g driver (it's inefficient ATM, I'm figuring out the constraints):

enum CHANS = {x,y,z,w};
enum REGS = {R1, R2, R3, R4}; % for starters

% args
enum OPERANDS = {src1, src2, src3, src4};
array[OPERANDS] of REGS: Regs = [R1, R2, R1, R3];
array[OPERANDS] of CHANS: Chans = [x, x, y, x];
array[OPERANDS] of 1..4: Inst = [1,1,2,2];
array[OPERANDS] of 1..3: Port = [1,2,1,2];

% the rest
array[OPERANDS] of var 1..3: PortOut;
constraint sum(i in PortOut where i = 1)(1) <= 3;
constraint sum(i in PortOut where i = 2)(1) <= 3;
constraint sum(i in PortOut where i = 3)(1) <= 3;

output [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where PortOut[op] == 1]
    ++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where PortOut[op] == 2]
    ++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where PortOut[op] == 3];
solve satisfy;

It works with the 3 "output" lines commented out, but otherwise it fails with:

λ minizinc test.mzn
test.mzn:17:
MiniZinc: type error: invalid type in output item, expected `array[int] opt string'

Any ideas?

Body:
When you are using decision variables in the output section you (might) have to use fix to use the value of the variable. Here the PortOut[op] need to be fix'ed:

output [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where fix(PortOut[op]) == 1]
++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where fix(PortOut[op]) == 2]
++ [show(Regs[op]) ++ "." ++ show(Chans[op]) ++ " " | op in OPERANDS where fix(PortOut[op]) == 3];


问:
Netsuite search filter for list of items
I am trying to add a filter in the search condition.

The problem I am facing is that while I am using the internalid and the int 1111 it works fine. But if i replace with some other column with string it does not work. It throws error in cust search line.
Can anyone suggest ?

```<code>        var custSearch = search.create({
        type : record.Type.CUSTOMER,
        columns : searchColumn,
        filters: [
                 'email', 'ANYOF', ["abanks@acera.com","3m@3m.com"]]
                 //'internalid', 'ANYOF', ["1397","1251"]] // Works fine

        });
        custSearch.run().each(function(result) { // throw errors
            log.debug("Found !",result);
            return true;
        });
</code>```

答:
Email field is not compatible with ANYOF operator. Try any of the following:

ANY

IS

ISEMPTY

STARTSWITH

CONTAINS

ISNOT

ISNOTEMPTY

DOESNOTSTARTWITH

DOESNOTCONTAIN

If you need to filter by multiple emails then you could use expressions to add "OR"s. I suggest using the Chrome extension Netsuite: Search Export to make things easier.

Body:
I am trying to add a filter in the search condition.

The problem I am facing is that while I am using the internalid and the int 1111 it works fine. But if i replace with some other column with string it does not work. It throws error in cust search line.
Can anyone suggest ?

        var custSearch = search.create({
        type : record.Type.CUSTOMER,
        columns : searchColumn,
        filters: [
                 'email', 'ANYOF', ["abanks@acera.com","3m@3m.com"]]
                 //'internalid', 'ANYOF', ["1397","1251"]] // Works fine

        });
        custSearch.run().each(function(result) { // throw errors
            log.debug("Found !",result);
            return true;
        });


问:
Problem when assigning a pointer to an enum variable in C
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

```<code>//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!
</code>```

答: I'm not sure if this is related exactly to your warning or not, but be very careful assigning references to local variables to pointers within structs. If the_go_status is a local, as soon as your function returns, the reference to that local will become invalid. So, if your code (or someone else's code) uses your instance of error_struct outside the function declaring the_go_status, things will quickly break.

Body:
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!


问:
attach library inside formElement in custom field widget
Hello everyone i am stuck in a place, I have created a custom field type and field widget and inside my field widget i have to call the js as image choose button is selected. Here is my code for custom field widget

```<code>public function formElement(
FieldItemListInterface $items,
$delta,
Array $element,
Array &$form,
FormStateInterface $formState
) {
$s3FormDetailss = GetSignature::getSignature();// To get the policy

$element['s3_select_image'] = array(
 '#type' => 'managed_file',
 '#title' => t($element['#title']),
 '#description' => t('Upload to s3'),
 '#default_value' => isset($items[$delta]->s3_upload_bucket_name) ?
     $items[$delta]->s3_upload_bucket_name: null,
 $form['#attached']['#library'][]= 's3_file_uploader/s3_file_uploader-s3_file_uploader-styles',
 $form['#attached']['drupalSettings']['s3_file_uploader']['s3_file_uploader-s3_file_uploader-styles']['variable'] = $s3FormDetailss,

);
</code>```

I want to attach the library here but i am getting error
"You are not allowed to use #library in #attached."

答:
Try to remove the # sign:
$form['#attached']['library'][]= '';

Body:
Hello everyone i am stuck in a place, I have created a custom field type and field widget and inside my field widget i have to call the js as image choose button is selected. Here is my code for custom field widget

public function formElement(
FieldItemListInterface $items,
$delta,
Array $element,
Array &$form,
FormStateInterface $formState
) {
$s3FormDetailss = GetSignature::getSignature();// To get the policy

$element['s3_select_image'] = array(
 '#type' => 'managed_file',
 '#title' => t($element['#title']),
 '#description' => t('Upload to s3'),
 '#default_value' => isset($items[$delta]->s3_upload_bucket_name) ?
     $items[$delta]->s3_upload_bucket_name: null,
 $form['#attached']['#library'][]= 's3_file_uploader/s3_file_uploader-s3_file_uploader-styles',
 $form['#attached']['drupalSettings']['s3_file_uploader']['s3_file_uploader-s3_file_uploader-styles']['variable'] = $s3FormDetailss,

);

I want to attach the library here but i am getting error
"You are not allowed to use #library in #attached."


问:
How to suppress stylecop error SA1650 (incorrectly spelled words)
I have a  documentation header on a class, that has words that are not spelled correctly according to stylecop. They are code specific and need to be there, though.

Error     SA1650 : CSharp.Documentation : The documentation text within
  the summary tag contains incorrectly spelled words: ...

I wish to suppress the error. How can I do this?

答:
The solution that worked for me is to add [SuppressMessage(...)] attribute with the following parameters:

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

/// <summary>
/// ... documentation with misspelled words ...
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")]
public class Program
{
    // ...
}
</code>```

Body:
The solution that worked for me is to add [SuppressMessage(...)] attribute with the following parameters:

// using System.Diagnostics.CodeAnalysis;

/// <summary>
/// ... documentation with misspelled words ...
/// </summary>
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")]
public class Program
{
    // ...
}

ContentLicense: CC BY-SA 4.0


问:
object is not a function or function pointer
I am getting the following compilation error:

prog.c:13:5: error: called object is not a function or function pointer
    a=250(n-1)+192;

```<code>#include <stdio.h>

int main(){
    long long n,a;
    int t;

    scanf("%d",&t);
    while(t--){
        scanf("%lld",&n);
        a=250(n-1)+192;
        printf("%lld\n",a);
    }
}
</code>```

答:
In C, you always have to write a * character for multiplication, as this:

```<code>a=250*(n-1)+192;
</code>```

Body:
I am getting the following compilation error:

prog.c:13:5: error: called object is not a function or function pointer
    a=250(n-1)+192;

#include <stdio.h>

int main(){
    long long n,a;
    int t;

    scanf("%d",&t);
    while(t--){
        scanf("%lld",&n);
        a=250(n-1)+192;
        printf("%lld\n",a);
    }
}

Body:
In C, you always have to write a * character for multiplication, as this:

a=250*(n-1)+192;


问:
Writing from JS to JSON
I have a JavaScript file:

```<code>export default {
  'test/index.yaml': {
    name: 'Test Index',
    product: 'test'
  },
  'test/hello.yaml': {
    name: 'Test Greeting',
    product: 'test'
  }
}
</code>```

I am looking to convert this into a JSON file with the desired output being:

```<code>{
  "test/index.yaml": {
    "name": "Test Index",
    "product": "test"
  },
  "test/hello.yaml": {
    "name": "Test Greeting",
    "product": "test"
  }
}
</code>```

--

I am trying to use something like this:

```<code>fs.readFileSync('test/configuration.js').toString().split('\n').forEach(function(line) {
    fs.appendFileSync('newTest/configuration.json', JSON.stringify(line) + '\n');
});
</code>```

But it doesn't break into the correct JSON syntax with the output of:

```<code>"export default {"
"  'test/index.yaml': {"
"    name: 'Test Index',"
"    product: 'test'"
"  },"
"  'test/hello.yaml': {"
"    name: 'Test Greeting',"
"    product: 'test'"
"  }"
"}"
</code>```

Thanks for the assistance!

答:
```<code>//'somefile.js'
module.exports = {
  'test/index.yaml': {
    name: 'Test Index',
    product: 'test'
  },
  'test/hello.yaml': {
    name: 'Test Greeting',
    product: 'test'
  }
}
</code>```

Your script:

```<code>let obj = require(__dirname + '/somefile.js');
console.log(obj);
//{ 'test/index.yaml': { name: 'Test Index', product: 'test' },
//  'test/hello.yaml': { name: 'Test Greeting', product: 'test' } }

fs = require('fs');
fs.writeFile('somefile.json', JSON.stringify(obj), function (err) {
  if(err) console.log(err);
});
</code>```

Title: Writing from JS to JSON

Body:
I have a JavaScript file:

export default {
  'test/index.yaml': {
    name: 'Test Index',
    product: 'test'
  },
  'test/hello.yaml': {
    name: 'Test Greeting',
    product: 'test'
  }
}

I am looking to convert this into a JSON file with the desired output being:

{
  "test/index.yaml": {
    "name": "Test Index",
    "product": "test"
  },
  "test/hello.yaml": {
    "name": "Test Greeting",
    "product": "test"
  }
}

--

I am trying to use something like this:

fs.readFileSync('test/configuration.js').toString().split('\n').forEach(function(line) {
    fs.appendFileSync('newTest/configuration.json', JSON.stringify(line) + '\n');
});

But it doesn't break into the correct JSON syntax with the output of:

"export default {"
"  'test/index.yaml': {"
"    name: 'Test Index',"
"    product: 'test'"
"  },"
"  'test/hello.yaml': {"
"    name: 'Test Greeting',"
"    product: 'test'"
"  }"
"}"

Thanks for the assistance!

Body:
//'somefile.js'
module.exports = {
  'test/index.yaml': {
    name: 'Test Index',
    product: 'test'
  },
  'test/hello.yaml': {
    name: 'Test Greeting',
    product: 'test'
  }
}

Your script:

let obj = require(__dirname + '/somefile.js');
console.log(obj);
//{ 'test/index.yaml': { name: 'Test Index', product: 'test' },
//  'test/hello.yaml': { name: 'Test Greeting', product: 'test' } }

fs = require('fs');
fs.writeFile('somefile.json', JSON.stringify(obj), function (err) {
  if(err) console.log(err);
});


问:
How to return a list of lists in recursive function in Python
I am playing around with some toy code in Python. But somehow cant get through. I am using a recursion in a Tree data structure to generate paths from a particular node to each children leaf nodes.

The idea behind the recursive function is to have a list which would collect each path to the individual leaf node and then collect each paths in another list.

```<code>class Tree:
    def __init__(self):
        self._ancestors = []
        self._store_nodes = {}

    def add_node(self, node):
        assert isinstance(node, Node)
        self._store_nodes[node.name] = node

    def get_c_path(self, node):
        subpath = []
        path = []
        path = self.ret_path(node, subpath, path)
        return path

    ## recursive function to fetch paths
    def ret_path(self, node, subpath=[], pathstore=[]):
        if len(node.children) ==  0:
            pathstore.append(subpath)
            return
        else:
            for c in node.children:
                subpath.append(c)
                self.ret_path(c, subpath, pathstore)

class Node(object):
    def __init__(self, name=''):
        self._name = name
        self._children = set([])
        self._parents = set([])

    @property
    def name(self):
        return self._name

    @property
    def children(self):
        return self._children

    @property
    def parents(self):
        return self._parents

    def add_child(self, node):
        assert isinstance(node, Node)
        self._children.add(node)

    def add_parent(self, node):
        assert isinstance(node, Node)
        self._parents.add(node)

if __name__ == '__main__':
    node_store = {1 : [2,3,4,5,6], 6 : [7,2,8,9,5], 2 : [10,11,5], 12 : [13,14,15,16], 5 : [21,22,23]}
    tree = Tree()
    ## build the tree and set parents and children of each node
    for k, v in node_store.items():
        parent_node = None
        if k in tree._store_nodes:
            parent_node = tree._store_nodes[k]
        else:
            parent_node = Node(k)
            tree.add_node(parent_node)
        for c in v:
            child_node = None
            if c in tree._store_nodes:
                child_node = tree._store_nodes[c]
            else:
                child_node = Node(c)
                tree.add_node(child_node)
            parent_node.add_child(child_node)
            child_node.add_parent(parent_node)

    print '-------------'
    path = tree.get_c_path(tree._store_nodes[2])
    for p in path:
        for t in p:
            print t.name
        print "-----"
</code>```

The result I am expecting is a list of list for Node-2 as follows:

```<code> path  = [[10], [11], [5, 21], [5, 22], [5, 23]]
</code>```

How can I correct my recursive function?

答:
Here's two methods that would accomplish this goal. I'm not quite sure how to fix your structure; it seemed easier to start from scratch.</p>

```<code>def get_c_path(self, node):
    branches = [[c] for c in node.children]
    expanded = self.expand_branches(branches)

    while branches != expanded:
        branches = expanded
        expanded = self.expand_branches(expanded)

    return expanded

def expand_branches(self, branches):
    new_branches = []
    for branch in branches:
        last_node = branch[-1]
        if last_node.children:
            for child in last_node.children:
                new_branches.append(branch + [child])
        else:
            new_branches.append(branch)
    return new_branches
</code>```

Body:
I am playing around with some toy code in Python. But somehow cant get through. I am using a recursion in a Tree data structure to generate paths from a particular node to each children leaf nodes.

The idea behind the recursive function is to have a list which would collect each path to the individual leaf node and then collect each paths in another list.

class Tree:
    def __init__(self):
        self._ancestors = []
        self._store_nodes = {}

    def add_node(self, node):
        assert isinstance(node, Node)
        self._store_nodes[node.name] = node

    def get_c_path(self, node):
        subpath = []
        path = []
        path = self.ret_path(node, subpath, path)
        return path

    ## recursive function to fetch paths
    def ret_path(self, node, subpath=[], pathstore=[]):
        if len(node.children) ==  0:
            pathstore.append(subpath)
            return
        else:
            for c in node.children:
                subpath.append(c)
                self.ret_path(c, subpath, pathstore)

class Node(object):
    def __init__(self, name=''):
        self._name = name
        self._children = set([])
        self._parents = set([])

    @property
    def name(self):
        return self._name

    @property
    def children(self):
        return self._children

    @property
    def parents(self):
        return self._parents

    def add_child(self, node):
        assert isinstance(node, Node)
        self._children.add(node)

    def add_parent(self, node):
        assert isinstance(node, Node)
        self._parents.add(node)

if __name__ == '__main__':
    node_store = {1 : [2,3,4,5,6], 6 : [7,2,8,9,5], 2 : [10,11,5], 12 : [13,14,15,16], 5 : [21,22,23]}
    tree = Tree()
    ## build the tree and set parents and children of each node
    for k, v in node_store.items():
        parent_node = None
        if k in tree._store_nodes:
            parent_node = tree._store_nodes[k]
        else:
            parent_node = Node(k)
            tree.add_node(parent_node)
        for c in v:
            child_node = None
            if c in tree._store_nodes:
                child_node = tree._store_nodes[c]
            else:
                child_node = Node(c)
                tree.add_node(child_node)
            parent_node.add_child(child_node)
            child_node.add_parent(parent_node)

    print '-------------'
    path = tree.get_c_path(tree._store_nodes[2])
    for p in path:
        for t in p:
            print t.name
        print "-----"

The result I am expecting is a list of list for Node-2 as follows:

 path  = [[10], [11], [5, 21], [5, 22], [5, 23]]

How can I correct my recursive function?

Body:
Here's two methods that would accomplish this goal. I'm not quite sure how to fix your structure; it seemed easier to start from scratch.

def get_c_path(self, node):
    branches = [[c] for c in node.children]
    expanded = self.expand_branches(branches)

    while branches != expanded:
        branches = expanded
        expanded = self.expand_branches(expanded)

    return expanded

def expand_branches(self, branches):
    new_branches = []
    for branch in branches:
        last_node = branch[-1]
        if last_node.children:
            for child in last_node.children:
                new_branches.append(branch + [child])
        else:
            new_branches.append(branch)
    return new_branches


问:
Powerpoint content add-in on Windows just show an image in slide show mode instead of a web app
I developed a powerpoint content addin and it works fine on Mac. Then I test it on Windows and found out that when I go to slide show mode, Powerpoint just show an image (a snapshot at the time entering to slide mode) instead of a web app. There is no interaction to the addin on slide show mode, clicking on it just make it move to the next slide. The addin works fine in edit mode though.

Strangely, this behaviour is not the same for all Powerpoint (2016) on Windows. I tested on another Windows laptop and everything works just fine. So I wonder if there is a settings or something for this, but I cannot figure out.

My addin shows the data changing overtime, animation, etc, so showing a static image is just useless.

Thanks for your help.

答:
Update 3/28/18

In response to the comments to this answer I've been in touch with the product team. It has now been determined that there is still an unfixed bug that causes these symptoms in some versions/builds/flight-configurations of PowerPoint. We are not able to provide an estimate of when it will be fixed. In the meantime, we cannot support interactive content add-ins in slide show mode in Windows.

-- Original Answer Below --

Update 10/18/17:

Just want to close the loop on this question.

It is possible for Office to behave differently on different computers even when the OS and Office version are the same, right down to the build number. Office pushes incremental code changes, called "flights", to desktop Office (Click-to-Run) approximately monthly without raising the Office build number.

Some of these flights are bug fixes. Others are experiments that are intentionally pushed to only some computers. Even in the case of bug fixes, the flights don't get pushed to all machines at the same time. It might take over a week for a flight to be pushed to all computers. (Strictly speaking, all computers with an Office build that supports the flight.)

The problem described in this question was a result of a bug in PowerPoint. A flight to fix it was deployed, but it had been pushed to only some of the OP's computers at the time (s)he posted the question. It has since been pushed to all computers.


问:
Setting build args for dockerfile agent using a Jenkins declarative pipeline
I'm using the declarative pipeline syntax to do some CI work inside a docker container.

I've noticed that the Docker plugin for Jenkins runs a container using the user id and group id of the jenkins user in the host (ie if the jenkins user has user id 100 and group id 111 it would run the pipeline creating a container with the command docker run -u 100:111 ...).

I had some problems with this, as the container will run with a non existing user (particularly I ran into some issues with the user not having a home dir). So I thought of creating a Dockerfile that will receive the user id and group id as build arguments and creater a proper jenkins user inside the container. The Dockerfile looks like this:

```<code>FROM ubuntu:trusty
ARG user_id
ARG group_id

# Add jenkins user
RUN groupadd -g ${group_id} jenkins
RUN useradd jenkins -u ${user_id} -g jenkins --shell /bin/bash --create-home
USER jenkins

...
</code>```

The dockerfile agent has an additionalBuildArgs property, so I can read the user id and group id of the jenkins user in the host and send those as build aguments, but the problem I have now is that it seems that there is no way of executing those commands in a declarative pipeline before specifying the agent. I want my Jenkinsfile to be something like this:

```<code>// THIS WON'T WORK
def user_id = sh(returnStdout: true, script: 'id -u').trim()
def group_id = sh(returnStdout: true, script: 'id -g').trim()

pipeline {
  agent {
    dockerfile {
      additionalBuildArgs "--build-arg user_id=${user_id} --build-arg group_id=${group_id}"
    }
  }
  stages {
    stage('Foo') {
      steps {
        ...
      }
    }
    stage('Bar') {
      steps {
        ...
      }
    }
    stage('Baz') {
      steps {
        ..
      }
    }
    ...
  }
}
</code>```

I there is any way to achieve this? I've also tried wrapping the pipeline directive inside a node, but the pipeline needs to be at the root of the file.

答:
if you have admin access to Jenkins you can add these two script approvals:

```<code>staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.String
staticMethod org.codehaus.groovy.runtime.ProcessGroovyMethods getText java.lang.Process
</code>```

in this URI: http://${jenkins_host:port}/jenkins/scriptApproval/

which will allow you to execute a shell command in the master in this way:

```<code>def user = 'id -u'.execute().text
node {
   echo "Hello World ${user}"
}
</code>```

Body:
I'm using the declarative pipeline syntax to do some CI work inside a docker container.

I've noticed that the Docker plugin for Jenkins runs a container using the user id and group id of the jenkins user in the host (ie if the jenkins user has user id 100 and group id 111 it would run the pipeline creating a container with the command docker run -u 100:111 ...).

I had some problems with this, as the container will run with a non existing user (particularly I ran into some issues with the user not having a home dir). So I thought of creating a Dockerfile that will receive the user id and group id as build arguments and creater a proper jenkins user inside the container. The Dockerfile looks like this:

FROM ubuntu:trusty
ARG user_id
ARG group_id

# Add jenkins user
RUN groupadd -g ${group_id} jenkins
RUN useradd jenkins -u ${user_id} -g jenkins --shell /bin/bash --create-home
USER jenkins

...

The dockerfile agent has an additionalBuildArgs property, so I can read the user id and group id of the jenkins user in the host and send those as build aguments, but the problem I have now is that it seems that there is no way of executing those commands in a declarative pipeline before specifying the agent. I want my Jenkinsfile to be something like this:

// THIS WON'T WORK
def user_id = sh(returnStdout: true, script: 'id -u').trim()
def group_id = sh(returnStdout: true, script: 'id -g').trim()

pipeline {
  agent {
    dockerfile {
      additionalBuildArgs "--build-arg user_id=${user_id} --build-arg group_id=${group_id}"
    }
  }
  stages {
    stage('Foo') {
      steps {
        ...
      }
    }
    stage('Bar') {
      steps {
        ...
      }
    }
    stage('Baz') {
      steps {
        ..
      }
    }
    ...
  }
}

I there is any way to achieve this? I've also tried wrapping the pipeline directive inside a node, but the pipeline needs to be at the root of the file.

Body:
if you have admin access to Jenkins you can add these two script approvals:

staticMethod org.codehaus.groovy.runtime.DefaultGroovyMethods execute java.lang.String
staticMethod org.codehaus.groovy.runtime.ProcessGroovyMethods getText java.lang.Process

in this URI: http://${jenkins_host:port}/jenkins/scriptApproval/

which will allow you to execute a shell command in the master in this way:

def user = 'id -u'.execute().text
node {
   echo "Hello World ${user}"
}


问:
How to hook to custom javascript trigger when using IJavaScriptExecutor
We have this event define in our web application, that creates a custom trigger called timelineEventClicked

```<code>canvas.addEventListener('click', function (evt) {
                    evt.stopImmediatePropagation();
                    var mousePos = getMousePos(canvas, evt);

                        ...//some manipulation here

                        $.event.trigger({
                            type: "timelineEventClicked",
                            sender: _timelineObject,
                            events: settings.events,
                            eventData: eventData
                        });
                    });
</code>```

I would like to hook to this event  timelineEventClicked and get back the eventData using selenium or protractor by injecting

```<code>IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
 executor.ExecuteScript(@"(function() {
                    document.addEventListener('timelineEventClicked', function(e) {
                        //Not sure what to do here to get back evendata
                })();"
                );
</code>```

The problem is that it doesn't seems to recognize the event timelineEventClicked and not sure why.

答:
To retreive the event, store it in the global scope with the listener.
Then click the canvas to trigger the event and return the variable:</p>

```<code>IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

// install the listener
executor.ExecuteScript(
  "$(document).on('timelineEventClicked', function(e){ window._evt=e; });");

// trigger the event
driver.FindElement(...).Click();

// return the event
var data = executor.ExecuteScript(@"return window._evt;");
</code>```

Body:
We have this event define in our web application, that creates a custom trigger called timelineEventClicked

canvas.addEventListener('click', function (evt) {
                    evt.stopImmediatePropagation();
                    var mousePos = getMousePos(canvas, evt);

                        ...//some manipulation here

                        $.event.trigger({
                            type: "timelineEventClicked",
                            sender: _timelineObject,
                            events: settings.events,
                            eventData: eventData
                        });
                    });

I would like to hook to this event  timelineEventClicked and get back the eventData using selenium or protractor by injecting

IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
 executor.ExecuteScript(@"(function() {
                    document.addEventListener('timelineEventClicked', function(e) {
                        //Not sure what to do here to get back evendata
                })();"
                );

The problem is that it doesn't seems to recognize the event timelineEventClicked and not sure why.

Body:
To retreive the event, store it in the global scope with the listener.
Then click the canvas to trigger the event and return the variable:

IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

// install the listener
executor.ExecuteScript(
  "$(document).on('timelineEventClicked', function(e){ window._evt=e; });");

// trigger the event
driver.FindElement(...).Click();

// return the event
var data = executor.ExecuteScript(@"return window._evt;");