问:
tensorflow - get max from tensor
So I have a tensor h_in of shape (50, ?, 1, 100) that I should now like to turn into shape (50, 1, 1, 100) by taking the max over the axis 1.

How do I do that?

I tried

```<code>h_out = max_pool(h_in)
</code>```

with

```<code>def max_pool(h,ksize=[1,-1,1,1],strides=[1,1,1,1],padding='VALID'):
    return tf.nn.max_pool(h,ksize=ksize,strides=strides,padding=padding)
</code>```

but that doesn't seem to reduce the size.

runnable example:

```<code>import tensorflow as tf
import numpy as np
import numpy.random as nprand

def _weight_variable(shape,name):
    initial = tf.truncated_normal(shape,stddev=0.1)
    v = tf.Variable(initial,name=name)
    return v

def _bias_variable(shape,name):
    initial = tf.constant(0.1,shape=shape)
    v = tf.Variable(initial,name=name)
    return v

def _embedding_variable(shape,name):
    initial = tf.truncated_normal(shape)
    v = tf.Variable(initial,name=name)
    return v

def conv2d(x,W,strides=[1,1,1,1],padding='VALID'):
    return tf.nn.conv2d(x,W,strides=strides,padding=padding)

def max_pool(h,ksize=[1,-1,1,1],strides=[1,1,1,1],padding='VALID'):
    return tf.nn.max_pool(h,ksize=ksize,strides=strides,padding=padding)

nof_embeddings= 55000
dim_embeddings = 300

batch_size = 50
filter_size = 100
x_input = tf.placeholder(tf.int32, shape=[batch_size, None])

def _model():

    embeddings = _embedding_variable([nof_embeddings,dim_embeddings],'embeddings')

    h_lookup = tf.nn.embedding_lookup(embeddings,x_input)
    h_embed = tf.reshape(h_lookup,[batch_size,-1,dim_embeddings,1])

    f = 3

    W_conv1f = _weight_variable([f,dim_embeddings,1,filter_size],f'W_conv1_{f}')
    b_conv1f = _bias_variable([filter_size],f'b_conv1_{f}')
    h_conv1f = tf.nn.relu(conv2d(h_embed,W_conv1f) + b_conv1f)

    h_pool1f = max_pool(h_conv1f)

    print("h_embed:",h_embed.get_shape())
    print()
    print(f'h_conv1_{f}:',h_conv1f.get_shape())
    print(f'h_pool1_{f}:',h_pool1f.get_shape())
    print()

    return tf.shape(h_pool1f)

if __name__ == '__main__':

    tensor_length = 35

    model = _model()
    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        batch = nprand.randint(0,nof_embeddings,size=[batch_size,tensor_length])
        shape = sess.run(model,
                         feed_dict ={
                                 x_input : batch
                                 })
        print('result:',shape)
</code>```

which outputs

```<code>h_embed: (50, ?, 300, 1)

h_conv1_3: (50, ?, 1, 100)
h_pool1_3: (50, ?, 1, 100)

result: [ 50  35   1 100]
</code>```

Let's say I instead hardcode the size that I want:

```<code>h_pool1f = max_pool(h_conv1f,ksize=[1,35-f+1,1,1])
</code>```

That works.
But now I'm in trouble as soon as I change the tensor_length (which is determined at runtime, so no, I cannot hardcode it).

One "solution" would be to blow the input up to a fixed maximum length by padding, or something, but then again, that introduces unnecessary computations and an artificial cap, both of which I should very much like to avoid.

So, is there

a way to make tensorflow "correctly" recognise the -1 in k_size?

or another way to compute the max?

答:
I think tf.reduce_max is what you are looking for:
https://www.tensorflow.org/api_docs/python/tf/reduce_max

Usage:

```<code>tens = some tensorflow.Tensor
ax = some positive integer, or -1 or None
red_m = tf.reduce_max(tens, axis=ax)
</code>```

If tens has shape [shape_0, shape_1, shape_2], the resulting tensor red_m will have shape [shape_1, shape_2] if ax=0, shape [shape_0, shape_2] if ax=1, and so on. If ax=-1, the last axes is inferred, while if ax=None, the reduction will happen along all axes.

Title: tensorflow - get max from tensor

Body:
So I have a tensor h_in of shape (50, ?, 1, 100) that I should now like to turn into shape (50, 1, 1, 100) by taking the max over the axis 1.

How do I do that?

I tried

h_out = max_pool(h_in)

with

def max_pool(h,ksize=[1,-1,1,1],strides=[1,1,1,1],padding='VALID'):
    return tf.nn.max_pool(h,ksize=ksize,strides=strides,padding=padding)

but that doesn't seem to reduce the size.

runnable example:

import tensorflow as tf
import numpy as np
import numpy.random as nprand

def _weight_variable(shape,name):
    initial = tf.truncated_normal(shape,stddev=0.1)
    v = tf.Variable(initial,name=name)
    return v

def _bias_variable(shape,name):
    initial = tf.constant(0.1,shape=shape)
    v = tf.Variable(initial,name=name)
    return v

def _embedding_variable(shape,name):
    initial = tf.truncated_normal(shape)
    v = tf.Variable(initial,name=name)
    return v

def conv2d(x,W,strides=[1,1,1,1],padding='VALID'):
    return tf.nn.conv2d(x,W,strides=strides,padding=padding)

def max_pool(h,ksize=[1,-1,1,1],strides=[1,1,1,1],padding='VALID'):
    return tf.nn.max_pool(h,ksize=ksize,strides=strides,padding=padding)

nof_embeddings= 55000
dim_embeddings = 300

batch_size = 50
filter_size = 100
x_input = tf.placeholder(tf.int32, shape=[batch_size, None])

def _model():

    embeddings = _embedding_variable([nof_embeddings,dim_embeddings],'embeddings')

    h_lookup = tf.nn.embedding_lookup(embeddings,x_input)
    h_embed = tf.reshape(h_lookup,[batch_size,-1,dim_embeddings,1])

    f = 3

    W_conv1f = _weight_variable([f,dim_embeddings,1,filter_size],f'W_conv1_{f}')
    b_conv1f = _bias_variable([filter_size],f'b_conv1_{f}')
    h_conv1f = tf.nn.relu(conv2d(h_embed,W_conv1f) + b_conv1f)

    h_pool1f = max_pool(h_conv1f)

    print("h_embed:",h_embed.get_shape())
    print()
    print(f'h_conv1_{f}:',h_conv1f.get_shape())
    print(f'h_pool1_{f}:',h_pool1f.get_shape())
    print()

    return tf.shape(h_pool1f)

if __name__ == '__main__':

    tensor_length = 35

    model = _model()
    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        batch = nprand.randint(0,nof_embeddings,size=[batch_size,tensor_length])
        shape = sess.run(model,
                         feed_dict ={
                                 x_input : batch
                                 })
        print('result:',shape)

which outputs

h_embed: (50, ?, 300, 1)

h_conv1_3: (50, ?, 1, 100)
h_pool1_3: (50, ?, 1, 100)

result: [ 50  35   1 100]

Let's say I instead hardcode the size that I want:

h_pool1f = max_pool(h_conv1f,ksize=[1,35-f+1,1,1])

That works.
But now I'm in trouble as soon as I change the tensor_length (which is determined at runtime, so no, I cannot hardcode it).

One "solution" would be to blow the input up to a fixed maximum length by padding, or something, but then again, that introduces unnecessary computations and an artificial cap, both of which I should very much like to avoid.

So, is there

a way to make tensorflow "correctly" recognise the -1 in k_size?

or another way to compute the max?

Body:
I think tf.reduce_max is what you are looking for:
https://www.tensorflow.org/api_docs/python/tf/reduce_max

Usage:

tens = some tensorflow.Tensor
ax = some positive integer, or -1 or None
red_m = tf.reduce_max(tens, axis=ax)

If tens has shape [shape_0, shape_1, shape_2], the resulting tensor red_m will have shape [shape_1, shape_2] if ax=0, shape [shape_0, shape_2] if ax=1, and so on. If ax=-1, the last axes is inferred, while if ax=None, the reduction will happen along all axes.


来源: stackexchange

问:
C# PsExec get process list: name, path
My code:

```<code>Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.FileName = Environment.CurrentDirectory + @"\PsExec\PsExec.exe";
p.StartInfo.Arguments = @"\\server-0 cmd /c wmic process get description,executablepath";
p.Start();
string output = p.StandardOutput.ReadToEnd();
string errormessage = p.StandardError.ReadToEnd();
p.WaitForExit();
</code>```

The console window does not close itself. When I close it manually, I see (in output):

```<code>Description             ExecutablePath
</code>```

I don't see any other line! But if I write the same in the console:

```<code>psexec \\server-0 cmd /c wmic process get description,executablepath
</code>```

I see:

```<code>Description             ExecutablePath
System Idle Process
System
smss.exe
csrss.exe               C:\Windows\system32\csrss.exe
wininit.exe             C:\Windows\system32\wininit.exe
csrss.exe               C:\Windows\system32\csrss.exe
...
</code>```

I tried some ideas like: Thread.Sleep(...), per line reading, -accepteula, EnableRaisingEvents / OutputDataReceived (it does not call), -d flag (no output), UseShellExecute=true (works, but I couldn't hide the console window)...

Why do I receive only the first row (in the C# code above)? What should I change to receive the same content I see in the console?

Sorry for the bad English. Thanks for your answers.

答: Use delegating. Rise event on output received and capture the data. I did the same</p>

ContentLicense: CC BY-SA 3.0

Title: C# PsExec get process list: name, path

Body:
My code:

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.FileName = Environment.CurrentDirectory + @"\PsExec\PsExec.exe";
p.StartInfo.Arguments = @"\\server-0 cmd /c wmic process get description,executablepath";
p.Start();
string output = p.StandardOutput.ReadToEnd();
string errormessage = p.StandardError.ReadToEnd();
p.WaitForExit();

The console window does not close itself. When I close it manually, I see (in output):

Description             ExecutablePath

I don't see any other line! But if I write the same in the console:

psexec \\server-0 cmd /c wmic process get description,executablepath

I see:

Description             ExecutablePath
System Idle Process
System
smss.exe
csrss.exe               C:\Windows\system32\csrss.exe
wininit.exe             C:\Windows\system32\wininit.exe
csrss.exe               C:\Windows\system32\csrss.exe
...

I tried some ideas like: Thread.Sleep(...), per line reading, -accepteula, EnableRaisingEvents / OutputDataReceived (it does not call), -d flag (no output), UseShellExecute=true (works, but I couldn't hide the console window)...

Why do I receive only the first row (in the C# code above)? What should I change to receive the same content I see in the console?

Sorry for the bad English. Thanks for your answers.


问:
cURL send JSON and PDF file
I have this cURL command to speak with my API:

```<code>curl -i -H "Content-Type: application/json" -X POST -d '{"sid":"01234567","text":"TEST","tlf":"123456","ctc":"123456","opr":"XYZ","fbm":"email@email.com","flag":"XYZ","product":"XYZ"}' http://XXX.XXX.XXX.XXX:8080/todo/api/v1.0/tasks
</code>```

Which works perfectly, here the response:

```<code>HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 24
Server: Werkzeug/0.11.3 Python/2.6.6
Date: Wed, 07 Jun 2017 10:03:00 GMT
</code>```

Now I want to send a pdf file in that same command.

I figured I add:

```<code>"file":"/var/www/html/olotool/API/attachments/pdf-test.pdf"
</code>```

at the end but it gets saved as a string instead of a document.

How can I add this in one command?

UPDATE:

```<code>"file":"$(base64 ~/attachments/pdf-test.pdf)"
</code>```

Changes the outcome into <type 'file'> it's still a string but at least it's content is not (base64 ~/attachments/pdf-test.pdf).

答:
Here is the answer:

```<code>curl -i -F data='{"sid":"0123456","text":"TEST","tlf":"13245679","ctc":"123456","opr":"XXX","fbm":"mail@mail.com","flag":"XYZ","product":"XYZ"}' -F 'file=@/var/www/html/olotool/API/testpdf/test.pdf' http://XXX.XXX.XXX.XXX:8080/todo/api/v1.0/tasks
</code>```

On the API instead of using request.json you use request.form then convert datato json with json.loads(data).

For the file, you need to use request.file['files'] and dont forget to encode files like pdf's or word docs to base64 if you want to import them to MySQL with file.read().encode("base64")

Title: cURL send JSON and PDF file

Body:
I have this cURL command to speak with my API:

curl -i -H "Content-Type: application/json" -X POST -d '{"sid":"01234567","text":"TEST","tlf":"123456","ctc":"123456","opr":"XYZ","fbm":"email@email.com","flag":"XYZ","product":"XYZ"}' http://XXX.XXX.XXX.XXX:8080/todo/api/v1.0/tasks

Which works perfectly, here the response:

HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 24
Server: Werkzeug/0.11.3 Python/2.6.6
Date: Wed, 07 Jun 2017 10:03:00 GMT

Now I want to send a pdf file in that same command.

I figured I add:

"file":"/var/www/html/olotool/API/attachments/pdf-test.pdf"

at the end but it gets saved as a string instead of a document.

How can I add this in one command?

UPDATE:

"file":"$(base64 ~/attachments/pdf-test.pdf)"

Changes the outcome into <type 'file'> it's still a string but at least it's content is not (base64 ~/attachments/pdf-test.pdf).

Body:
Here is the answer:

curl -i -F data='{"sid":"0123456","text":"TEST","tlf":"13245679","ctc":"123456","opr":"XXX","fbm":"mail@mail.com","flag":"XYZ","product":"XYZ"}' -F 'file=@/var/www/html/olotool/API/testpdf/test.pdf' http://XXX.XXX.XXX.XXX:8080/todo/api/v1.0/tasks

On the API instead of using request.json you use request.form then convert datato json with json.loads(data).

For the file, you need to use request.file['files'] and dont forget to encode files like pdf's or word docs to base64 if you want to import them to MySQL with file.read().encode("base64")


问:
get client ip address in request hapijs for node
I need to get the ip address of client using my application in the request of hapijs node... we are using pm2 and Nginx for server to run live and we have used the request.info.address but it gives the server local ip as 127.0.0.1 but what i need was the client's IP who uses my application eg: 192.x.x.111 ...</p>

答:
I'm running the same stack for my hapi apps with nginx and PM2. Proxying requests through nginx to a node app on the same host will always result in 127.0.0.1 for the remote address, because nginx forwards the request on the same host.

Solution: there's a dedicated plugin hapi-geo-locate that determines the actual client IP address even though you're running your app behind a reverse proxy (like nginx).

hapi-geo-locate supports various proxies and HTTP headers, so you should be save and get the user's IP running your app on different platforms.

Hope that helps!


问:
C++ Question about default constructor
What does it mean to call a class like this:

```<code>class Example
{
 public:
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

 return(0);
}
</code>```

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

答: Does it even compile? Anyway, see this related topic.</p>

OwnerDisplayName: Daniel

ContentLicense: CC BY-SA 2.5

Title: C++ Question about default constructor

Body:
What does it mean to call a class like this:

class Example
{
 public:
  Example(void);
  ~Example(void);
}

int main(void)
{
 Example ex(); // <<<<<< what is it called to call it like this?

 return(0);
}

Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that would be bad?

Thanks for all answers.

LastEditorDisplayName: codelogic

OwnerDisplayName: Nemanja Trifunovic


问:
Can't start phpMyAdmin. Keep getting the #2002 socket error
I've been trying to set mysql and phpMyAdmin for the last 12 hours, without any success. And yes, after hours and hours of Google-ing I know that is a common problem and I've read similar queries on stackoverflow but still can't come with the solution.....

I've tried everything - from changing the

```<code>$cfg['Servers'][$i]['port']
</code>```

in the config.inc.php file to 3306, 127.0.0.1....

typing the socket path in the config.inc.php file - both  tmp/mysql.php and the /var/mysql/mysql.sock.

I've tried changing the socket path in the my.cnf file and the php.ini....but I keep getting the same error:

```<code>#2002 - No such file or directory
The server is not responding (or the local server's socket is not correctly configured).
</code>```

I'm using MySQL (5.1.65), PhpMyAdmin (3.5.2.2) and PHP (5.3.8).

答:
Had this problem on Windows 7 Ultimate, AppServ.
Just reload SQL and Apache (but you need to reload both of them, reloading only Apache didn't worked).</p>

```
PHPMyAdmin 4.6.6
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
Server version: 5.7.17-log - MySQL Community Server (GPL)
PHP: 5.6.30
```

Body:
I've been trying to set mysql and phpMyAdmin for the last 12 hours, without any success. And yes, after hours and hours of Google-ing I know that is a common problem and I've read similar queries on stackoverflow but still can't come with the solution.....

I've tried everything - from changing the

$cfg['Servers'][$i]['port']

in the config.inc.php file to 3306, 127.0.0.1....

typing the socket path in the config.inc.php file - both  tmp/mysql.php and the /var/mysql/mysql.sock.

I've tried changing the socket path in the my.cnf file and the php.ini....but I keep getting the same error:

#2002 - No such file or directory
The server is not responding (or the local server's socket is not correctly configured).

I'm using MySQL (5.1.65), PhpMyAdmin (3.5.2.2) and PHP (5.3.8).

Body:
Had this problem on Windows 7 Ultimate, AppServ.
Just reload SQL and Apache (but you need to reload both of them, reloading only Apache didn't worked).

PHPMyAdmin 4.6.6
Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/5.6.30
Server version: 5.7.17-log - MySQL Community Server (GPL)
PHP: 5.6.30


问:
Check if a variable has "moved"
I have a thread wherein the program constantly gets the user's distance from another phone thru bluetooth.

I opted to implement a text-to-speech feature wherein the program will "talk" when the user moves a meter closer/farther. I am already able to get the distance but the problem is I have no idea how to check if the distance has moved atleast 1 meter closer/farther. For example:

```<code>Initial distance: 0.81 meters
</code>```

The TTS feature should activate when the value increases/decreases by roughly 1 meter.

```<code>Should activate TTS when distance becomes: 1.81, 2.85, 3.90
</code>```

Notice that the 2nd value 2.85 is not exactly 1 meter farther from the last distance 1.81 because the distance being obtained "jumps" meaning if you display the distance and start walking away it will look similar to this:

```<code>Distance: 1.01, 1.86, 2.31, 3.29, ...
</code>```

I have tried various ways but I just can't seem to do it. Any help will be appreciated!

答:
You can use following code:</p>

```<code>int initialDistance = x;//declare it global
int newDistance = y;

if(Math.abs(newDistance -initialDistance )>=1) {
//TTS;
initialDistance = newDistance;
}
</code>```

Title: Check if a variable has "moved"

Body:
I have a thread wherein the program constantly gets the user's distance from another phone thru bluetooth.

I opted to implement a text-to-speech feature wherein the program will "talk" when the user moves a meter closer/farther. I am already able to get the distance but the problem is I have no idea how to check if the distance has moved atleast 1 meter closer/farther. For example:

Initial distance: 0.81 meters

The TTS feature should activate when the value increases/decreases by roughly 1 meter.

Should activate TTS when distance becomes: 1.81, 2.85, 3.90

Notice that the 2nd value 2.85 is not exactly 1 meter farther from the last distance 1.81 because the distance being obtained "jumps" meaning if you display the distance and start walking away it will look similar to this:

Distance: 1.01, 1.86, 2.31, 3.29, ...

I have tried various ways but I just can't seem to do it. Any help will be appreciated!

Body:
You can use following code:

int initialDistance = x;//declare it global
int newDistance = y;

if(Math.abs(newDistance -initialDistance )>=1) {
//TTS;
initialDistance = newDistance;
}


问:
How can I go from First ViewController to Second ViewController, get values and go back to First
I just spent couple of days for trying to figure this out for mac app, but not doing it successfully.

I have first ViewController and second ViewController.  Let's say, ViewControllerA(VC-A) and ViewControllerB(VC-B).  In Main.storyboard, they are connected by segue with identifier "PromptToUser".

VC-B gets triggered not by button, but if condition during the process.

It is triggered by:

```<code>performSegue(withIdentifier: "PromptToUser", sender: self)
</code>```

in VC-A.

In VC-A, I put the followings so far:

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
}

In VC-B, so far, I have:

```<code>@IBOutlet weak var Login: NSTextField!
@IBOutlet weak var Pass: NSSecureTextField!
</code>```

VC-B also has a button which I want to make as a trigger to collect information entered by user for above variables and send it back to first view.

I found many similar topics on this in stackoverflow.  However, it seems most of them are for iOS, but not for mac app as I could not make UI... and other classes (delegates) and protocols they mentioned to be recognized for Swift 3 environment.  I have NSViewController, and NS... not UI...

What would be the best way to approach this for mac app with Swift 3?

答:
You Can make a static variable in VC-A and just update the value of static variable from VC-B. Example

In VC-A

```<code>static var login = ""
static var password = ""
</code>```

In VC-B

```<code>VC-A.login =  nameTextField.text
VC-A.password = passTextField.text
</code>```

Write the code in SaveButton Action of VC-B, and you will get the update value in VC-A.
If You are not using any Save Button in VC-B, then You can write code in viewWillDisappear Method of VC-B

```<code>    override func viewDidDisappear(_ animated: Bool) {
          firstVC_A.login =  nameTextField.text
          firstVC_A.password = passTextField.text

    }
</code>```

Body:
I just spent couple of days for trying to figure this out for mac app, but not doing it successfully.

I have first ViewController and second ViewController.  Let's say, ViewControllerA(VC-A) and ViewControllerB(VC-B).  In Main.storyboard, they are connected by segue with identifier "PromptToUser".

VC-B gets triggered not by button, but if condition during the process.

It is triggered by:

performSegue(withIdentifier: "PromptToUser", sender: self)

in VC-A.

In VC-A, I put the followings so far:

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
}

In VC-B, so far, I have:

@IBOutlet weak var Login: NSTextField!
@IBOutlet weak var Pass: NSSecureTextField!

VC-B also has a button which I want to make as a trigger to collect information entered by user for above variables and send it back to first view.

I found many similar topics on this in stackoverflow.  However, it seems most of them are for iOS, but not for mac app as I could not make UI... and other classes (delegates) and protocols they mentioned to be recognized for Swift 3 environment.  I have NSViewController, and NS... not UI...

What would be the best way to approach this for mac app with Swift 3?

Body:
You Can make a static variable in VC-A and just update the value of static variable from VC-B. Example

In VC-A

static var login = ""
static var password = ""

In VC-B

VC-A.login =  nameTextField.text
VC-A.password = passTextField.text

Write the code in SaveButton Action of VC-B, and you will get the update value in VC-A.
If You are not using any Save Button in VC-B, then You can write code in viewWillDisappear Method of VC-B

    override func viewDidDisappear(_ animated: Bool) {
          firstVC_A.login =  nameTextField.text
          firstVC_A.password = passTextField.text

    }


问:
Alternative to View for complex Data?
I have a table that contains partial data that is of no use to the user viewing my application. The viewer wants to see a similar table that has all the values calculated out, and wants to be able to quickly query THAT data. Normally, this would be the perfect place to use a View. Unfortunately the complex nature of the calculations limit my use of Views, so I need an alternate solution. I was thinking of doing something like the following...

Table A contains back-end data. Any time this table is updated, a trigger fired that updates Table B, which shows the result of these calculations. Table B can be queried quickly at this point.

My only concern is that the calculation procedure is somewhat lengthy, and Table A has the potential to be updated many times in bursts. Are there any solutions that are almost like a "Before Select" trigger? So basically Table A could be updated many times in a row, but the calculation would only occur when Table B was queried?

Here's an example timeline:

Table A is Updated

Table A is Updated Again [Don't run SP since nobody needs Table B data yet]

Data is requested from Table B [Run SP to update Table B before getting data]

Table A is Updated

Data is requested from Table B [Run SP to update Table B before getting data]

Data is requested from Table B [Don't run stored procedure because Table A wasn't updated between requests for Table B data]

So my questions are:

Is there anything existing like what I described above?

If not, is there a way to make triggers hold off until the completion of a batch of updates/inserts? Table A won't be modified very often, so I can live with a slow trigger when it is updated. The only problem is that when Table A does get updated, it is normally hundreds of rows at a time and I don't want a slow trigger to run every time.

Thanks for any solutions/insight!

Edit - A little more detail on why (I think at least) the trigger implementation would be slow:

The application that will be sending the Update/Insert/Delete statements is using LINQ-to-SQL, which isn't particularly good with batch operations. So if I wanted to delete a bunch of records, it would send a bunch of delete statements instead of a batch delete statement. Is there any way to group delete statements and have the trigger run after that? (Maybe I'm getting too far off topic here).

The "calculations" I'm speaking of involve some recursive functions and some decision-making processes. The data I'm actually dealing with is scheduling data. So Table A contains tasks which may or may not have a scheduled start. If there is no scheduled start defined, it has to derive it from its predecessors scheduled start + its predecessors duration. In some cases the predecessor might not have that information either, hence the recursive query that keeps digging until it finds the result. It's not painfully slow, but if it had to run on every insert/update/delete, it would get there. The "Table B" I refer to above is basically the same table, but it already has the calculated scheduled start data within (which needs to change on update of Table A).

答: If possible (which of course it might not be in your specific situation), you could return your data from table B via a stored procedure call, rather than SELECTing from a view/table. That way your procedure does the heavy lifting only when it is specifically called (i.e. after Table A has been updated).</p>

Title: Alternative to View for complex Data?


问:
How to setup a browse menu to cycle a page and it's sub pages only in typo3?
I am trying to set up a browse menu to cycle a page and it's sub pages. I have to have it in the format of < 2 > where < is the previous page, 2 is the current page, and > is the next page. To reslove this I decided to put an extension template on the parent page which in which a browse menu points to the first page of the sub page tree:

```<code>lib.pagenumber = HMENU
lib.pagenumber{
  special = browse
  special.items = | next
  special.next.uid = 100
  special.next.fields.title = 2

  1 = TMENU
  1{
     noBlur = 1
     expAll = 0
     NO = 1
     NO.ATagTitle = 1
     NO.before = <div id="currLGMpg" class= "currpg">1</div>
     NO.linkWrap = <div class=nextLGMpg>|</div>

  }
}
</code>```

The current page is not linked but just an image box which has to be between the prev and next links and also be auto numbered. this is the second problem I am trying to solve.
For the subpages I am thinking that a template on the first subpage with option split on the linkwrap would work for styling the prev and next links but I have no idea how to put the image for the current page in the middle.

答:
Hello for cycling you should follows the below steps this only for next please follow same steps for prev.</p>

```<code>temp.lightbox_navi.30 = HMENU
temp.lightbox_navi.30 {
    stdWrap.wrap = <li>|</li>
    special = browse
    special {
        items = next
        items.prevnextToSection = 0
        next.fields.title = < next Projekt
    }
    1 = TMENU
    1 {
        NO = 1
    }
    stdWrap.ifEmpty.cObject = HMENU
    stdWrap.ifEmpty.cObject {
        special = browse
        special {
            items = first
            items.prevnextToSection = 0
            first.fields.title = < next Projekt o
        }
        1 = TMENU
        1 {
            NO = 1
        }
    }
}
</code>```

Body:
I am trying to set up a browse menu to cycle a page and it's sub pages. I have to have it in the format of < 2 > where < is the previous page, 2 is the current page, and > is the next page. To reslove this I decided to put an extension template on the parent page which in which a browse menu points to the first page of the sub page tree:

lib.pagenumber = HMENU
lib.pagenumber{
  special = browse
  special.items = | next
  special.next.uid = 100
  special.next.fields.title = 2

  1 = TMENU
  1{
     noBlur = 1
     expAll = 0
     NO = 1
     NO.ATagTitle = 1
     NO.before =
1

     NO.linkWrap =
|

  }
}

The current page is not linked but just an image box which has to be between the prev and next links and also be auto numbered. this is the second problem I am trying to solve.
For the subpages I am thinking that a template on the first subpage with option split on the linkwrap would work for styling the prev and next links but I have no idea how to put the image for the current page in the middle.

Body:
Hello for cycling you should follows the below steps this only for next please follow same steps for prev.

temp.lightbox_navi.30 = HMENU
temp.lightbox_navi.30 {
    stdWrap.wrap = <li>|</li>
    special = browse
    special {
        items = next
        items.prevnextToSection = 0
        next.fields.title = < next Projekt
    }
    1 = TMENU
    1 {
        NO = 1
    }
    stdWrap.ifEmpty.cObject = HMENU
    stdWrap.ifEmpty.cObject {
        special = browse
        special {
            items = first
            items.prevnextToSection = 0
            first.fields.title = < next Projekt o
        }
        1 = TMENU
        1 {
            NO = 1
        }
    }
}


问:
C++ v100 platform toolset profiler
I am looking for a profiler for C++ project build in Visual Studio and compiled with v100 platform toolset

I got memory leak when my application is running (memory usage is increasing).

When i exit the program i do not see any memory leaks (I use VLD)

答:
If you’re using new in your application, you should use the debug version of new. Add the following line at the beginning of your files (but after #include "stdafx.h"):

```<code>//...
#define new DEBUG_NEW
//...
</code>```

If the memory allocation number that you're seeing in the output window has always the same number, regardless of how many times you're running the application, you can set a break-point on allocation number:

```<code>Output Window:
...
Detected memory leaks!
Dumping objects ->
your file path (line number where new was called) : {allocation number}
...
</code>```

Title: C++ v100 platform toolset profiler

Body:
If you’re using new in your application, you should use the debug version of new. Add the following line at the beginning of your files (but after #include "stdafx.h"):

//...
#define new DEBUG_NEW
//...

If the memory allocation number that you're seeing in the output window has always the same number, regardless of how many times you're running the application, you can set a break-point on allocation number:

Output Window:
...
Detected memory leaks!
Dumping objects ->
your file path (line number where new was called) : {allocation number}
...


问:
What is the difference between binlog-do-db and replicate-do-db?
I'm a beginner for MySQL Master-Slave .

and I have read two tutorials .

How to Setup MariaDB (Master-Slave) Replication

Setup MariaDB Master-Slave Replication

In first tutorial. It make me that

```<code>[mysqld] Master section

log-bin

server_id=1

replicate-do-db=employees

bind-address=192.168.0.18

[mysqld] SLAVE Section

server_id=2
replicate-do-db=employees
</code>```

But in the second tutorial, it show me that

```<code>[mysqld] Master
server_id=1
log-basename=master
log-bin
binlog-format=row
binlog-do-db=unixmen

[mysqld] Slave
server-id = 2
replicate-do-db=unixmen
</code>```

And why I should LOCK TABLES, and mysqldump sql, then import it ?

```<code>FLUSH TABLES WITH READ LOCK;
</code>```

答:
DISCLAIMER: To keep things easy and non-confusing here, I talk about a simple 1 Master - 1 Slave setup. No chains, no master-master, or whatever...

Your first tutorial is wrong, it should be binlog-do-db there.

Replication works like this.

The master writes all transactions into its binary log.

The slave reads the transactions from masters binary log and writes them to its relay log.

Only after that the slave executes the statements from its relay log.

binlog-do-db makes the master write only statements for the specified DB into its binary log.

replicate-do-db makes the slave just read statements from the relay log, that are for the specified DB.

replicate-do-db has no effect on the master, since there is no relay log to read from.

The LOCK TABLES part is there, so that the data is consistent. It prevents that the data on the master is modified while backing up the data is still in process.

You restore the database from this backup on the slave, because when you set up a slave, you don't always start from fresh. Therefore it's made so, that you just provide the same data basis on both servers, then you tell the slave at which transaction coordinates the master is and voila, you can start your replication. You can also unlock the master after having dumped the data. Just make sure, that you get the slave up in time before statements in the binary log get lost due to log rotation.

Body:
I'm a beginner for MySQL Master-Slave .

and I have read two tutorials .

How to Setup MariaDB (Master-Slave) Replication

Setup MariaDB Master-Slave Replication

In first tutorial. It make me that

[mysqld] Master section

log-bin

server_id=1

replicate-do-db=employees

bind-address=192.168.0.18

[mysqld] SLAVE Section

server_id=2
replicate-do-db=employees

But in the second tutorial, it show me that

[mysqld] Master
server_id=1
log-basename=master
log-bin
binlog-format=row
binlog-do-db=unixmen

[mysqld] Slave
server-id = 2
replicate-do-db=unixmen

And why I should LOCK TABLES, and mysqldump sql, then import it ?

FLUSH TABLES WITH READ LOCK;


问:
How can I configure Featherlight to support tabindex within the modal?
My form (look at the demo fiddle here, and I've also pasted some code below) seems not to support tabindex inside the Featherlight modal.

I think it's because of this part of Featherlight here.

How can I display a form within a modal and still let a user press the TAB key to bounce to the next field?

It seems like I need to add a hack into the Featherlight library, which I'd rather not do.

Thanks!

```<code><div style="display: none;">
  <div id="modal">
    My form NEEDS to support tabindex. If Featherlight is going to set tabindex to -1 for anything (even temporarily), it should only be for elements that aren't inside the modal.
    <div class="mainInputWrapper">
      <input type="text" name="fullname" placeholder="Your Name" required id="firstname" /><span class="forValidationDisplay"></span>
    </div>
    <div class="mainInputWrapper">
      <input type="email" name="email" placeholder="Your Best Email Address*" required id="email" /><span class="forValidationDisplay"></span>
    </div>
    <button>
      Submit
    </button>
  </div>
</div>
<a class="role-element leadstyle-link" href="#" data-featherlight="#modal">Click here if you're interested</a>
</code>```

答:
Just in case you wonder, the last statement of @Ryan's code is not required.

I added this at the end of the source code (because in my case I don't mind editing the source code) and it worked:

```<code>$.featherlight._callbackChain.beforeOpen = function (event) {
        //http://stackoverflow.com/q/42234790/470749
        //By overriding this function, I can prevent the messing up of tabindex values done by: https://github.com/noelboss/featherlight/blob/master/src/featherlight.js#L559
};
$.featherlight._callbackChain.afterClose = function (event) {
    //See note above in $.featherlight._callbackChain.beforeOpen
};
</code>```

Body:
My form (look at the demo fiddle here, and I've also pasted some code below) seems not to support tabindex inside the Featherlight modal.

I think it's because of this part of Featherlight here.

How can I display a form within a modal and still let a user press the TAB key to bounce to the next field?

It seems like I need to add a hack into the Featherlight library, which I'd rather not do.

Thanks!

    My form NEEDS to support tabindex. If Featherlight is going to set tabindex to -1 for anything (even temporarily), it should only be for elements that aren't inside the modal.

      <input type="text" name="fullname" placeholder="Your Name" required id="firstname" />

      <input type="email" name="email" placeholder="Your Best Email Address*" required id="email" />

    <button>
      Submit
    </button>

Click here if you're interested

Body:
Just in case you wonder, the last statement of @Ryan's code is not required.

I added this at the end of the source code (because in my case I don't mind editing the source code) and it worked:

$.featherlight._callbackChain.beforeOpen = function (event) {
        //http://stackoverflow.com/q/42234790/470749
        //By overriding this function, I can prevent the messing up of tabindex values done by: https://github.com/noelboss/featherlight/blob/master/src/featherlight.js#L559
};
$.featherlight._callbackChain.afterClose = function (event) {
    //See note above in $.featherlight._callbackChain.beforeOpen
};


问:
undefined method `action' for ArticlesController(Table doesn't exist):Class - Ruby on Rails error
I got an error notification but I dont know where to search.
See attachement.

Where's the file with the included error?
I did the following instruction:
http://guides.rubyonrails.org/getting_started.html

Here's my code:

```<code>class ArticlesController < ActiveRecord::Base
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private #description
    def article_params #description
      params.require(:article).permit(:title, :text)
    end #here's the end
end
</code>```

答:
Change

```<code>class ArticlesController < ActiveRecord::Base
// ...
end
</code>```

to

```<code>class ArticlesController < ApplicationController
// ...
end
</code>```

ActiveRecord::Base is for models.

Body:
I got an error notification but I dont know where to search.
See attachement.

Where's the file with the included error?
I did the following instruction:
http://guides.rubyonrails.org/getting_started.html

Here's my code:

class ArticlesController < ActiveRecord::Base
  def index
    @articles = Article.all
  end

  def show
    @article = Article.find(params[:id])
  end

  def new
    @article = Article.new
  end

  def edit
    @article = Article.find(params[:id])
  end

  def create
    @article = Article.new(article_params)

    if @article.save
      redirect_to @article
    else
      render 'new'
    end
  end

  def update
    @article = Article.find(params[:id])

    if @article.update(article_params)
      redirect_to @article
    else
      render 'edit'
    end
  end

  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    redirect_to articles_path
  end

  private #description
    def article_params #description
      params.require(:article).permit(:title, :text)
    end #here's the end
end

Body:
Change

class ArticlesController < ActiveRecord::Base
// ...
end

to

class ArticlesController < ApplicationController
// ...
end

ActiveRecord::Base is for models.


问:
Click and disabled element only once previous operation is complete
using Eclipse automating my application using Selenium. In my application there is a page were some data loads so applied an explicit wait until he data loads, now once that is loaded I save and that save time depends each time on the amount of data loaded. There is an element over the screen that becomes disabled during this Save operation and enabled only when Save operation is over. But her when I'm applying the explicit wait with Isclickable method it is not working. It reaches to that element before the save was over and tries clicking an disabled object. Can someone please help with this. </p>

答:
Use implicit wait.
Or,
When element is enabled at that time only click the element.You need to check whether element is enabled or disabled.So for that try using Boolean.</p>


问:
issue with filter binding with knockout.js
I'm new working with Knockout.js framework and I'm having the following error in my code, I'm building an application using Knockout.js, everything works fine except when I tried to create a dependentObservable.

This is the javascript code:

```<code>(function() {
  'use strict';

    console.log("This is my Application");

     var app = {
         mapElement: document.getElementById('map'),
         mapObj: map,
         locations : ko.observableArray([
            {id: 1, title: 'Holywood Theater', location: {lat: 43.098344, lng: -76.145697}},
            {id: 2, title: 'Mattydale Fire Department', location: {lat: 43.098172, lng: -76.142189}},
            {id: 3, title: 'Original Italian Pizza', location: {lat: 43.098854, lng:  -76.144700}},
            {id: 4, title: 'Roxboro Road Middle School', location: {lat: 43.101110, lng: -76.150901}},
            {id: 5, title: 'Big Lots', location: {lat: 43.101400, lng: -76.146985}},
            {id: 6, title: 'Camnel pub', location: {lat: 43.098670, lng: -76.145832}}
        ]),
        markers:[],
        textFilter: ko.observable(),
        filterLocations: ko.dependentObservable(function () {
                            return ko.utils.arrayFilter(app.locations(), function (loc) {
                                return loc.title().toLowerCase().includes(app.textFilter().toLowerCase());
                            });
                        })
     };

    ko.applyBindings(app);
})();
</code>```

The error in the chrome console is:

Uncaught TypeError: Cannot read property 'locations' of undefined

答:
You can't use 'app' var because you're still creating it.</p>

```<code>var app = {...

    ^^^    return ko.utils.arrayFilter(app.locations(), ...

                                       ^^^
</code>```

Body:
I'm new working with Knockout.js framework and I'm having the following error in my code, I'm building an application using Knockout.js, everything works fine except when I tried to create a dependentObservable.

This is the javascript code:

(function() {
  'use strict';

    console.log("This is my Application");

     var app = {
         mapElement: document.getElementById('map'),
         mapObj: map,
         locations : ko.observableArray([
            {id: 1, title: 'Holywood Theater', location: {lat: 43.098344, lng: -76.145697}},
            {id: 2, title: 'Mattydale Fire Department', location: {lat: 43.098172, lng: -76.142189}},
            {id: 3, title: 'Original Italian Pizza', location: {lat: 43.098854, lng:  -76.144700}},
            {id: 4, title: 'Roxboro Road Middle School', location: {lat: 43.101110, lng: -76.150901}},
            {id: 5, title: 'Big Lots', location: {lat: 43.101400, lng: -76.146985}},
            {id: 6, title: 'Camnel pub', location: {lat: 43.098670, lng: -76.145832}}
        ]),
        markers:[],
        textFilter: ko.observable(),
        filterLocations: ko.dependentObservable(function () {
                            return ko.utils.arrayFilter(app.locations(), function (loc) {
                                return loc.title().toLowerCase().includes(app.textFilter().toLowerCase());
                            });
                        })
     };

    ko.applyBindings(app);
})();

The error in the chrome console is:

Uncaught TypeError: Cannot read property 'locations' of undefined

Body:
You can't use 'app' var because you're still creating it.

var app = {...

    ^^^    return ko.utils.arrayFilter(app.locations(), ...

                                       ^^^


问:
find files by extension, *.html under a folder in nodejs
I'd like to find all *.html files in src folder and all its sub folders using nodejs. What is the best way to do it? </p>

```<code>var folder = '/project1/src';
var extension = 'html';
var cb = function(err, results) {
   // results is an array of the files with path relative to the folder
   console.log(results);

}
// This function is what I am looking for. It has to recursively traverse all sub folders.
findFiles(folder, extension, cb);
</code>```

<p>I think a lot developers should have great and tested solution and it is better to use it than writing one myself. </p>

答:
my two pence, using map in place of for-loop</p>

```<code>var path = require('path'), fs = require('fs');

var findFiles = function(folder, pattern = /.*/, callback) {
  var flist = [];

  fs.readdirSync(folder).map(function(e){
    var fname = path.join(folder, e);
    var fstat = fs.lstatSync(fname);
    if (fstat.isDirectory()) {
      // don't want to produce a new array with concat
      Array.prototype.push.apply(flist, findFiles(fname, pattern, callback));
    } else {
      if (pattern.test(fname)) {
        flist.push(fname);
        if (callback) {
          callback(fname);
        }
      }
    }
  });
  return flist;
};

// HTML files
var html_files = findFiles(myPath, /\.html$/, function(o) { console.log('look what we have found : ' + o} );

// All files
var all_files = findFiles(myPath);
</code>```

Body:
I'd like to find all *.html files in src folder and all its sub folders using nodejs. What is the best way to do it?

var folder = '/project1/src';
var extension = 'html';
var cb = function(err, results) {
   // results is an array of the files with path relative to the folder
   console.log(results);

}
// This function is what I am looking for. It has to recursively traverse all sub folders.
findFiles(folder, extension, cb);

I think a lot developers should have great and tested solution and it is better to use it than writing one myself.

Body:
my two pence, using map in place of for-loop

var path = require('path'), fs = require('fs');

var findFiles = function(folder, pattern = /.*/, callback) {
  var flist = [];

  fs.readdirSync(folder).map(function(e){
    var fname = path.join(folder, e);
    var fstat = fs.lstatSync(fname);
    if (fstat.isDirectory()) {
      // don't want to produce a new array with concat
      Array.prototype.push.apply(flist, findFiles(fname, pattern, callback));
    } else {
      if (pattern.test(fname)) {
        flist.push(fname);
        if (callback) {
          callback(fname);
        }
      }
    }
  });
  return flist;
};

// HTML files
var html_files = findFiles(myPath, /\.html$/, function(o) { console.log('look what we have found : ' + o} );

// All files
var all_files = findFiles(myPath);


问:
Javafx : ScrollPane in SplitPane cannot scroll
I have many panes in my .fxml file ( here is the earlier version of my fxml: Javafx : SplitPane resize children) Now I want to fix the first two elements in the split pane in the top of my view, so I put them out of the ScrollPane but now the problem is that I cannot scroll the rest of the panes, and I have no idea why. I tried to wrap them into a BorderPane, another try was that to wrap them in a SplitPane so the those two panes become items in the SplitPane and the third item is the ScrollPane but none of the worked. Do you have any idea what did I miss, or any solution for this problem?

Edit : So here is the code that I have tried, so I put the first two elements out of ScrollPane

```<code><TitledPane>
        <TextArea fx:id="taTop" wrapText="true" editable="false" prefHeight="100"/>
</TitledPane>
<TitledPane>
        <TableView fx:id="tableFrist" minHeight="120" maxHeight="120">
            <columns>
                <TableColumn fx:id="column" prefWidth="200"/>
            </columns>
        </TableView>
</TitledPane>
<ScrollPane AnchorPane.topAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0"
        AnchorPane.leftAnchor="0.0">
    <SplitPane orientation="VERTICAL" fx:id="splitPane">
        <TitledPane>
            <TreeTableView fx:id="tableSecond">
                <columns>
                    <TreeTableColumn fx:id="columnTreeS" prefWidth="200"/>
                </columns>
            </TreeTableView>
        </TitledPane>
        <TitledPane>
            <TreeTableView fx:id="tableThird">
                <columns>
                    <TreeTableColumn fx:id="columnTreeT" prefWidth="200"/>
                </columns>
            </TreeTableView>
        </TitledPane>
        <TitledPane>
            <TextArea fx:id="taBot" wrapText="true" editable="false"/>
        </TitledPane>
    </SplitPane>
</ScrollPane>
</code>```

Expanded state:

Collapsed state:

So when I expand all panes there is no scrollbar so I cannot scroll down to the other panes.

答:
I have found the solution, in my controller class i have inserted this line:
scrollPane.prefHeightProperty().bind(contentPane.heightProperty());
and it solved my problem, I guess the ScrollPane had Infinite height so the scrollbar had never sown.

Body:
I have many panes in my .fxml file ( here is the earlier version of my fxml: Javafx : SplitPane resize children) Now I want to fix the first two elements in the split pane in the top of my view, so I put them out of the ScrollPane but now the problem is that I cannot scroll the rest of the panes, and I have no idea why. I tried to wrap them into a BorderPane, another try was that to wrap them in a SplitPane so the those two panes become items in the SplitPane and the third item is the ScrollPane but none of the worked. Do you have any idea what did I miss, or any solution for this problem?

Edit : So here is the code that I have tried, so I put the first two elements out of ScrollPane

<TitledPane>
        <TextArea fx:id="taTop" wrapText="true" editable="false" prefHeight="100"/>
</TitledPane>
<TitledPane>
        <TableView fx:id="tableFrist" minHeight="120" maxHeight="120">
            <columns>
                <TableColumn fx:id="column" prefWidth="200"/>
            </columns>
        </TableView>
</TitledPane>
<ScrollPane AnchorPane.topAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.bottomAnchor="0.0"
        AnchorPane.leftAnchor="0.0">
    <SplitPane orientation="VERTICAL" fx:id="splitPane">
        <TitledPane>
            <TreeTableView fx:id="tableSecond">
                <columns>
                    <TreeTableColumn fx:id="columnTreeS" prefWidth="200"/>
                </columns>
            </TreeTableView>
        </TitledPane>
        <TitledPane>
            <TreeTableView fx:id="tableThird">
                <columns>
                    <TreeTableColumn fx:id="columnTreeT" prefWidth="200"/>
                </columns>
            </TreeTableView>
        </TitledPane>
        <TitledPane>
            <TextArea fx:id="taBot" wrapText="true" editable="false"/>
        </TitledPane>
    </SplitPane>
</ScrollPane>

Expanded state:

Collapsed state:

So when I expand all panes there is no scrollbar so I cannot scroll down to the other panes.


问:
Java Base64 MIME decoding/encoding throws away delimiters
I have a Base64-encoded string that looks like "data:image/png;base64,iVBORw0K". I'm trying to decode it back to binary and later encode it again into Base64 using java.util.Base64. Strangely, after decoding and encoding again, I would lose the delimiters and get back "dataimage/pngbase64iVBORw0I=".

This is how I do the decoding and encoding (written in Scala, but you get the idea):

```<code>import java.util.Base64

val b64mime = "data:image/png;base64,iVBORw0K"

val decoder = Base64.getMimeDecoder
val encoder = Base64.getMimeEncoder

println(encoder.encodeToString(decoder.decode(b64mime)))
</code>```

Here is an example: https://scalafiddle.io/sf/TJY7eeg/0

This also happens with javax.xml.bind.DatatypeConverter. What am I doing wrong? Is this the expected behavior?

答:
Base64 doesnt have those characters in it. It looks like the decoder is ignoring those invalid characters.

```<code>@ decoder.decode(";")
res10: Array[Byte] = Array()
</code>```

However if you just decode the last part you get what you want.

```<code>@ decoder.decode("iVBORw0K")
res9: Array[Byte] = Array(-119, 80, 78, 71, 13, 10)
@ encoder.encodeToString(res9)
res12: String = "iVBORw0K"
</code>```

Body:
I have a Base64-encoded string that looks like "data:image/png;base64,iVBORw0K". I'm trying to decode it back to binary and later encode it again into Base64 using java.util.Base64. Strangely, after decoding and encoding again, I would lose the delimiters and get back "dataimage/pngbase64iVBORw0I=".

This is how I do the decoding and encoding (written in Scala, but you get the idea):

import java.util.Base64

val b64mime = "data:image/png;base64,iVBORw0K"

val decoder = Base64.getMimeDecoder
val encoder = Base64.getMimeEncoder

println(encoder.encodeToString(decoder.decode(b64mime)))

Here is an example: https://scalafiddle.io/sf/TJY7eeg/0

This also happens with javax.xml.bind.DatatypeConverter. What am I doing wrong? Is this the expected behavior?

Body:
Base64 doesnt have those characters in it. It looks like the decoder is ignoring those invalid characters.

@ decoder.decode(";")
res10: Array[Byte] = Array()

However if you just decode the last part you get what you want.

@ decoder.decode("iVBORw0K")
res9: Array[Byte] = Array(-119, 80, 78, 71, 13, 10)
@ encoder.encodeToString(res9)
res12: String = "iVBORw0K"


问:
How can I make my html td elements fit to changing window sizes?
```<code>**THIS IS MY HTML**

<div class="table">
<table>
<tr>
<td><a href="otherpage.html">Home</a></td>
<td><a href="otherpage.html">About us</a></td>
<td><a href="otherpage.html">Testimonials</a></td>
<td><a href="otherpage.html">Contact us</a></td>
<tr>
</table>
</div>
</code>```

THIS IS MY CSS

```<code>html,body{
margin:0;
height:100%;
background: linear-gradient(red,pink);
}
.table{
background-color:black;
margin:0;
}
td,a{
padding:25px;
margin:80px;
}
</code>```

When I make the window size smaller, some of the text in td goes to the next line. How to I make that stop?

This is normal:

This is after I reduce window size:

答:
html,body{ margin:0; height:100%; background: linear-gradient(red,pink); } .table{ background-color:black; margin:0; } td,a{ padding:20px;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="table">
<table>
<tr>
<td>Home</td>
<td>About us</td>
<td>Testimonials</td>
<td>Contact us</td>
<tr>
</table>
</div></code>```

Body:
**THIS IS MY HTML**

Home
About us
Testimonials
Contact us

THIS IS MY CSS

html,body{
margin:0;
height:100%;
background: linear-gradient(red,pink);
}
.table{
background-color:black;
margin:0;
}
td,a{
padding:25px;
margin:80px;
}

When I make the window size smaller, some of the text in td goes to the next line. How to I make that stop?

This is normal:

This is after I reduce window size:

Body:
html,body{ margin:0; height:100%; background: linear-gradient(red,pink); } .table{ background-color:black; margin:0; } td,a{ padding:20px;  }

<div class="table">
<table>
<tr>
<td><a href="otherpage.html">Home</a></td>
<td><a href="otherpage.html">About us</a></td>
<td><a href="otherpage.html">Testimonials</a></td>
<td><a href="otherpage.html">Contact us</a></td>
<tr>
</table>
</div>


问:
STUN/TURN server connectivity test
I am trying to figure out how to test whether a STUN/TURN server is alive and properly responding to connections. Ideally this test would be performed from an external machine, just in case the STUN/TURN machine is down for this case should also be reported by the connectivity test.

Has anyone looked into this case in the past? What solutions would be recommended?

答:
You could set up a 3rd party monitoring service (we use Monitis) or even your own machine to PING the server every minute from 1 or more locations. However this will only tell you if the server is reachable and not necessarily if the TURN/STUN application server still accepts & responds to TURN/STUN packets.

A server side monitoring library for STUN/TURN would make a great GitHub project.

Title: STUN/TURN server connectivity test


问:
module.exports = Promise.all not working inside tests
I want to just make sure that my server is running before I create PR's locally to test that nothing is broken.

worker.js

My server exports a promise

```<code>module.exports = Promise.all([
    hbsPartialsLoaded,
])
.then(() => {
    let server;

    if (!isTestEnvironment) {
        server = app.listen(config.port);
    }

    return { server, app };
});
</code>```

tests

```<code>let { expect, request } = require('chai')
    .use(require('chai-http'))
    .use(require('chai-cheerio'));
const config = require('../../app/config');
const worker = require('../../app/worker');

describe('server response', function () {
    worker.then(() => {
        before(function () {
            server.listen(config.port);
        });

        it('should return 200', function (done) {
            request.get(`http://localhost:${config.port}`, function (err, res, body){
                expect(res.statusCode).to.equal(200);
                done();
            });
        });

        after(function () {
            worker.close();
        });
    })
});
</code>```

Running Tests

```<code> NODE_ENV=test mocha --timeout 20000 --recursive test/ --compilers js:babel-core/register

  0 passing (1ms)
</code>```

My tests are never run. How can I get it so I wait for sever.js to finish its promises before the tests are run?

答:
it() functions should be called directly inside describe(). Nested inside a promise doesn't read well nor follow the standard testing process

```<code>let { expect, request } = require('chai')
    .use(require('chai-http'))
    .use(require('chai-cheerio'));
const config = require('../../app/config');
const worker = require('../../app/worker');

describe('server response', function () {
    before(function () {
        server.listen(config.port);
    });

    it('should return 200', function (done) {
        worker.then(() => {
            request.get(`http://localhost:${config.port}`, function (err, res, body){
                expect(res.statusCode).to.equal(200);
                done();
            });
        })
    });

    after(function () {
        worker.close();
    });
});
</code>```

Body:
I want to just make sure that my server is running before I create PR's locally to test that nothing is broken.

worker.js

My server exports a promise

module.exports = Promise.all([
    hbsPartialsLoaded,
])
.then(() => {
    let server;

    if (!isTestEnvironment) {
        server = app.listen(config.port);
    }

    return { server, app };
});

tests

let { expect, request } = require('chai')
    .use(require('chai-http'))
    .use(require('chai-cheerio'));
const config = require('../../app/config');
const worker = require('../../app/worker');

describe('server response', function () {
    worker.then(() => {
        before(function () {
            server.listen(config.port);
        });

        it('should return 200', function (done) {
            request.get(`http://localhost:${config.port}`, function (err, res, body){
                expect(res.statusCode).to.equal(200);
                done();
            });
        });

        after(function () {
            worker.close();
        });
    })
});

Running Tests

 NODE_ENV=test mocha --timeout 20000 --recursive test/ --compilers js:babel-core/register

  0 passing (1ms)

My tests are never run. How can I get it so I wait for sever.js to finish its promises before the tests are run?

Body:
it() functions should be called directly inside describe(). Nested inside a promise doesn't read well nor follow the standard testing process

let { expect, request } = require('chai')
    .use(require('chai-http'))
    .use(require('chai-cheerio'));
const config = require('../../app/config');
const worker = require('../../app/worker');

describe('server response', function () {
    before(function () {
        server.listen(config.port);
    });

    it('should return 200', function (done) {
        worker.then(() => {
            request.get(`http://localhost:${config.port}`, function (err, res, body){
                expect(res.statusCode).to.equal(200);
                done();
            });
        })
    });

    after(function () {
        worker.close();
    });
});


问:
indy GET dowloading speed
Welcome,

I have to create caption with information about downloading speed in my application using indy http get compontent.

In my mind i found simple solution.

At onwork event i will get actual progress of downloading (size) and compare it with previous reading. (for example every 5 seconds).  curent size minus previous (5 seconds eariel, stored in global var) divide by 5 seconds * 8  and i will get speed.
If actual size is equal previous then sped is always 0.

So i want start codding, but i found problem in simple function called odwork.

```
procedure TForm1.HttpWork(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
  begin
    showmessage('hello im herre');
end;
```

Problem is, that function isnt called...
I don't know why.

I'm downloading 100 MB file, and i cant see any showmessage...

Have any idea ?
Regards

答: The OnWork... events are only fired if the connection's BeginWork() method has been called beforehand.  Many of Indy's reading/writing methods do not call that automatically.  However, TIdHTTP reads/writes request/response body data using TStream objects, and the connection's read/write TStream methods do call BeginWork() internally, so you will definately get OnWork... events fired during HTTP operations.</p>

Title: indy GET dowloading speed

Body:
Welcome,

I have to create caption with information about downloading speed in my application using indy http get compontent.

In my mind i found simple solution.

At onwork event i will get actual progress of downloading (size) and compare it with previous reading. (for example every 5 seconds).  curent size minus previous (5 seconds eariel, stored in global var) divide by 5 seconds * 8  and i will get speed.
If actual size is equal previous then sped is always 0.

So i want start codding, but i found problem in simple function called odwork.

procedure TForm1.HttpWork(ASender: TObject; AWorkMode: TWorkMode;
  AWorkCount: Int64);
  begin
    showmessage('hello im herre');
end;

Problem is, that function isnt called...
I don't know why.

I'm downloading 100 MB file, and i cant see any showmessage...

Have any idea ?
Regards


问:
Monthly interval between two date
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

```<code>2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28
</code>```

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

```<code>foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}
</code>```

The code for RecuperoDate is:

```<code>public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)
</code>```

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:

答:
```<code>public List<string> GetIntervals(DateTime startDate, DateTime endDate) {
    List<string> result = new List<string>();
    result.Add(startDate.ToShortDateString());
    result.Add(endDate.ToShortDateString());
    DateTime target = startDate;
    while (target <= endDate) {
        result.Add(new DateTime(target.Year, target.Month, DateTime.DaysInMonth(target.Year, target.Month)).ToShortDateString());
        target = target.AddMonths(1);
    }
    result = result.Distinct().ToList();
    result.Sort();
    return result;
}
</code>```

Title: Monthly interval between two date

Body:
I have two dates like 2017-10-05 and 2018-02-20, my interval result should be:

2017-10-05
2017-10-31
2017-11-30
2017-12-31
2018-01-31
2018-02-20
2018-02-28

Any suggestions to do this in C# using DateTime object?

UPDATE #1

The problem I mentioned first concerns is a real situation of a cash flow management, so I had to change dates specifications for the calculation of interest, dif and civ. This code i use for the purpose:

foreach (DataRow dr in DTFlussi.Rows)
{
    DateTime d1 = Convert.ToDateTime(DTFlussi.Rows[n]["data_scadenza"]).Date;
    DateTime d2 = Convert.ToDateTime(DTFlussi.Rows[n + 1]["data_scadenza"]).Date;
    int[] date = RecuperoDate(d1, d2);

    if (saldoConto > 0)
        InteressiAttivi(saldoConto, date, DTOneri, d1, d2);
    else if (saldoConto <= 0 && saldoConto >= (fidoConto * -1))
    {
        //esempio di interessi FIDO al 2%
        InteressiFido(saldoConto, date, tassoFIDO, DTOneri, d1, d2);
    }
    else if (saldoConto < 0 && saldoConto < (fidoConto * -1))
    {
        //esempio con interessi FIDO al 2% e interessi EXTRAFIDO al 4%
        InteressiExtraFido(saldoConto, fidoConto, date, tassoFIDO, tassoEXTRAFIDO, DTOneri, d1, d2);
    }
    catch (Exception)
    {

    }
    n++;
}

The code for RecuperoDate is:

public int[] RecuperoDate(DateTime d1, DateTime d2)
{
    int[] diff = new int[2];

    //Gestione anno bisestile Febbrario
    int giorniFebbraio = 0;
    if (DateTime.IsLeapYear(d1.Year))
        giorniFebbraio = 29;
    else
        giorniFebbraio = 28;

    try
    {
        #region MESE 1

        if (d1.Date >= new DateTime(d1.Year, 1, 1) && d1.Date <= new DateTime(d1.Year, 1, 31) && d2.Date >= new DateTime(d1.Year, 1, 31))
        {
            DateTime Mese1 = new DateTime(d1.Year, 1, 31).Date;
            diff[0] = (int)(Mese1 - d1).TotalDays;
            diff[1] = (int)(d2 - Mese1).TotalDays;
        }

        #endregion

        //NOTE: incomplete code because is the same thing for the other months (February - December)

This is necessary to obtain subsequent variations in the balance and at the end of the calculations this is what I want:


问:
Is there a way to replace all nulls in a table at once?
If I have a table like this:

How might I replace all nulls with blanks at once?

I'd prefer a solution that dynamically accounts for column names, to account for more or less columns and differing column names. So Table.ReplaceValue(#"Changed Type",null,"",Replacer.ReplaceValue,{"Column1", "Column2", "Column3", "Column4"}) would not be what I'm after.

I'm thinking the solution would rely on somehow using something like{Table.ColumnNames(tablename here)} in place of {"Column1", "Column2", "Column3", "Column4"}but when I try that, I get an error:

I'm sure I just don't understand the proper syntax. I'll certainly appreciate your help.

答:
I think I just figured it out. I needed to drop the brackets.
I changed...

Table.ReplaceValue(#"Added Custom",null,"",Replacer.ReplaceValue,{Table.ColumnNames(#"Changed Type")})

to...

Table.ReplaceValue(#"Added Custom",null,"",Replacer.ReplaceValue,Table.ColumnNames(#"Changed Type"))

and it seemed to work.


问:
XSLT stylesheet to convert Graphml to SVG
I am having more trouble than expected to find an XSLT stylesheet that converts a  simple Graphml document to an SVG diagram. I've searched quite widely, and so far I have only partial success. Here's my input Graphml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<graph id="G" edgedefault="directed">
  <node id="d1e2"/>
  <node id="d1e4"/>
  <node id="d1e7"/>
  <node id="d1e9"/>
  <node id="d1e11"/>
  <node id="d1e14"/>
  <node id="d1e17"/>
  <node id="d1e21"/>
  <node id="d1e23"/>
  <node id="d1e26"/>
  <node id="d1e29"/>
  <node id="d1e33"/>
  <node id="d1e35"/>
  <node id="d1e38"/>
  <node id="d1e41"/>
  <edge source="d1e2" target="d1e4"/>
  <edge source="d1e2" target="d1e7"/>
  <edge source="d1e7" target="d1e9"/>
  <edge source="d1e9" target="d1e11"/>
  <edge source="d1e9" target="d1e14"/>
  <edge source="d1e9" target="d1e17"/>
  <edge source="d1e7" target="d1e21"/>
  <edge source="d1e21" target="d1e23"/>
  <edge source="d1e21" target="d1e26"/>
  <edge source="d1e21" target="d1e29"/>
  <edge source="d1e7" target="d1e33"/>
  <edge source="d1e33" target="d1e35"/>
  <edge source="d1e33" target="d1e38"/>
  <edge source="d1e33" target="d1e41"/>
</graph>
</graphml>
</code>```

and here's my stylesheet (from http://www.svgopen.org/2003//papers/ComparisonXML2SVGTransformationMechanisms/index.html#S2). Note that I have temporarily disabled edge processing to focus on the placement of the nodes:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/2000/svg">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <!-- for a 'graph' element, creates an 'svg' element -->
  <xsl:template match="graph">
  <!-- first give a CSS reference for the generated SVG -->
    <xsl:processing-instruction name="xml-stylesheet">type="text/css" href="default.css"</xsl:processing-instruction>
    <svg>
      <!-- defs section for the arrow -->
      <!-- ... -->
      <!-- recurse 'node' elements of the graph to find graph root -->
      <xsl:apply-templates select="node"/>
    </svg>
  </xsl:template>

  <!-- recurse 'node' element to find graph root -->
  <xsl:template match="node">
    <!-- check if the first 'edge' has current 'node' as target -->
    <xsl:apply-templates select="../edge[1]">
       <xsl:with-param name="n" select="."/>
    </xsl:apply-templates>
  </xsl:template>

  <!-- check if a 'node' ($n) is a target of the current 'edge' -->
  <xsl:template match="edge">
    <xsl:param name="n">null</xsl:param>
    <!-- if the 'node' is not a target of the current 'edge' -->
    <xsl:if test="not(@target=$n/@id)">
      <!-- advance to the next edge -->
      <xsl:apply-templates select="following-sibling::edge[position()=1]">
        <xsl:with-param name="n" select="$n"/>
      </xsl:apply-templates>
      <!-- if all edges have been queried  -->
      <xsl:if test="not(following-sibling::edge[position()=1])">
        <!-- the 'node' ($n) is the root, create it -->
        <xsl:call-template name="create-node">
          <xsl:with-param name="n" select="$n"/>
        </xsl:call-template>
      </xsl:if>
    </xsl:if>
  </xsl:template>

  <!-- transform a 'node' to SVG and recurse through its children -->
  <xsl:template name="create-node">
    <xsl:param name="n">null</xsl:param>
    <xsl:param name="level">0</xsl:param>
    <xsl:param name="count">0</xsl:param>
    <xsl:param name="edge">null</xsl:param>
    <xsl:param name="x1">0</xsl:param>
    <xsl:param name="y1">0</xsl:param>
    <!-- some helpers -->
    <xsl:variable name="side" select="1-2*($count mod 2)"/>
    <xsl:variable name="x" select="$level*150"/>
    <xsl:variable name="y" select="$y1 - 50+$side*ceiling($count div 2)*150"/>
    <!-- create the 'node' itself and position it -->
    <g class="node">
      <rect x="{$x}" y="{$y}" width="100" height="100"/>
      <text text-anchor="middle" x="{$x+50}" y="{$y+55}">
        <xsl:value-of select="$n/@id"/>
      </text>
    </g>
    <!-- if there is an 'edge' ($edge) draw it -->
    <xsl:if test="$edge!='null'">
      <!-- the 'edge' position goes from previous 'node' position to $n one -->
      <!--
      <line class="edge" x1="{$x1}" y1="{$y1}" x2="{$x}" y2="{$y+50}">
        <xsl:attribute name="style">marker-end:url(#arrow)</xsl:attribute>
      </line>
      -->
    </xsl:if>
    <!-- now that the 'node' is created, recurse to children through edges -->
    <xsl:call-template name="query-edge">
      <xsl:with-param name="edge" select="$n/../edge[@source=$n/@id][1]"/>
      <xsl:with-param name="x1" select="$x+100"/>
      <xsl:with-param name="y1" select="$y+50"/>
      <xsl:with-param name="n" select="$n"/>
      <!-- going to the upper level, increment level -->
      <xsl:with-param name="level" select="$level+1"/>
      <!-- going to the first child, set counter to 0 -->
      <xsl:with-param name="count" select="0"/>
    </xsl:call-template>
  </xsl:template>

  <!-- recurse a 'node' ($n) edges to find 'node' children -->
  <xsl:template name="query-edge">
    <xsl:param name="edge">null</xsl:param>
    <xsl:param name="x1">0</xsl:param>
    <xsl:param name="y1">0</xsl:param>
    <xsl:param name="n">null</xsl:param>
    <xsl:param name="level">0</xsl:param>
    <xsl:param name="count">0</xsl:param>
    <xsl:variable name="target" select="$edge/@target"/>
    <!-- if there is an 'edge' -->
    <xsl:if test="$edge!='null'">
      <!-- go down the tree, create the 'node' of the 'edge' target -->
      <xsl:call-template name="create-node">
        <xsl:with-param name="n" select="$edge/../node[@id=$target]"/>
        <xsl:with-param name="level" select="$level"/>
        <xsl:with-param name="count" select="$count"/>
        <xsl:with-param name="edge" select="$edge"/>
        <xsl:with-param name="x1" select="$x1"/>
        <xsl:with-param name="y1" select="$y1"/>
      </xsl:call-template>
      <!-- go to the next 'edge' that has also the 'node' ($n) has source -->
      <xsl:variable name="next-edge" select="$edge/following-sibling::edge[position()=1][@source=$n/@id]"/>
      <xsl:call-template name="query-edge">
       <xsl:with-param name="edge" select="$next-edge"/>
       <xsl:with-param name="x1" select="$x1"/>
       <xsl:with-param name="y1" select="$y1"/>
       <xsl:with-param name="n" select="$n"/>
       <xsl:with-param name="level" select="$level"/>
       <!-- next 'edge', increment counter -->
       <xsl:with-param name="count" select="$count+1"/>
     </xsl:call-template>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>
</code>```

When I run this through Saxon, I get the following SVG file:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
   <?xml-stylesheet type="text/css" href="default.css"?><svg xmlns="http://www.w3.org/2000/svg">
   <g class="node">
      <rect x="0" y="-50" width="100" height="100"/>
      <text text-anchor="middle" x="50" y="5">d1e2</text>
   </g>
   <g class="node">
      <rect x="150" y="-50" width="100" height="100"/>
      <text text-anchor="middle" x="200" y="5">d1e4</text>
   </g>
   <g class="node">
      <rect x="150" y="-200" width="100" height="100"/>
      <text text-anchor="middle" x="200" y="-145">d1e7</text>
   </g>
   <g class="node">
      <rect x="300" y="-200" width="100" height="100"/>
      <text text-anchor="middle" x="350" y="-145">d1e9</text>
   </g>
   <g class="node">
      <rect x="450" y="-200" width="100" height="100"/>
      <text text-anchor="middle" x="500" y="-145">d1e11</text>
   </g>
   <g class="node">
      <rect x="450" y="-350" width="100" height="100"/>
      <text text-anchor="middle" x="500" y="-295">d1e14</text>
   </g>
   <g class="node">
      <rect x="450" y="-50" width="100" height="100"/>
      <text text-anchor="middle" x="500" y="5">d1e17</text>
   </g>
</svg>
</code>```

This is pretty good, but it has lost all of the nodes after the d1e17 node, and I can't work out why.

Can anyone spot the bug in the stylesheet? Or does anyone have a better stylesheet for this purpose?

Thanks for any help, Martin

答:
If you transform your flat list of nodes into a tree first, then you can use the axes to find information about the structure.

Try something like this:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" version="2.0">
  <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

  <xsl:template match="/graphml/graph">

    <!-- Find the root ID -->
    <xsl:variable name="rootId">
      <xsl:for-each select="node">
        <xsl:variable name="nodeId" select="@id"/>
        <xsl:if test="not(../edge[@target=$nodeId])">
          <xsl:value-of select="$nodeId"/>
        </xsl:if>
      </xsl:for-each>
    </xsl:variable>

    <!-- Turn flat list into a tree -->
    <xsl:variable name="tree">
      <xsl:apply-templates select="node[@id=$rootId]"/>
    </xsl:variable>

    <!-- Turn tree into a flat list of svg elements -->
    <svg>
      <g transform="translate(50 50)">
        <xsl:apply-templates select="$tree"/>
      </g>
    </svg>
  </xsl:template>

  <xsl:template match="node">
    <xsl:variable name="nodeId" select="@id"/>
    <xsl:variable name="childIds" select="//edge[@source=$nodeId]/@target"/>
    <treeNode id="{@id}">
      <xsl:apply-templates select="//node[@id=$childIds]"/>
    </treeNode>
  </xsl:template>

  <xsl:template match="svg:treeNode">
    <xsl:variable name="level" select="count(ancestor::*)"/>
    <xsl:variable name="leafChildren" select="count(descendant::*[not(descendant::*)])"/>
    <xsl:variable name="earlierChildren" select="count(preceding::*[not(descendant::*)])"/>
    <xsl:variable name="x" select="100 * $level"/>
    <xsl:variable name="y" select="50 * $earlierChildren + 25 * max((0, $leafChildren - 1))"/>
    <g class="node">
      <circle cx="{$x}" cy="{$y}" r="10"/>
      <text x="{$x - 10}" y="{$y + 25}"><xsl:value-of select="@id"/></text>

      <!-- Draw line to parent -->
      <xsl:if test="$level != 0">
        <xsl:variable name="parentLevel" select="$level - 1"/>
        <xsl:variable name="parentLeafChildren" select="count(../descendant::*[not(descendant::*)])"/>
        <xsl:variable name="parentEarlierChildren" select="count(../preceding::*[not(descendant::*)])"/>
        <xsl:variable name="parentX" select="100 * $parentLevel"/>
        <xsl:variable name="parentY" select="50 * $parentEarlierChildren + 25 * max((0, $parentLeafChildren - 1))"/>
        <path d="M {$parentX} {$parentY} C {$parentX + 50} {$parentY}, {$x - 50} {$y}, {$x} {$y}" stroke="black" fill="transparent" stroke-width="2"/>
      </xsl:if>
    </g>
    <xsl:apply-templates select="child::*"/>
  </xsl:template>

</xsl:stylesheet>
</code>```

Result ist this:

Body:
I am having more trouble than expected to find an XSLT stylesheet that converts a  simple Graphml document to an SVG diagram. I've searched quite widely, and so far I have only partial success. Here's my input Graphml file:

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<graph id="G" edgedefault="directed">
  <node id="d1e2"/>
  <node id="d1e4"/>
  <node id="d1e7"/>
  <node id="d1e9"/>
  <node id="d1e11"/>
  <node id="d1e14"/>
  <node id="d1e17"/>
  <node id="d1e21"/>
  <node id="d1e23"/>
  <node id="d1e26"/>
  <node id="d1e29"/>
  <node id="d1e33"/>
  <node id="d1e35"/>
  <node id="d1e38"/>
  <node id="d1e41"/>
  <edge source="d1e2" target="d1e4"/>
  <edge source="d1e2" target="d1e7"/>
  <edge source="d1e7" target="d1e9"/>
  <edge source="d1e9" target="d1e11"/>
  <edge source="d1e9" target="d1e14"/>
  <edge source="d1e9" target="d1e17"/>
  <edge source="d1e7" target="d1e21"/>
  <edge source="d1e21" target="d1e23"/>
  <edge source="d1e21" target="d1e26"/>
  <edge source="d1e21" target="d1e29"/>
  <edge source="d1e7" target="d1e33"/>
  <edge source="d1e33" target="d1e35"/>
  <edge source="d1e33" target="d1e38"/>
  <edge source="d1e33" target="d1e41"/>
</graph>
</graphml>

and here's my stylesheet (from http://www.svgopen.org/2003//papers/ComparisonXML2SVGTransformationMechanisms/index.html#S2). Note that I have temporarily disabled edge processing to focus on the placement of the nodes:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/2000/svg">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:template match="graph">

    <xsl:processing-instruction name="xml-stylesheet">type="text/css" href="default.css"</xsl:processing-instruction>
    <svg>

      <xsl:apply-templates select="node"/>
    </svg>
  </xsl:template>

  <xsl:template match="node">

    <xsl:apply-templates select="../edge[1]">
       <xsl:with-param name="n" select="."/>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="edge">
    <xsl:param name="n">null</xsl:param>

    <xsl:if test="not(@target=$n/@id)">

      <xsl:apply-templates select="following-sibling::edge[position()=1]">
        <xsl:with-param name="n" select="$n"/>
      </xsl:apply-templates>

      <xsl:if test="not(following-sibling::edge[position()=1])">

        <xsl:call-template name="create-node">
          <xsl:with-param name="n" select="$n"/>
        </xsl:call-template>
      </xsl:if>
    </xsl:if>
  </xsl:template>

  <xsl:template name="create-node">
    <xsl:param name="n">null</xsl:param>
    <xsl:param name="level">0</xsl:param>
    <xsl:param name="count">0</xsl:param>
    <xsl:param name="edge">null</xsl:param>
    <xsl:param name="x1">0</xsl:param>
    <xsl:param name="y1">0</xsl:param>

    <xsl:variable name="side" select="1-2*($count mod 2)"/>
    <xsl:variable name="x" select="$level*150"/>
    <xsl:variable name="y" select="$y1 - 50+$side*ceiling($count div 2)*150"/>

    <g class="node">
      <rect x="{$x}" y="{$y}" width="100" height="100"/>
      <text text-anchor="middle" x="{$x+50}" y="{$y+55}">
        <xsl:value-of select="$n/@id"/>
      </text>
    </g>

    <xsl:if test="$edge!='null'">

    </xsl:if>

    <xsl:call-template name="query-edge">
      <xsl:with-param name="edge" select="$n/../edge[@source=$n/@id][1]"/>
      <xsl:with-param name="x1" select="$x+100"/>
      <xsl:with-param name="y1" select="$y+50"/>
      <xsl:with-param name="n" select="$n"/>

      <xsl:with-param name="level" select="$level+1"/>

      <xsl:with-param name="count" select="0"/>
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="query-edge">
    <xsl:param name="edge">null</xsl:param>
    <xsl:param name="x1">0</xsl:param>
    <xsl:param name="y1">0</xsl:param>
    <xsl:param name="n">null</xsl:param>
    <xsl:param name="level">0</xsl:param>
    <xsl:param name="count">0</xsl:param>
    <xsl:variable name="target" select="$edge/@target"/>

    <xsl:if test="$edge!='null'">

      <xsl:call-template name="create-node">
        <xsl:with-param name="n" select="$edge/../node[@id=$target]"/>
        <xsl:with-param name="level" select="$level"/>
        <xsl:with-param name="count" select="$count"/>
        <xsl:with-param name="edge" select="$edge"/>
        <xsl:with-param name="x1" select="$x1"/>
        <xsl:with-param name="y1" select="$y1"/>
      </xsl:call-template>

      <xsl:variable name="next-edge" select="$edge/following-sibling::edge[position()=1][@source=$n/@id]"/>
      <xsl:call-template name="query-edge">
       <xsl:with-param name="edge" select="$next-edge"/>
       <xsl:with-param name="x1" select="$x1"/>
       <xsl:with-param name="y1" select="$y1"/>
       <xsl:with-param name="n" select="$n"/>
       <xsl:with-param name="level" select="$level"/>

       <xsl:with-param name="count" select="$count+1"/>
     </xsl:call-template>
    </xsl:if>
  </xsl:template>
</xsl:stylesheet>

When I run this through Saxon, I get the following SVG file:

    <?xml version="1.0" encoding="UTF-8"?>
   <?xml-stylesheet type="text/css" href="default.css"?><svg xmlns="http://www.w3.org/2000/svg">
   <g class="node">
      <rect x="0" y="-50" width="100" height="100"/>
      <text text-anchor="middle" x="50" y="5">d1e2</text>
   </g>
   <g class="node">
      <rect x="150" y="-50" width="100" height="100"/>
      <text text-anchor="middle" x="200" y="5">d1e4</text>
   </g>
   <g class="node">
      <rect x="150" y="-200" width="100" height="100"/>
      <text text-anchor="middle" x="200" y="-145">d1e7</text>
   </g>
   <g class="node">
      <rect x="300" y="-200" width="100" height="100"/>
      <text text-anchor="middle" x="350" y="-145">d1e9</text>
   </g>
   <g class="node">
      <rect x="450" y="-200" width="100" height="100"/>
      <text text-anchor="middle" x="500" y="-145">d1e11</text>
   </g>
   <g class="node">
      <rect x="450" y="-350" width="100" height="100"/>
      <text text-anchor="middle" x="500" y="-295">d1e14</text>
   </g>
   <g class="node">
      <rect x="450" y="-50" width="100" height="100"/>
      <text text-anchor="middle" x="500" y="5">d1e17</text>
   </g>
</svg>

This is pretty good, but it has lost all of the nodes after the d1e17 node, and I can't work out why.

Can anyone spot the bug in the stylesheet? Or does anyone have a better stylesheet for this purpose?

Thanks for any help, Martin

Body:
If you transform your flat list of nodes into a tree first, then you can use the axes to find information about the structure.

Try something like this:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" version="2.0">
  <xsl:output method="xml" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />

  <xsl:template match="/graphml/graph">

    <!-- Find the root ID -->
    <xsl:variable name="rootId">
      <xsl:for-each select="node">
        <xsl:variable name="nodeId" select="@id"/>
        <xsl:if test="not(../edge[@target=$nodeId])">
          <xsl:value-of select="$nodeId"/>
        </xsl:if>
      </xsl:for-each>
    </xsl:variable>

    <!-- Turn flat list into a tree -->
    <xsl:variable name="tree">
      <xsl:apply-templates select="node[@id=$rootId]"/>
    </xsl:variable>

    <!-- Turn tree into a flat list of svg elements -->
    <svg>
      <g transform="translate(50 50)">
        <xsl:apply-templates select="$tree"/>
      </g>
    </svg>
  </xsl:template>

  <xsl:template match="node">
    <xsl:variable name="nodeId" select="@id"/>
    <xsl:variable name="childIds" select="//edge[@source=$nodeId]/@target"/>
    <treeNode id="{@id}">
      <xsl:apply-templates select="//node[@id=$childIds]"/>
    </treeNode>
  </xsl:template>

  <xsl:template match="svg:treeNode">
    <xsl:variable name="level" select="count(ancestor::*)"/>
    <xsl:variable name="leafChildren" select="count(descendant::*[not(descendant::*)])"/>
    <xsl:variable name="earlierChildren" select="count(preceding::*[not(descendant::*)])"/>
    <xsl:variable name="x" select="100 * $level"/>
    <xsl:variable name="y" select="50 * $earlierChildren + 25 * max((0, $leafChildren - 1))"/>
    <g class="node">
      <circle cx="{$x}" cy="{$y}" r="10"/>
      <text x="{$x - 10}" y="{$y + 25}"><xsl:value-of select="@id"/></text>

      <!-- Draw line to parent -->
      <xsl:if test="$level != 0">
        <xsl:variable name="parentLevel" select="$level - 1"/>
        <xsl:variable name="parentLeafChildren" select="count(../descendant::*[not(descendant::*)])"/>
        <xsl:variable name="parentEarlierChildren" select="count(../preceding::*[not(descendant::*)])"/>
        <xsl:variable name="parentX" select="100 * $parentLevel"/>
        <xsl:variable name="parentY" select="50 * $parentEarlierChildren + 25 * max((0, $parentLeafChildren - 1))"/>
        <path d="M {$parentX} {$parentY} C {$parentX + 50} {$parentY}, {$x - 50} {$y}, {$x} {$y}" stroke="black" fill="transparent" stroke-width="2"/>
      </xsl:if>
    </g>
    <xsl:apply-templates select="child::*"/>
  </xsl:template>

</xsl:stylesheet>

Result ist this:


问:
IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section
On attempting to deploy a .net 3.5 website on the default app pool in IIS7 having the framework section set to 4.0, I get the following error.

There is a duplicate
  'system.web.extensions/scripting/scriptResourceHandler' section
  defined.

Commenting off the offending lines didn't help either. Any pointers on what I need to do or look at?

答:
My app was an ASP.Net3.5 app (using version 2 of the framework). When ASP.Net3.5 apps got created Visual Studio automatically added scriptResourceHandler to the web.config. Later versions of .Net put this into the machine.config. If you run your ASP.Net 3.5 app using the version 4 app pool (depending on install order this is the default app pool), you will get this error.

When I moved to using the version 2.0 app pool. The error went away. I then had to deal with the error when serving WCF .svc :

HTTP Error 404.17 - Not Found The requested content appears to be script and will not be served by the static file handler

After some investigation, it seems that I needed to register the WCF handler. using the following steps:

open Visual Studio Command Prompt (as administrator)

navigate to "C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation"

Run servicemodelreg -i


问:
Find years where 22nd March will be a Tuesday
I need to find out in which years between 2017 and 2100 (both inclusive) will the 22nd March be a Tuesday.

I tried using the datetime module but I couldn't figure out how...

Body:
If you want to use the datetime module:

>>> tuesdays = [year for year in range(2017, 2101) if datetime.date(year, 3, 22).weekday() == 1]

>>> tuesdays
[2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095]


问:
Screen shatter animation for Unity / Vuforia AR Mobile App
I am a Unity/Vuforia noob and I am currently building an Augmented Reality app for iOS / Android using C#.

I would like to create a phone / tablet screen shatter animation.

I have used the Unity canvas / panel to create a static image like this:

https://lh3.googleusercontent.com/4E6_yKxtYn4L8-AQRPEReOVNWiBjoMvWIx5rdbC6V44LIw5ABSK57RPuHXAf6rFTtiQ=h900-rw

But I would then like it to animate the glass to fall downwards and then to disappear, like the first effect here:

https://www.youtube.com/watch?v=D6WYsz4iSvQ

I have purchased some breaking glass assets if that helps:

Breakable Glass Complete Solution
https://www.assetstore.unity3d.com/en/#!/content/39717

I cannot get a suitable animation to appear on the canvas / UI?

Is this even possible?

Thanks for any advice.

答: Looks like I have solved this by playing around with the camera location.</p>


问:
Android: Kotlin with Butterknife
I'm trying to use Kotlin with Butterknife for my Android Application.

Here is my build.gradle

```<code>dependencies {
    ...
    compile 'com.jakewharton:butterknife:8.0.1'
    kapt 'com.jakewharton:butterknife-compiler:8.0.1'
}

kapt {
    generateStubs = true
}
</code>```

I also has an EditText and I want to show a message using ButterKnife when it is changed:

```<code>@OnTextChanged(R.id.input)
fun test() {
   toast(1)
}
</code>```

However, nothing happens. I put a breakpoint into the function - and it is not even executed.

P.S: I have heard about kotterknife, however I have seen an example with pure Butterknife.

What am I doing wrong?

答:
Add this in your Project Build.gradle

```<code>buildscript {
ext.kotlin_version = '1.1.2-4'
ext.butterknife_version = '8.6.0'
repositories {
    maven { url 'https://maven.google.com' }
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "com.jakewharton:butterknife-gradle-plugin:$butterknife_version"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
   }
}
</code>```

And in your app Build.Gradle add this.

```<code>    //Butterknife
compile "com.jakewharton:butterknife:$butterknife_version"
kapt "com.jakewharton:butterknife-compiler:$butterknife_version"
</code>```

Title: Android: Kotlin with Butterknife

Body:
I'm trying to use Kotlin with Butterknife for my Android Application.

Here is my build.gradle

dependencies {
    ...
    compile 'com.jakewharton:butterknife:8.0.1'
    kapt 'com.jakewharton:butterknife-compiler:8.0.1'
}

kapt {
    generateStubs = true
}

I also has an EditText and I want to show a message using ButterKnife when it is changed:

@OnTextChanged(R.id.input)
fun test() {
   toast(1)
}

However, nothing happens. I put a breakpoint into the function - and it is not even executed.

P.S: I have heard about kotterknife, however I have seen an example with pure Butterknife.

What am I doing wrong?

Body:
Add this in your Project Build.gradle

buildscript {
ext.kotlin_version = '1.1.2-4'
ext.butterknife_version = '8.6.0'
repositories {
    maven { url 'https://maven.google.com' }
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    classpath "com.jakewharton:butterknife-gradle-plugin:$butterknife_version"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
   }
}

And in your app Build.Gradle add this.

    //Butterknife
compile "com.jakewharton:butterknife:$butterknife_version"
kapt "com.jakewharton:butterknife-compiler:$butterknife_version"