问:
dagre layout draw all nodes in same position when using cy.add
fist of all, let me explain my problem:
I'm using cytoscape to draw a network based on information located in a MySQL database, using Ajax the information is passed from a PHP document to the script, if I use a layout like "circle" everything goes fine, but I need to draw the tree to be readable so I've decided to use "dagre" this is the code:

```<code>$.ajax({
        type: "POST",
        url:"dispositivos.php",
        async: true,
        success:  function(datos){
            var dataJson = eval(datos);
            dibujanodos(dataJson);
          },
        error: function (obj, error, objError){
            //avisar que ocurrió un error
        }

});

$.ajax({
    type: "POST",
    url:"relaciones.php",
    async: true,
    success:  function(datosdos){
        var dataJsondos = eval(datosdos);
        dibujarlineas(dataJsondos);
      },
    error: function (obj, error, objError){
        //avisar que ocurrió un error
    }

});

var cy = cytoscape({
  container: document.getElementById('cy'),

  boxSelectionEnabled: false,
  autounselectify: true,

  layout: {
    name: 'dagre'
  },

  style: [
    {
      selector: 'node',
      style: {
        'content': 'data(id)',
        'text-opacity': 0.5,
        'text-valign': 'center',
        'text-halign': 'right',
        'background-color': '#11479e'
      }
    },

    {
      selector: 'edge',
      style: {
        'width': 4,
        'target-arrow-shape': 'triangle',
        'line-color': '#9dbaea',
        'target-arrow-color': '#9dbaea'
      }
    }
  ],

  elements: {
    nodes: [

      //for (var i = 0; i < Object.keys(datos).length; i++) {
        //      data: { id: datos[i].sn,
          //            etiqueta: "IP: " + datos[i].ip_adress + " Device id: " + datos[i].device_id}
          //    }

        { data: { id: 'n15' } },
        { data: { id: 'n14' } },
        { data: { id: 'n13' } },
        { data: { id: 'n12' } },
        { data: { id: 'n11' } },
    ],
    edges: [
      { data: { source: 'n0', target: 'n1' } },
      { data: { source: 'n1', target: 'n2' } },
      { data: { source: 'n1', target: 'n3' } },
      { data: { source: 'n4', target: 'n5' } },
      { data: { source: 'n4', target: 'n6' } },
      { data: { source: 'n6', target: 'n7' } },
      { data: { source: 'n6', target: 'n8' } },
      { data: { source: 'n8', target: 'n9' } },
      { data: { source: 'n8', target: 'n10' } },
      { data: { source: 'n11', target: 'n12' } },
      { data: { source: 'n12', target: 'n13' } },
      { data: { source: 'n13', target: 'n14' } },
      { data: { source: 'n13', target: 'n15' } },
    ]
  },
});

function dibujanodos(datos){

 for (var i = 0; i < Object.keys(datos).length; i++) {
     cy.add({
         data: { id: datos[i].sn,}
       });
   }
}

function dibujarlineas (datosdos){

  for (var i = 0; i < Object.keys(datosdos).length; i++) {
  var source = datosdos[i].Device_SN_O;
cy.add({
  data: {
      id: datosdos[i].Device_SN_O + datosdos[i].Device_SN_D,
      source: source,
      target: datosdos[i].Device_SN_D,
      etiquetaedge: datosdos[i].Port_ID,
  }
});
}
}
</code>```

In this code, I left some manually added nodes in order to show the problem as you can see it, in the image below nodes created with cy.add function are all in the same position while manually added nodes are ok.

displayed image

Even though all edges and nodes' id are correct, it doesn't look like a tree, once I expand the nodes it looks like this:
expected result

I would like to get this result since the graph is drawn, Any suggestions?

答:
After adding the new nodes, run the layout again</p>

```<code>var layout = cy.makeLayout({ name: 'dagre' });
layout.run();
</code>```

Body:
fist of all, let me explain my problem:
I'm using cytoscape to draw a network based on information located in a MySQL database, using Ajax the information is passed from a PHP document to the script, if I use a layout like "circle" everything goes fine, but I need to draw the tree to be readable so I've decided to use "dagre" this is the code:

$.ajax({
        type: "POST",
        url:"dispositivos.php",
        async: true,
        success:  function(datos){
            var dataJson = eval(datos);
            dibujanodos(dataJson);
          },
        error: function (obj, error, objError){
            //avisar que ocurrió un error
        }

});

$.ajax({
    type: "POST",
    url:"relaciones.php",
    async: true,
    success:  function(datosdos){
        var dataJsondos = eval(datosdos);
        dibujarlineas(dataJsondos);
      },
    error: function (obj, error, objError){
        //avisar que ocurrió un error
    }

});

var cy = cytoscape({
  container: document.getElementById('cy'),

  boxSelectionEnabled: false,
  autounselectify: true,

  layout: {
    name: 'dagre'
  },

  style: [
    {
      selector: 'node',
      style: {
        'content': 'data(id)',
        'text-opacity': 0.5,
        'text-valign': 'center',
        'text-halign': 'right',
        'background-color': '#11479e'
      }
    },

    {
      selector: 'edge',
      style: {
        'width': 4,
        'target-arrow-shape': 'triangle',
        'line-color': '#9dbaea',
        'target-arrow-color': '#9dbaea'
      }
    }
  ],

  elements: {
    nodes: [

      //for (var i = 0; i < Object.keys(datos).length; i++) {
        //      data: { id: datos[i].sn,
          //            etiqueta: "IP: " + datos[i].ip_adress + " Device id: " + datos[i].device_id}
          //    }

        { data: { id: 'n15' } },
        { data: { id: 'n14' } },
        { data: { id: 'n13' } },
        { data: { id: 'n12' } },
        { data: { id: 'n11' } },
    ],
    edges: [
      { data: { source: 'n0', target: 'n1' } },
      { data: { source: 'n1', target: 'n2' } },
      { data: { source: 'n1', target: 'n3' } },
      { data: { source: 'n4', target: 'n5' } },
      { data: { source: 'n4', target: 'n6' } },
      { data: { source: 'n6', target: 'n7' } },
      { data: { source: 'n6', target: 'n8' } },
      { data: { source: 'n8', target: 'n9' } },
      { data: { source: 'n8', target: 'n10' } },
      { data: { source: 'n11', target: 'n12' } },
      { data: { source: 'n12', target: 'n13' } },
      { data: { source: 'n13', target: 'n14' } },
      { data: { source: 'n13', target: 'n15' } },
    ]
  },
});

function dibujanodos(datos){

 for (var i = 0; i < Object.keys(datos).length; i++) {
     cy.add({
         data: { id: datos[i].sn,}
       });
   }
}

function dibujarlineas (datosdos){

  for (var i = 0; i < Object.keys(datosdos).length; i++) {
  var source = datosdos[i].Device_SN_O;
cy.add({
  data: {
      id: datosdos[i].Device_SN_O + datosdos[i].Device_SN_D,
      source: source,
      target: datosdos[i].Device_SN_D,
      etiquetaedge: datosdos[i].Port_ID,
  }
});
}
}

In this code, I left some manually added nodes in order to show the problem as you can see it, in the image below nodes created with cy.add function are all in the same position while manually added nodes are ok.

displayed image

Even though all edges and nodes' id are correct, it doesn't look like a tree, once I expand the nodes it looks like this:
expected result

I would like to get this result since the graph is drawn, Any suggestions?

Body:
After adding the new nodes, run the layout again

var layout = cy.makeLayout({ name: 'dagre' });
layout.run();


来源: stackexchange

问:
php: wanted to replace '\\\/' from string
I wanted to replace en/us with es/es:</p>

```<code><?php

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');

$json = json_encode($str);

$str = str_replace('en\/us', 'es\/es', $json);

echo $str;
</code>```

答:
Try this

```<code>$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str['url']=str_replace('en\/us', 'es\/es', $str['url']);
$json = json_encode($str);
</code>```

It produce out put as

It will work for you.

ContentLicense: CC BY-SA 3.0

Body:
I wanted to replace en/us with es/es:

<?php

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');

$json = json_encode($str);

$str = str_replace('en\/us', 'es\/es', $json);

echo $str;

Body:
Try this

$str = array('url'=>'www.domain.com\/data\/en\/us\/data.gif');
$str['url']=str_replace('en\/us', 'es\/es', $str['url']);
$json = json_encode($str);

It produce out put as

It will work for you.


问:
If TRUE in one column, change value in other column
I have a character vector: (shortened version shown)

```<code>Unit <- c("e10", "e11", "10e10", "10e11")
</code>```

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

```<code>"10e10" "10e11" "10e10" "10e11"
</code>```

I used startsWith() to create a TRUE/FALSE vector:

```<code>startsWith.e <- startsWith(Unit, "e")
</code>```

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

```<code>while(startsWith.e){
grep("e", "10e", Unit) }
</code>```

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

答:
If you want to use for, like this (but this is longer version of lmo's answer):

```<code>Unit <- c("e10", "e11", "10e10", "10e11")
startsWith.e <- startsWith(Unit, "e")
for (i in 1:length(Unit)) {
 if (startsWith.e[i]) {
    Unit[i] <- paste0("10", Unit[i])
  }
}
Unit
#> [1] "10e10" "10e11" "10e10" "10e11"
</code>```

Body:
I have a character vector: (shortened version shown)

Unit <- c("e10", "e11", "10e10", "10e11")

I want to apply the following condition: if the value start with 'e', replace 'e' with '10e' so that the final vector will look something like this:

"10e10" "10e11" "10e10" "10e11"

I used startsWith() to create a TRUE/FALSE vector:

startsWith.e <- startsWith(Unit, "e")

This gives TRUE TRUE FALSE FALSE.

Lastly, I want to run a for or while loop (or some kind of conditional), so that when startsWith.e is TRUE, values 'e' in Unit are replaced with '10e'.

while(startsWith.e){
grep("e", "10e", Unit) }

However, I get stuck in an infinite loop and using an if statement says it will only evaluate the first statement (and therefore change all cases because it will evaluate TRUE).

Hope someone can help!

Body:
If you want to use for, like this (but this is longer version of lmo's answer):

Unit <- c("e10", "e11", "10e10", "10e11")
startsWith.e <- startsWith(Unit, "e")
for (i in 1:length(Unit)) {
 if (startsWith.e[i]) {
    Unit[i] <- paste0("10", Unit[i])
  }
}
Unit
#> [1] "10e10" "10e11" "10e10" "10e11"


问:
How to return values from function - React native
How to return a boolean value from react native function?</p>

答:
it can be accomplish like this:

```<code>export function isJson(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}
</code>```

This function checks whether provided value is valid JSON or not.

Body:
it can be accomplish like this:

export function isJson(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
}

This function checks whether provided value is valid JSON or not.


问:
Multiple $scope.$watch not working in Angular JS
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)</p>

```<code>$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});
</code>```

答:
Try this syntax and see what you will get in the console

```<code>$scope.$watch('id', function(newVal, oldVal) {
    console.log(oldVal, newVal);
});
</code>```

if log is OK, why dont you try with the newVal like this

```<code>$scope.$watch('id', function(newVal, oldVal) {
    if (newVal !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+newVal+".*'}}";
        fetch2(filter);
    };
});
</code>```

Edited

Body:
Can anyone explain why only the first $watch below is firing within the same controller? Both the inputs are text boxes with each ng-model assigned. (thanks in advance)

$scope.$watch('search', function() {
   if ($scope.watch !== ""){
       var filter = "{'name':{'$regex':'(?i).*"+$scope.search+".*'}}";
       fetch(filter);
      };
});

$scope.$watch('id', function() {
    if ($scope.id !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+$scope.id+".*'}}";
        fetch2(filter);
    };
});

Body:
Try this syntax and see what you will get in the console

$scope.$watch('id', function(newVal, oldVal) {
    console.log(oldVal, newVal);
});

if log is OK, why dont you try with the newVal like this

$scope.$watch('id', function(newVal, oldVal) {
    if (newVal !== ""){
        var filter = "{'id':{'$regex':'(?i).*"+newVal+".*'}}";
        fetch2(filter);
    };
});

Edited


问:
Find and replace all instances of a pattern in a string using Regular Expressions
Using Excel VBA, I'm trying to replace all instances of a simple pattern that looks like this:

```<code>{some text}
</code>```

with some other constant string. So I want to find all the text that is enclosed in curly braces and replace is (with the curly braces) with another string.

I use the following code:

```<code>Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)
</code>```

where qtext and html_input are some strings. But this only replaces the first instance of the pattern.

For example:

```<code>qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
html_input = "I am HTML"
</code>```

And the result should be:

```<code>"yadda yadda I am HTML omtty doom I am HTML loppy loop"
</code>```

But what I get is:

```<code>"yadda yadda I am HTML omtty doom {1:NM:=6/6} loppy loop"
</code>```

What am I missing?

答:
As @SJR said in their comment, you need to set the Global property of the regex object to True. The property is described on MSDN:

Global - A Boolean property that indicates if the regular expression should be tested against all possible matches in a string. By default, Global is set to False.

So in your code becomes:

```<code>Option Explicit

Sub ReplaceText()

    Dim regEx As Object
    Dim qtext As String
    Dim html_input As String

    ' set up regex
    Set regEx = CreateObject("VBScript.RegExp")
    regEx.Pattern = "\{.*?\}"
    regEx.Global = True '<-- set flag to true to replace all occurences of match

    ' input and replacement text
    qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
    html_input = "I am HTML"

    ' do replace
    qtext = regEx.Replace(qtext, html_input)

    ' test output
    MsgBox qtext

End Sub
</code>```

Body:
Using Excel VBA, I'm trying to replace all instances of a simple pattern that looks like this:

{some text}

with some other constant string. So I want to find all the text that is enclosed in curly braces and replace is (with the curly braces) with another string.

I use the following code:

Dim regEx As Object
Set regEx = CreateObject("VBScript.RegExp")
regEx.Pattern = "\{.*?\}"
qtext = regEx.Replace(qtext, html_input)

where qtext and html_input are some strings. But this only replaces the first instance of the pattern.

For example:

qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
html_input = "I am HTML"

And the result should be:

"yadda yadda I am HTML omtty doom I am HTML loppy loop"

But what I get is:

"yadda yadda I am HTML omtty doom {1:NM:=6/6} loppy loop"

What am I missing?

Body:
As @SJR said in their comment, you need to set the Global property of the regex object to True. The property is described on MSDN:

Global - A Boolean property that indicates if the regular expression should be tested against all possible matches in a string. By default, Global is set to False.

So in your code becomes:

Option Explicit

Sub ReplaceText()

    Dim regEx As Object
    Dim qtext As String
    Dim html_input As String

    ' set up regex
    Set regEx = CreateObject("VBScript.RegExp")
    regEx.Pattern = "\{.*?\}"
    regEx.Global = True '<-- set flag to true to replace all occurences of match

    ' input and replacement text
    qtext = "yadda yadda {1:NM:=12.000:0.120} omtty doom {1:NM:=6/6} loppy loop"
    html_input = "I am HTML"

    ' do replace
    qtext = regEx.Replace(qtext, html_input)

    ' test output
    MsgBox qtext

End Sub


问:
saving operators in arrays, error
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

```<code>int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);
</code>```

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!

答:
Firstly, you are trying to use ints and Strings interchangeably, which is not possible in a strongly-typed language such as Java.

Secondly, for this kind of calculator application you should be using a stack. For easiest implementation, have one stack for numbers and one stack for operators.

ContentLicense: CC BY-SA 2.5

Title: saving operators in arrays, error

Body:
To give an idea of what I want elaborate with this code is the following:

Enter two numbers: 10 7

Choose Operator: e.g. (+, - , * and /)

What's 10 * 7?

Correct!

int[] arr = new int[5];

System.out.println("enter two numbers: ");
arr[1] = sc.nextInt();
arr[2] = sc.nextInt();

System.out.println("Choose Operator: ");
arr[3] = sc.nextInt();

int operator = arr[1]+arr[3]+arr[2];

System.out.print("what's "+operator);
int svar = sc.nextInt();

if (svar == operator)
    System.out.println("Correct!");
else
    System.out.println("Wrong - the right answer is "+operator);

Now I'm having a problem with running some aspects within this code. It works fine to compile but each time the program asks for to "choose operator" the compiler responses with the following error:

Exception in thread "main"

java.util.InputMismatchException   at

java.util.Scanner.throwFor(Unknown

Source)    at

java.util.Scanner.next(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)    at

java.util.Scanner.nextInt(Unknown

Source)

at test1.main(test1.java:13)

I wonder how I'm going to deal with this one. But the goal would be to "save" the desired operator, and then put it together with arr[1] and arr[2] (shown in int operator) to "sort of" create this whole mathematical operation. But the error occurs when I choose one particular operator.

I would appreciate some help with this one. Thank you!


问:
How do I mock dom elements when using mocha javascript?
I'm using mocha to test my JavaScript code. The code involves html and css and implements a chat app. As far as I saw, Mocha can test JavaScript functions by matching the expected value to the function's return value.

But what if I want to test functions that don't return a value? Functions that mainly deal with DOM elements. (Like appending an image for example ).

How exactly can I mock DOM elements in mocha and then test if the function succeeds in generating the appropriate DOM elements?

I had looked around and found it was possible with selenium webdriver and jsdom. Is it possible to do this test with mocha alone and no other additional interfaces?

答:
JSDOM is convenient because it allows you to test against a "real" DOM implementation without the overhead of running in a web browser.

If you can run your unit tests inside a browser you can assert against the DOM in the same way:

```<code>describe("the super special button", () => {

  it("adds an image", (done) => {
    const button = document.querySelector(".js-super-special");
    button.click();

    // give the browser a chance to update the DOM
    setTimeout(() => {
      const image = document.querySelector(".js-image")

      // using assertion library, like chai
      expect(image).to.not.beNull();

      // or using a port of Node's `assert` from a bundler like browserify:
      assert(image != null);

      done();
    })
  })
});
</code>```

Body:
JSDOM is convenient because it allows you to test against a "real" DOM implementation without the overhead of running in a web browser.

If you can run your unit tests inside a browser you can assert against the DOM in the same way:

describe("the super special button", () => {

  it("adds an image", (done) => {
    const button = document.querySelector(".js-super-special");
    button.click();

    // give the browser a chance to update the DOM
    setTimeout(() => {
      const image = document.querySelector(".js-image")

      // using assertion library, like chai
      expect(image).to.not.beNull();

      // or using a port of Node's `assert` from a bundler like browserify:
      assert(image != null);

      done();
    })
  })
});


问:
How to remove php code from a string?
I have a string that has php code in it, I need to remove the php code from the string, for example:

```<code><?php $db1 = new ps_DB() ?><p>Dummy</p>
</code>```

Should return
Dummy

And a string with no php for example
Dummy
 should return the same string.

I know this can be done with a regular expression, but after 4h I haven't found a solution.

答:
A simple solution is to explode into arrays using the php tags to remove any content between  and implode back to a string.

```<code>function strip_php($str) {

  $newstr = '';

  //split on opening tag
  $parts = explode('<?',$str);

  if(!empty($parts)) {
      foreach($parts as $part) {

          //split on closing tag
          $partlings =  explode('?>',$part);
          if(!empty($partlings)) {

              //remove content before closing tag
              $partlings[0] = '';
          }

          //append to string
          $newstr .= implode('',$partlings);
      }
  }
  return $newstr;
}
</code>```

This is slower than regex but doesn't require valid html or php; it only requires all php tags to be closed.

For files which don't always include a final closing tag and for general error checking you could count the tags and append a closing tag if it's missing or notify if the opening and closing tags don't add up as expected, e.g. add the code below at the start of the function. This would slow it down a bit more though :)

```<code>  $tag_diff = (substr_count($str,'<?') - (substr_count($str,'?>');

  //Append if there's one less closing tag
  if($tag_diff == 1) $str .= '?>';

  //Parse error if the tags don't add up
  if($tag_diff < 0 || $tag_diff > 1) die('Error: Tag mismatch.
  (Opening minus closing tags = '.$tag_diff.')<br><br>
  Dumping content:<br><hr><br>'.htmlentities($str));
</code>```

Title: How to remove php code from a string?

Body:
I have a string that has php code in it, I need to remove the php code from the string, for example:

<?php $db1 = new ps_DB() ?>
Dummy

Should return
Dummy

And a string with no php for example
Dummy
 should return the same string.

I know this can be done with a regular expression, but after 4h I haven't found a solution.

Body:
A simple solution is to explode into arrays using the php tags to remove any content between  and implode back to a string.

function strip_php($str) {

  $newstr = '';

  //split on opening tag
  $parts = explode('<?',$str);

  if(!empty($parts)) {
      foreach($parts as $part) {

          //split on closing tag
          $partlings =  explode('?>',$part);
          if(!empty($partlings)) {

              //remove content before closing tag
              $partlings[0] = '';
          }

          //append to string
          $newstr .= implode('',$partlings);
      }
  }
  return $newstr;
}

This is slower than regex but doesn't require valid html or php; it only requires all php tags to be closed.

For files which don't always include a final closing tag and for general error checking you could count the tags and append a closing tag if it's missing or notify if the opening and closing tags don't add up as expected, e.g. add the code below at the start of the function. This would slow it down a bit more though :)

  $tag_diff = (substr_count($str,'<?') - (substr_count($str,'?>');

  //Append if there's one less closing tag
  if($tag_diff == 1) $str .= '?>';

  //Parse error if the tags don't add up
  if($tag_diff < 0 || $tag_diff > 1) die('Error: Tag mismatch.
  (Opening minus closing tags = '.$tag_diff.')<br><br>
  Dumping content:<br><hr><br>'.htmlentities($str));


问:
Accessing Collection of DStreams
I am trying to access a collection of filtered DStreams obtained like in the solution to this question: Spark Streaming - Best way to Split Input Stream based on filter Param

I create the Collection as follows:

```<code>val statuCodes = Set("200","500", "404")
    spanTagStream.cache()
    val statusCodeStreams = statuCodes.map(key => key -> spanTagStream.filter(x => x._3.get("http.status_code").getOrElse("").asInstanceOf[String].equals(key)))
</code>```

I try to access statusCodeStreams in the following way:

```<code>for(streamTuple <- statusCodeStreams){
      streamTuple._2.foreachRDD(rdd =>
  rdd.foreachPartition(
      partitionOfRecords =>
        {
            val props = new HashMap[String, Object]()
            props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers)
            props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
              "org.apache.kafka.common.serialization.StringSerializer")
            props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
              "org.apache.kafka.common.serialization.StringSerializer")
            val producer = new KafkaProducer[String,String](props)

            partitionOfRecords.foreach
            {
                 x=>{
                 /* Code Writing to Kafka using streamTuple._1 as the topic-String */
                 }
            }
      })
   )
}
</code>```

When executing this I receive the following error:
java.io.NotSerializableException: Object of org.apache.spark.streaming.kafka010.DirectKafkaInputDStream is being serialized possibly as a part of closure of an RDD operation. This is because the DStream object is being referred to from within the closure. Please rewrite the RDD operation inside this DStream to avoid this. This has been enforced to avoid bloating of Spark tasks with unnecessary objects

How do I access the Streams to write to Kafka in a serializable way?

答:
As the exception indicates, the DStream definition is being captured by the closure.
A simple option is to declare this DStream transient:

```<code>@transient val spamTagStream = //KafkaUtils.create...
</code>```

@transient flags certain objects to be removed from the Java serialization of the object graph of some object. The key of this scenario is that some val declared in the same scope as the DStream (statusCodeStreams in this case) is used within the closure. The actual reference of that val from within the closure is outer.statusCodeStreams, causing that the serialization process to "pull"  all context of outer into the closure. With @transient we mark the DStream (and also the StreamingContext)  declarations as non-serializable and we avoid the serialization issue.  Depending on the code structure (if it's all linear in one main function (bad practice, btw) it might be necessary to mark ALL DStream declarations + the StreamingContext instance as @transient.

If the only intent of the initial filtering is to 'route' the content to separate Kafka topics, it might be worth moving the filtering within the foreachRDD. That would make for a simpler program structure.

```<code>spamTagStream.foreachRDD{ rdd =>
    rdd.cache()
    statuCodes.map{code =>
        val matchingCodes = rdd.filter(...)
        matchingCodes.foreachPartition{write to kafka}
    }
    rdd.unpersist(true)
}
</code>```

Title: Accessing Collection of DStreams

Body:
I am trying to access a collection of filtered DStreams obtained like in the solution to this question: Spark Streaming - Best way to Split Input Stream based on filter Param

I create the Collection as follows:

val statuCodes = Set("200","500", "404")
    spanTagStream.cache()
    val statusCodeStreams = statuCodes.map(key => key -> spanTagStream.filter(x => x._3.get("http.status_code").getOrElse("").asInstanceOf[String].equals(key)))

I try to access statusCodeStreams in the following way:

for(streamTuple <- statusCodeStreams){
      streamTuple._2.foreachRDD(rdd =>
  rdd.foreachPartition(
      partitionOfRecords =>
        {
            val props = new HashMap[String, Object]()
            props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServers)
            props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
              "org.apache.kafka.common.serialization.StringSerializer")
            props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
              "org.apache.kafka.common.serialization.StringSerializer")
            val producer = new KafkaProducer[String,String](props)

            partitionOfRecords.foreach
            {
                 x=>{
                 /* Code Writing to Kafka using streamTuple._1 as the topic-String */
                 }
            }
      })
   )
}

When executing this I receive the following error:
java.io.NotSerializableException: Object of org.apache.spark.streaming.kafka010.DirectKafkaInputDStream is being serialized possibly as a part of closure of an RDD operation. This is because the DStream object is being referred to from within the closure. Please rewrite the RDD operation inside this DStream to avoid this. This has been enforced to avoid bloating of Spark tasks with unnecessary objects

How do I access the Streams to write to Kafka in a serializable way?

Body:
As the exception indicates, the DStream definition is being captured by the closure.
A simple option is to declare this DStream transient:

@transient val spamTagStream = //KafkaUtils.create...

@transient flags certain objects to be removed from the Java serialization of the object graph of some object. The key of this scenario is that some val declared in the same scope as the DStream (statusCodeStreams in this case) is used within the closure. The actual reference of that val from within the closure is outer.statusCodeStreams, causing that the serialization process to "pull"  all context of outer into the closure. With @transient we mark the DStream (and also the StreamingContext)  declarations as non-serializable and we avoid the serialization issue.  Depending on the code structure (if it's all linear in one main function (bad practice, btw) it might be necessary to mark ALL DStream declarations + the StreamingContext instance as @transient.

If the only intent of the initial filtering is to 'route' the content to separate Kafka topics, it might be worth moving the filtering within the foreachRDD. That would make for a simpler program structure.

spamTagStream.foreachRDD{ rdd =>
    rdd.cache()
    statuCodes.map{code =>
        val matchingCodes = rdd.filter(...)
        matchingCodes.foreachPartition{write to kafka}
    }
    rdd.unpersist(true)
}


问:
screen.width/device-width different in PhoneGap then regular browser
I have identical content being loaded in a browser and also through a PhoneGap application.  I'm using CSS media queries to differentiate between mobile devices and desktop.  The query works fine in the browser but in PhoneGap it fails (both running on the same phone).

Using the remote device inspector in Chrome, I can run console statements and check issues.  The page loaded in a regular browser reports screen.width is 360 as the device is using a pixel ratio of 3:1.  If I inspect the same page loaded via PhoneGap then screen.width is reporting 1080.  In both cases, though, window.devicePixelRatio reports 3!

I've read other people having issues because they didn't set the viewport but I have it currently set to: <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, shrink-to-fit=no">

Both devices seem to give the same answer to window.innerWidth which is 360...

How do I get it so my CSS media queries that match device-width work correctly in both the browser and in PhoneGap?

EDIT

I think the difference is that PhoneGap is using the Android System WebView while the other is using Chrome for Android.  Apparently the WebView reports physical pixels while Chrome reports virtual pixels.  Is there a way around this??

答:
Before Android 5.0 the built in webview was the "Android" one and after that is a Chromium based one.  The "Android" one reported physical pixels.  I think the Chromium one properly reports "css pixels".  However, even on an Android 5.0 device, if the APK is compiled with a lower version SDK it seems to behave the same as the "Android" webview and used physical pixels.

However CSS media queries based on max-device-width are deprecated so I changed to using max-width which reliably used "CSS pixels" across different devices/browsers.


问:
changing the text area value for selected checkboxes when click on applyAll button using angular js
I need to display a block comments of selected check boxes with respective comments fields only(i.e if we select 1,3 check boxes and typing a comments and when we clicking on apply all button it should replace the comments fields of 1,3 after if we select 2,4 again when we change the text of comments and clicks on apply all button it should replace the comments fields of 2,4 only it shouldn't replace the 1,2,3,4 with new comments) can any one help me?

var app = angular.module('demo', []);
app.controller("profileController", function($scope) {

 $scope.personalDetails = [
            {
               'fname':'Muhammed',
                'lname':'Shanid',
                'email':'shanid@shanid.com',
                'check' : 'Y',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'John',
                'lname':'Abraham',
                'email':'john@gmail.com',
                'check' : 'N',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'raj',
                'lname':'komali',
                'email':'raj@gmail.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'Roy',
                'lname':'Mathew',
                'email':'roy@roy.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            }];

 $scope.applyCmtsAll = function(personBlckCmts) {
  angular.forEach($scope.personalDetails, function(value) {
   if (value.selected == true) {
    console.log("value " + value);
    value.selectedDpn.selectVal = "Yes";
    value.indivalCmts = personBlckCmts;
    //$scope.indivalCmts==personBlckCmts;
    return;
   }
  });
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
     text-decoration: line-through;

  }</code>```

<!DOCTYPE html>

  <link rel="stylesheet" href="style.css">

    <textarea ng-model="personBlckCmts"></textarea>
    <button  class="btn btn-default btn-sm" ng-click="applyCmtsAll(personBlckCmts)">Apply All</button>

     <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
     Firstname
     Lastname
     Email
     Yes/No
     Comment

        {{$index}}

   <input type="checkbox" ng-click="setClickedRow($index)" ng-model="personalDetail.selected" ng-disabled="personalDetail.selected"/>

     {{personalDetail.fname}}

     {{personalDetail.lname}}

     {{personalDetail.email}}

             <select  ng-init="personalDetail.selectedDpn= personalDetail.checkxDrpn[1]" ng-options="value as value.selectVal for value in personalDetail.checkxDrpn track by value.key"
        ng-model="personalDetail.selectedDpn" ></select>

  <textarea ng-model="indivalCmts" ng-disabled="personalDetail.selected">

  </textarea>

```

答:
I have updated your source code here. May be it will help to solve your issue.

var app = angular.module('demo', []);
app.controller("profileController", function($scope) {

 $scope.personalDetails = [
            {
               'fname':'Muhammed',
                'lname':'Shanid',
                'email':'shanid@shanid.com',
                'check' : 'Y',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'John',
                'lname':'Abraham',
                'email':'john@gmail.com',
                'check' : 'N',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'raj',
                'lname':'komali',
                'email':'raj@gmail.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'Roy',
                'lname':'Mathew',
                'email':'roy@roy.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            }];

 $scope.applyCmtsAll = function(personBlckCmts) {
  angular.forEach($scope.personalDetails, function(value) {
   if (value.selected == true) {

    value.selectedDpn.selectVal = "Yes";
    value.indivalCmts = personBlckCmts;
    value.selected = false;
   }
  });
  $scope.personBlckCmts='';
 }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.selected {
     text-decoration: line-through;

  }</code>```

<!DOCTYPE html>

  <link rel="stylesheet" href="style.css">

    <textarea ng-model="personBlckCmts"></textarea>
    <button  class="btn btn-default btn-sm" ng-click="applyCmtsAll(personBlckCmts)">Apply All</button>

     <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
     Firstname
     Lastname
     Email
     Yes/No
     Comment

        {{$index}}

   <input type="checkbox" ng-click="setClickedRow($index)" ng-model="personalDetail.selected" ng-disabled="personalDetail.selected"/>

     {{personalDetail.fname}}

     {{personalDetail.lname}}

     {{personalDetail.email}}

             <select  ng-init="personalDetail.selectedDpn= personalDetail.checkxDrpn[1]" ng-options="value as value.selectVal for value in personalDetail.checkxDrpn track by value.key"
        ng-model="personalDetail.selectedDpn" ></select>

  <textarea ng-model="personalDetail.indivalCmts" ng-disabled="personalDetail.selected">

  </textarea>

```

Body:
I need to display a block comments of selected check boxes with respective comments fields only(i.e if we select 1,3 check boxes and typing a comments and when we clicking on apply all button it should replace the comments fields of 1,3 after if we select 2,4 again when we change the text of comments and clicks on apply all button it should replace the comments fields of 2,4 only it shouldn't replace the 1,2,3,4 with new comments) can any one help me?

var app = angular.module('demo', []);
app.controller("profileController", function($scope) {

 $scope.personalDetails = [
            {
               'fname':'Muhammed',
                'lname':'Shanid',
                'email':'shanid@shanid.com',
                'check' : 'Y',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'John',
                'lname':'Abraham',
                'email':'john@gmail.com',
                'check' : 'N',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'raj',
                'lname':'komali',
                'email':'raj@gmail.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'Roy',
                'lname':'Mathew',
                'email':'roy@roy.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            }];

 $scope.applyCmtsAll = function(personBlckCmts) {
  angular.forEach($scope.personalDetails, function(value) {
   if (value.selected == true) {
    console.log("value " + value);
    value.selectedDpn.selectVal = "Yes";
    value.indivalCmts = personBlckCmts;
    //$scope.indivalCmts==personBlckCmts;
    return;
   }
  });
 }

});

.selected {
     text-decoration: line-through;

  }

<!DOCTYPE html>

  <link rel="stylesheet" href="style.css">

    <textarea ng-model="personBlckCmts"></textarea>
    <button  class="btn btn-default btn-sm" ng-click="applyCmtsAll(personBlckCmts)">Apply All</button>

     <input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
     Firstname
     Lastname
     Email
     Yes/No
     Comment

        {{$index}}

   <input type="checkbox" ng-click="setClickedRow($index)" ng-model="personalDetail.selected" ng-disabled="personalDetail.selected"/>

     {{personalDetail.fname}}

     {{personalDetail.lname}}

     {{personalDetail.email}}

             <select  ng-init="personalDetail.selectedDpn= personalDetail.checkxDrpn[1]" ng-options="value as value.selectVal for value in personalDetail.checkxDrpn track by value.key"
        ng-model="personalDetail.selectedDpn" ></select>

  <textarea ng-model="indivalCmts" ng-disabled="personalDetail.selected">

  </textarea>

Body:
I have updated your source code here. May be it will help to solve your issue.

var app = angular.module('demo', []);
app.controller("profileController", function($scope) {

 $scope.personalDetails = [
            {
               'fname':'Muhammed',
                'lname':'Shanid',
                'email':'shanid@shanid.com',
                'check' : 'Y',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'John',
                'lname':'Abraham',
                'email':'john@gmail.com',
                'check' : 'N',
                'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'raj',
                'lname':'komali',
                'email':'raj@gmail.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            },
            {
                'fname':'Roy',
                'lname':'Mathew',
                'email':'roy@roy.com',
                'check' : 'N',
                 'checkxDrpn' : [
                  { key: 'Y',selectVal: "Yes"},
                  { key: 'N',selectVal: "No"}
                ],
                'indivalCmts' : ''
            }];

 $scope.applyCmtsAll = function(personBlckCmts) {
  angular.forEach($scope.personalDetails, function(value) {
   if (value.selected == true) {

    value.selectedDpn.selectVal = "Yes";
    value.indivalCmts = personBlckCmts;
    value.selected = false;
   }
  });
  $scope.personBlckCmts='';
 }

});

.selected {
     text-decoration: line-through;

  }

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="style.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
 <script src="script.js"></script>
</head>
<body ng-app="demo" ng-controller="profileController">
<div class="">
    <textarea ng-model="personBlckCmts"></textarea>
    <button  class="btn btn-default btn-sm" ng-click="applyCmtsAll(personBlckCmts)">Apply All</button>
 </div>
<table class="table table-striped table-bordered">
   <thead>
    <tr>
     <th></th>
     <th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" /></th>
     <th>Firstname</th>
     <th>Lastname</th>
     <th>Email</th>
     <th>Yes/No</th>
     <th>Comment</th>
   </tr>
  </thead>
      <tbody>
        <tr ng-repeat="personalDetail in personalDetails" ng-class="{'selected':personalDetail.selected}">
        <td>{{$index}}</td>
  <td>
   <input type="checkbox" ng-click="setClickedRow($index)" ng-model="personalDetail.selected" ng-disabled="personalDetail.selected"/>
  </td>
   <td>
     <span>{{personalDetail.fname}}</span>
  </td>
  <td>
     <span>{{personalDetail.lname}}</span>
  </td>
   <td>
     <span>{{personalDetail.email}}</span>
  </td>

          <td>
             <select  ng-init="personalDetail.selectedDpn= personalDetail.checkxDrpn[1]" ng-options="value as value.selectVal for value in personalDetail.checkxDrpn track by value.key"
        ng-model="personalDetail.selectedDpn" ></select>
       </td>
    <td>
  <textarea ng-model="personalDetail.indivalCmts" ng-disabled="personalDetail.selected">

  </textarea>
    </td>
        </tr>
      </tbody>
      </table>

</body>
</html>


问:
python-docx cannot be imported to python
I'm trying to install python-docx so I typed in the cmd

```<code>easy_install python-docx
</code>```

and got:

```<code>Searching for python-docx
Best match: python-docx 0.7.4
Processing python_docx-0.7.4-py2.6.egg
python-docx 0.7.4 is already the active version in easy-install.pth

Using c:\python26\lib\site-packages\python_docx-0.7.4-py2.6.egg
Processing dependencies for python-docx
Finished processing dependencies for python-docx
</code>```

but when I open python and type:

import docx

I got:

```<code> File "c:\python26\lib\site-packages\docx-0.2.4-py2.6.egg\docx.py", line 17, in <
module>
    from lxml import etree
ImportError: DLL load failed: The specified procedure could not be found.
</code>```

How can I solve this import error? what is missing?

答: I too was getting same 'DLL load failed' error. Stupid mistake on my part, but had installed 32 bit Python on to 64 bit Windows. Un-installed 32 bit version, installed 64 bit version - problem sorted.</p>

Body:
I'm trying to install python-docx so I typed in the cmd

easy_install python-docx

and got:

Searching for python-docx
Best match: python-docx 0.7.4
Processing python_docx-0.7.4-py2.6.egg
python-docx 0.7.4 is already the active version in easy-install.pth

Using c:\python26\lib\site-packages\python_docx-0.7.4-py2.6.egg
Processing dependencies for python-docx
Finished processing dependencies for python-docx

but when I open python and type:

import docx

I got:

 File "c:\python26\lib\site-packages\docx-0.2.4-py2.6.egg\docx.py", line 17, in <
module>
    from lxml import etree
ImportError: DLL load failed: The specified procedure could not be found.

How can I solve this import error? what is missing?


问:
Sidebar menu and hover submenus with CSS
I'm looking for improve my sidebar menu in my Django application. I would like to display submenus with a hover effect when users put their mouses on each menu titles.

This is my script :

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 170px;
  bottom: 0;
  height: 80%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>

<div class="area"></div>
<nav class="main-menu">
  <ul>
    <li>

        <i class="fa fa-home fa-2x"></i>
        <span class="nav-text">
           Accueil
        </span>

    </li>
    <li class="has-subnav">
      <i class="fa fa-file-text-o fa-2x"></i>
        <span class="nav-text">Fiches Identifications</span>
      <ul>
        <li>Accueil</li>
        <li>Individus</li>
        <li>Sociétés</li>
      </ul>
    </li>
    <li>

        <i class="fa fa-bar-chart-o fa-2x"></i>
        <span class="nav-text">
           Statistiques
        </span>

    </li>
    <li>

        <i class="fa fa-folder fa-2x"></i>
        <span class="nav-text">
           DatasystemsDOC
        </span>

    </li>
    <li>

        <i class="fa fa-cog fa-spin fa-2x fa-fw"></i>
        <span class="nav-text">
           Configurations
        </span>

    </li>
    <li>

        <i class="fa fa-life-ring fa-2x"></i>
        <span class="nav-text">
          Aide et Support
        </span>

    </li>
    <li>

        <i class="fa fa-info fa-2x"></i>
        <span class="nav-text">
           Documentation
        </span>

    </li>
  </ul>

  <ul class="logout">
    <li>

        <i class="fa fa-power-off fa-2x"></i>
        <span class="nav-text">
           Logout
        </span>

    </li>
  </ul>
</nav></code>```

My preview is available there : see preview

I would like to display submenus Accueil Individus Sociétés when I put my mouse on Fiches Identifications with a vertical hover effect.

Do you have any idea to do that ?

答:
try this code

$('ul li').hover(function() {
  $(this).find('li').closest('ul').toggle(1000);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 0px;
  bottom: 0;
  height: 100%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

               Accueil

            Fiches Identifications

Accueil

Individus

Sociétés

               Statistiques

               DatasystemsDOC

               Configurations

              Aide et Support

               Documentation

               Logout

```

Body:
I'm looking for improve my sidebar menu in my Django application. I would like to display submenus with a hover effect when users put their mouses on each menu titles.

This is my script :

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 170px;
  bottom: 0;
  height: 80%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

           Accueil

        Fiches Identifications

Accueil

Individus

Sociétés

           Statistiques

           DatasystemsDOC

           Configurations

          Aide et Support

           Documentation

           Logout

My preview is available there : see preview

I would like to display submenus Accueil Individus Sociétés when I put my mouse on Fiches Identifications with a vertical hover effect.

Do you have any idea to do that ?

Body:
try this code

$('ul li').hover(function() {
  $(this).find('li').closest('ul').toggle(1000);
});

@import url(//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css);

}
@import url(https://fonts.googleapis.com/css?family=Titillium+Web:300);
.fa-2x {
  font-size: 2em;
}
.fa {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 20px;
}
.main-menu:hover,
nav.main-menu.expanded {
  width: 250px;
  overflow: visible;
}
.main-menu {
  background: #0083A2;
  border-top: 1px solid black;
  border-right: 1px solid black;
  border-left: 1px solid black;
  border-bottom: 1px solid black;
  position: absolute;
  top: 0px;
  bottom: 0;
  height: 100%;
  left: 0;
  width: 60px;
  overflow: hidden;
  -webkit-transition: width .05s linear;
  transition: width .05s linear;
  -webkit-transform: translateZ(0) scale(1, 1);
  z-index: 1000;
}
.main-menu>ul {
  margin: 7px 0;
}
.main-menu li {
  position: relative;
  display: block;
  width: 250px;
}
.main-menu li>a {
  position: relative;
  display: table;
  border-collapse: collapse;
  border-spacing: 0;
  color: white;
  font-family: Helvetica;
  font-weight: bolder;
  font-size: 14px;
  text-decoration: none;
  -webkit-transform: translateZ(0) scale(1, 1);
  -webkit-transition: all .1s linear;
  transition: all .1s linear;
}
.main-menu .nav-icon {
  position: relative;
  display: table-cell;
  width: 60px;
  height: 36px;
  text-align: center;
  vertical-align: middle;
  font-size: 18px;
}
.main-menu .nav-text {
  position: relative;
  display: table-cell;
  vertical-align: middle;
  width: 190px;
  font-family: 'Helvetica Neue', sans-serif;
}
.main-menu>ul.logout {
  position: absolute;
  left: 0;
  bottom: 0;
}
.no-touch .scrollable.hover {
  overflow-y: hidden;
}
.no-touch .scrollable.hover:hover {
  overflow-y: auto;
  overflow: visible;
}
a:hover,
a:focus {
  text-decoration: none;
}
nav {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
}
nav ul,
nav li {
  outline: 0;
  margin: 0;
  padding: 0;
}
.main-menu li:hover>a,
nav.main-menu li.active>a,
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-menu>.active>a,
.dropdown-menu>.active>a:hover,
.dropdown-menu>.active>a:focus,
.no-touch .dashboard-page nav.dashboard-menu ul li:hover a,
.dashboard-page nav.dashboard-menu ul li.active a {
  color: #fff;
  background-color: #5fa2db;
}
.area {
  float: left;
  background: #e2e2e2;
  width: 100%;
  height: 100%;
}
@font-face {
  font-family: 'Helvetica Neue';
  font-style: normal;
  font-weight: 300;
  src: local('Helvetica Neue'), local('Helvetica Neue'), url(http://themes.googleusercontent.com/static/fonts/titilliumweb/v2/anMUvcNT0H1YN4FII8wpr24bNCNEoFTpS2BTjF6FB5E.woff) format('woff');
}
nav.main-menu>ul>li.has-subnav>ul>li {
  margin-left: 100px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

</head>
<div class="area"></div>
<nav class="main-menu">
  <ul>
    <li>
      <a href="{% url " accueil " %}">
        <i class="fa fa-home fa-2x"></i>
        <span class="nav-text">
               Accueil
         </span>
      </a>
    </li>
    <li class="has-subnav">
      <a href="#"><i class="fa fa-file-text-o fa-2x"></i>
            <span class="nav-text">Fiches Identifications</span></a>
      <ul style='display:none'>
        <li><a href="#">Accueil</a></li>
        <li><a href="#">Individus</a></li>
        <li><a href="#">Sociétés</a></li>
      </ul>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-bar-chart-o fa-2x"></i>
        <span class="nav-text">
               Statistiques
            </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-folder fa-2x"></i>
        <span class="nav-text">
               DatasystemsDOC
            </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-cog fa-spin fa-2x fa-fw"></i>
        <span class="nav-text">
               Configurations
            </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-life-ring fa-2x"></i>
        <span class="nav-text">
              Aide et Support
            </span>
      </a>
    </li>
    <li>
      <a href="#">
        <i class="fa fa-info fa-2x"></i>
        <span class="nav-text">
               Documentation
            </span>
      </a>
    </li>
  </ul>

  <ul class="logout">
    <li>
      <a href="#">
        <i class="fa fa-power-off fa-2x"></i>
        <span class="nav-text">
               Logout
         </span>
      </a>
    </li>
  </ul>
</nav>


问:
Difference between Java EE and Spring framework
I am striving to know the difference between Java EE and Spring Framework. Could anyone please help me on this.</p>

答:
Java EE:

A Sun/Oracle standard that app server vendors conform to

Based on Enterprise Java Beans

Implemented by many vendors: BEA/Oracle, WebSphere, JBOSS, Glassfish, etc.

Spring:

Not a standard; it's the brainchild of Rod Johnson and implemented by Spring/VMWare.

Not based on Enterprise Java Beans; it's a POJO model.  Can manage EJBs if you wish to use them, but not required.

Not implemented by any vendor other than Spring.

EJB 3.1 has taken a great deal from Spring.  Now it includes dependency injection, a form of aspects, and JPA.  EJB 3.1 is much closer to Spring than EJB 2.0 was.


问:
How to use # instead of $ in DB2 query with iBatis
I use DB2 with iBatis in my project.

There are many

```<code>FETCH FRIST $perPg$ ROWS ONLY
</code>```

queries for paging in DaoMap.xml files. But it seems dangerous in case of query injection. so I want to change them using # instead of $, but I can't figure it out.

Functions like CAST(#perPg# AS INTEGER) doesn't work on FETCH query. How can I solve this problem?

答:
If you want to convert to int (and ensure that the value arrived is int) you can try with this:</p>

```<code>#perPg:BIGINT#
</code>```

Body:
I use DB2 with iBatis in my project.

There are many

FETCH FRIST $perPg$ ROWS ONLY

queries for paging in DaoMap.xml files. But it seems dangerous in case of query injection. so I want to change them using # instead of $, but I can't figure it out.

Functions like CAST(#perPg# AS INTEGER) doesn't work on FETCH query. How can I solve this problem?

Body:
If you want to convert to int (and ensure that the value arrived is int) you can try with this:

#perPg:BIGINT#


问:
Does Exchange Server (in-house) suppport REST API?
This document that applies to Exchange Server suggests that the bulk of API / Web Services is SOAP based:
https://msdn.microsoft.com/en-us/library/office/dd877012(v=exchg.150).aspx

However i see that Office 365 (which i assume is cloud based) supports a REST API.
https://msdn.microsoft.com/en-us/library/office/dn776319(v=exchg.150).aspx

But there it says that this documentation applies to Exchange Online / Office 365 only. So if i have an in-house Exchange Server, will it also support REST? Is there some official docu to this end? (i know that it supports EWS via SOAP, but i would prefer REST, and what i found online was just bits and pieces of stories and experiments)

Many thanks...

答:
Regarding to the Exchange Team Blog, the REST API is also supported in On-Premise-Scenarios beginning from Exchange 2016 CU3.

Please see https://blogs.technet.microsoft.com/exchange/2016/09/26/on-premises-architectural-requirements-for-the-rest-api/ for reference. I've tested it with our Exchange 2016 CU5 (Non-Hybrid)-Deployment and it worked well.

You can for example query the mails from your account via the following PowerShell-Code:

```<code>$restdata = Invoke-RestMethod -Uri "https://YOUR-Exchange-Server/api/v2.0/me/messages" -Credential (Get-Credential)
$restdata.value
</code>```

Body:
Regarding to the Exchange Team Blog, the REST API is also supported in On-Premise-Scenarios beginning from Exchange 2016 CU3.

Please see https://blogs.technet.microsoft.com/exchange/2016/09/26/on-premises-architectural-requirements-for-the-rest-api/ for reference. I've tested it with our Exchange 2016 CU5 (Non-Hybrid)-Deployment and it worked well.

You can for example query the mails from your account via the following PowerShell-Code:

$restdata = Invoke-RestMethod -Uri "https://YOUR-Exchange-Server/api/v2.0/me/messages" -Credential (Get-Credential)
$restdata.value


问:
iOS Vision detect light on binarized image
I stuck with some issue. How can I define the light spot on the binarized image.  I am using ios11 and Vision now.

I use binarization filter CIColorControls (also tried to combine this with CIColorInvert).

For light detection, I use VNImageRequestHandler with VNDetectRectanglesRequest.
In VNDetectRectanglesRequest I check for VNDetectedObjectObservation
But can't achieve the 100% frame detection (sometimes app can't recognize light spot on frames). What I am doing wrong? Appreciate any help

Here is my code

```<code> lazy var rectanglesRequest: VNDetectRectanglesRequest = {
        return VNDetectRectanglesRequest(completionHandler: self.handleRectangles)
    }()

 func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
            connection.videoOrientation = AVCaptureVideoOrientation.portrait
            guard let uiImage = imageFromSampleBuffer(sampleBuffer: sampleBuffer) else { return }

            let correctedImage = uiImage
                .applyingFilter("CIColorControls", withInputParameters: [
                    kCIInputSaturationKey: 0,
                    kCIInputContrastKey: 4.5,
                    kCIInputBrightnessKey: -1.54
                    ])
                //.applyingFilter("CIColorInvert", withInputParameters: nil)
              self.searchLightSpot(ciImage: correctedImage)

            DispatchQueue.main.async { [unowned self] in //unowned
                self.frameImageView.image = UIImage(ciImage: correctedImage)
            }
        }

 func searchLightSpot(ciImage: CIImage) {
        var requestOptions: [VNImageOption: Any] = [:]
        let handler = VNImageRequestHandler(ciImage: ciImage, options: requestOptions)
        DispatchQueue.global(qos: .userInteractive).async {
            do {
                try handler.perform([self.rectanglesRequest])
            } catch {
                print(error)
            }
        }
    }

func handleRectangles(request: VNRequest, error: Error?) {
        guard let observations = request.results as? [VNDetectedObjectObservation]
            else {
                print("unexpected result type from VNDetectedObjectObservation")
                return
        }
        guard let detectedObject = observations.first else {
                print("not detected object")
            return
        }

        print("detected object: ", detectedObject)
    }
</code>```

答:
After making additional research I understood that it looks like Apple make additional optimizations with frames

For example if we get light in the 1st frame and the next 5 frames would be the same
It will show us the same frame so instead 5 frames - we have only 1
It means that we can not relay on static number of frames in second with 100% sure

So I can't detect the signal duration and so on....

One of the possible solution can be:

1. We can start our timer which will get the current frame from camera (for example each 100ms)

2. Then we will check if the frame has white dot. Based on these results of histogramm

y - color (0/1 displays if white color exists on frame)

x - timeline (ms)

3. So the output of this diagram  could be

```<code>[01111100001111…]
</code>```

4. Then we can analyze and detect signal

You can use EasyImagy
and write your own extension to binarize and detect white spots

```<code>  extension Image  where Pixel == RGBA {

        fileprivate func getPixelCount() -> Int {
            return Int(10 * width / 100)
        }

        func binarize() -> (isWhite: Bool, binarizedImage: Image<RGBA>) {

            var kWidth = 0
            var img = self
            let pixelCount = getPixelCount()
            for x in 0..<width{
                var kHeight = 0
                for y in 0..<height {

                    if let _pixel = pixel(x, y) {
                        if _pixel.gray < 245 {
                            img[x, y] = .black
                            kHeight = 0
                        } else {
                            img[x, y] = .white
                            kHeight += 1
                        }

                        if kHeight > pixelCount {
                            kWidth += 1
                            break
                        }
                    }
                }
                print("Hwhite: \(kHeight) Wwhite: \(kWidth)")
                if kHeight >= pixelCount && kWidth >= pixelCount  {
                    return (true, img)
                }
            }
            return (false, img)
        }
    }
</code>```

Body:
I stuck with some issue. How can I define the light spot on the binarized image.  I am using ios11 and Vision now.

I use binarization filter CIColorControls (also tried to combine this with CIColorInvert).

For light detection, I use VNImageRequestHandler with VNDetectRectanglesRequest.
In VNDetectRectanglesRequest I check for VNDetectedObjectObservation
But can't achieve the 100% frame detection (sometimes app can't recognize light spot on frames). What I am doing wrong? Appreciate any help

Here is my code

 lazy var rectanglesRequest: VNDetectRectanglesRequest = {
        return VNDetectRectanglesRequest(completionHandler: self.handleRectangles)
    }()

 func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
            connection.videoOrientation = AVCaptureVideoOrientation.portrait
            guard let uiImage = imageFromSampleBuffer(sampleBuffer: sampleBuffer) else { return }

            let correctedImage = uiImage
                .applyingFilter("CIColorControls", withInputParameters: [
                    kCIInputSaturationKey: 0,
                    kCIInputContrastKey: 4.5,
                    kCIInputBrightnessKey: -1.54
                    ])
                //.applyingFilter("CIColorInvert", withInputParameters: nil)
              self.searchLightSpot(ciImage: correctedImage)

            DispatchQueue.main.async { [unowned self] in //unowned
                self.frameImageView.image = UIImage(ciImage: correctedImage)
            }
        }

 func searchLightSpot(ciImage: CIImage) {
        var requestOptions: [VNImageOption: Any] = [:]
        let handler = VNImageRequestHandler(ciImage: ciImage, options: requestOptions)
        DispatchQueue.global(qos: .userInteractive).async {
            do {
                try handler.perform([self.rectanglesRequest])
            } catch {
                print(error)
            }
        }
    }

func handleRectangles(request: VNRequest, error: Error?) {
        guard let observations = request.results as? [VNDetectedObjectObservation]
            else {
                print("unexpected result type from VNDetectedObjectObservation")
                return
        }
        guard let detectedObject = observations.first else {
                print("not detected object")
            return
        }

        print("detected object: ", detectedObject)
    }

Body:
After making additional research I understood that it looks like Apple make additional optimizations with frames

For example if we get light in the 1st frame and the next 5 frames would be the same
It will show us the same frame so instead 5 frames - we have only 1
It means that we can not relay on static number of frames in second with 100% sure

So I can't detect the signal duration and so on....

One of the possible solution can be:

1. We can start our timer which will get the current frame from camera (for example each 100ms)

2. Then we will check if the frame has white dot. Based on these results of histogramm

y - color (0/1 displays if white color exists on frame)

x - timeline (ms)

3. So the output of this diagram  could be

[01111100001111…]

4. Then we can analyze and detect signal

You can use EasyImagy
and write your own extension to binarize and detect white spots

  extension Image  where Pixel == RGBA {

        fileprivate func getPixelCount() -> Int {
            return Int(10 * width / 100)
        }

        func binarize() -> (isWhite: Bool, binarizedImage: Image<RGBA>) {

            var kWidth = 0
            var img = self
            let pixelCount = getPixelCount()
            for x in 0..<width{
                var kHeight = 0
                for y in 0..<height {

                    if let _pixel = pixel(x, y) {
                        if _pixel.gray < 245 {
                            img[x, y] = .black
                            kHeight = 0
                        } else {
                            img[x, y] = .white
                            kHeight += 1
                        }

                        if kHeight > pixelCount {
                            kWidth += 1
                            break
                        }
                    }
                }
                print("Hwhite: \(kHeight) Wwhite: \(kWidth)")
                if kHeight >= pixelCount && kWidth >= pixelCount  {
                    return (true, img)
                }
            }
            return (false, img)
        }
    }


问:
CSS: remove edge / ie animations
Not so surprisingly scale effects look horrible in ms edge browsers. Is there a way to disable this all together for edge? </p>

```<code>.jumbotron__bg {
 -webkit-animation-name: animateBg;
 animation-name: animateBg;
 -ms-animation-name: none;

 animation-duration: 18000ms;
 animation-fill-mode: both;

 animation-timing-function: cubic-bezier(.3,0,.7,1);
 animation-iteration-count: 1;
}

@keyframes animateBg {
  from {
  transform: scale(1.05, 1.05);
  -ms-transform: scale(1,1);
 }

 to {
 transform: scale(1, 1);
 -ms-transform: scale(1,1);
 }
}
</code>```

<p>(ie is ok, does not work for edge)</p>

答:
you could use @supports with a property that only Edge supports ;

this works on Edge 12 and later (all versions) :

```<code>@supports (-ms-ime-align: auto) {
     .jumbotron__bg {
         animation-name: none;
     }
}
</code>```

~or~

this only works in Edge up to v13

```<code>@supports (-ms-accelerator:true) {
     .jumbotron__bg {
         animation-name: none;
     }
}
</code>```

Title: CSS: remove edge / ie animations

Body:
Not so surprisingly scale effects look horrible in ms edge browsers. Is there a way to disable this all together for edge?

.jumbotron__bg {
 -webkit-animation-name: animateBg;
 animation-name: animateBg;
 -ms-animation-name: none;

 animation-duration: 18000ms;
 animation-fill-mode: both;

 animation-timing-function: cubic-bezier(.3,0,.7,1);
 animation-iteration-count: 1;
}

@keyframes animateBg {
  from {
  transform: scale(1.05, 1.05);
  -ms-transform: scale(1,1);
 }

 to {
 transform: scale(1, 1);
 -ms-transform: scale(1,1);
 }
}

(ie is ok, does not work for edge)

Body:
you could use @supports with a property that only Edge supports ;

this works on Edge 12 and later (all versions) :

@supports (-ms-ime-align: auto) {
     .jumbotron__bg {
         animation-name: none;
     }
}

~or~

this only works in Edge up to v13

@supports (-ms-accelerator:true) {
     .jumbotron__bg {
         animation-name: none;
     }
}


问:
Getting Contents of Google form on Email after a user submits a google form
I want to get the contents of the google form sent to my email rather than just a notification that a new user has submitted the form. I put in the following code. But I get a response saying that namedValues is undefined. I tried actually submitting a dummy google form, but it still doesn't send me the contents of the google form on email.
function sendFormByEmail (e) {
     var email = "example@gmail.com"; </p>

```<code> var Name = e.values[3];
 var EmailAddress = e.values[4];
 var txt = "";
 for(var field in e.namedValues) {
 txt += field + ' :: ' + e.namedValues[field].toString() + "\n\n";
 }
 MailApp.sendEmail(email, "New Client", txt);
 }
</code>```

答:
If the script is attached to the form and triggered when that form is submitted, use the response object with that event.  AFAIK the namedValues object you are trying to access is only available if your script is attached to the spreadsheet that recieves the form input.

I use this script when I want to quickly send a simple form submission to an email address (and not use the addons that can do this and more):

```<code>function onFormSubmit_sendEmail(e) {
  var msgBody = "";
  var itemResponses = e.response.getItemResponses();
  for (var i = 0; i < itemResponses.length; i++) {
    var itemResponse = itemResponses[i];
    msgBody = msgBody + itemResponse.getItem().getTitle() + ": " + itemResponse.getResponse() + "\n\n";
  }
  MailApp.sendEmail("someemail@somedomain", "Form Submission", msgBody);
  }
}
</code>```

You can use some tests on the item title (getTitle() method) to do different things depending on the question - e.g. if one question is where you want the email sent to, do something like:

```<code>if (itemResponse.getItem().getTitle() == "Recipient Address") {
  var email = itemResponse.getResponse();
</code>```

You could then use that MailApp.sendMail() function. Hope this helps.

Body:
I want to get the contents of the google form sent to my email rather than just a notification that a new user has submitted the form. I put in the following code. But I get a response saying that namedValues is undefined. I tried actually submitting a dummy google form, but it still doesn't send me the contents of the google form on email.
function sendFormByEmail (e) {
     var email = "example@gmail.com";

 var Name = e.values[3];
 var EmailAddress = e.values[4];
 var txt = "";
 for(var field in e.namedValues) {
 txt += field + ' :: ' + e.namedValues[field].toString() + "\n\n";
 }
 MailApp.sendEmail(email, "New Client", txt);
 }

Body:
If the script is attached to the form and triggered when that form is submitted, use the response object with that event.  AFAIK the namedValues object you are trying to access is only available if your script is attached to the spreadsheet that recieves the form input.

I use this script when I want to quickly send a simple form submission to an email address (and not use the addons that can do this and more):

function onFormSubmit_sendEmail(e) {
  var msgBody = "";
  var itemResponses = e.response.getItemResponses();
  for (var i = 0; i < itemResponses.length; i++) {
    var itemResponse = itemResponses[i];
    msgBody = msgBody + itemResponse.getItem().getTitle() + ": " + itemResponse.getResponse() + "\n\n";
  }
  MailApp.sendEmail("someemail@somedomain", "Form Submission", msgBody);
  }
}

You can use some tests on the item title (getTitle() method) to do different things depending on the question - e.g. if one question is where you want the email sent to, do something like:

if (itemResponse.getItem().getTitle() == "Recipient Address") {
  var email = itemResponse.getResponse();

You could then use that MailApp.sendMail() function. Hope this helps.


问:
Selenium GeckoDriver get IP and Port no of the launched driver instance
I'm using Selenium 3.4, Geckodriver 0.17.

I launch FirefoxDriver using the below code

```<code>    System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
    FirefoxDriver driver = new FirefoxDriver();
    driver.get("http://www.bing.com");
    System.out.println(driver.getSessionId());
</code>```

Is there a way I can get the IP and the port of the launched driver instance?

The data I want is printed in the logs.

```<code>1499170600204   geckodriver INFO    Listening on 127.0.0.1:38840
1499170601127   geckodriver::marionette INFO    Starting browser C:\Program Files\Mozilla Firefox\firefox.exe with args ["-marionette"]
[GFX1]: Potential driver version mismatch ignored due to missing DLLs igd10umd32 v= and igd10iumd32 v=
1499170608388   Marionette  INFO    Listening on port 12793
Jul 04, 2017 5:46:48 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
</code>```

The First line of the output 127.0.0.1:38840 prints the info I want. I don't want to parse the log as I will be running drivers in parallel.

答:
The RemoteWebDriver has getCommandExecutor method.

Which can be TypeCasted to HttpCommandExecutor and getAddressOfRemoteServer() method returns the URL.

```<code>HttpCommandExecutor ce = (HttpCommandExecutor) driver.getCommandExecutor();
System.out.println(ce.getAddressOfRemoteServer());
</code>```

Body:
I'm using Selenium 3.4, Geckodriver 0.17.

I launch FirefoxDriver using the below code

    System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
    FirefoxDriver driver = new FirefoxDriver();
    driver.get("http://www.bing.com");
    System.out.println(driver.getSessionId());

Is there a way I can get the IP and the port of the launched driver instance?

The data I want is printed in the logs.

1499170600204   geckodriver INFO    Listening on 127.0.0.1:38840
1499170601127   geckodriver::marionette INFO    Starting browser C:\Program Files\Mozilla Firefox\firefox.exe with args ["-marionette"]
[GFX1]: Potential driver version mismatch ignored due to missing DLLs igd10umd32 v= and igd10iumd32 v=
1499170608388   Marionette  INFO    Listening on port 12793
Jul 04, 2017 5:46:48 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C

The First line of the output 127.0.0.1:38840 prints the info I want. I don't want to parse the log as I will be running drivers in parallel.

Body:
The RemoteWebDriver has getCommandExecutor method.

Which can be TypeCasted to HttpCommandExecutor and getAddressOfRemoteServer() method returns the URL.

HttpCommandExecutor ce = (HttpCommandExecutor) driver.getCommandExecutor();
System.out.println(ce.getAddressOfRemoteServer());


问:
Spring MVC 3.2.8: Create a new FileSystemXmlApplicationContext and loading the definitions from the given XML files
I have an Spring MVC 3.2.8 app, and I want to run StandAlone process to generate a PDF. I want to initialize the container and manage beans from an stand-alone app.
I have this piece of code:

```<code>   public class CreatePDF {

        private static final Logger LOGGER = Logger.getLogger   (ImportEcolabelToolboxToECAT.class);

        public static void main(String[] args) {

            String[] configLocations = new String[] {

"C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/resources/com/nicinc/dao/dataAccessContext.xml",

"C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/webapp/WEB-INF/dao/databaseMessageSource.xml",
                                                        "C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/resources/com/nicinc/services/impl/servicesContext.xml",
                                                        "C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/webapp/WEB-INF/applicationContext.xml",
                                                        "C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/resources/com/nicinc/controller/propertyeditors/propertyeditorsContext.xml"};

            FileSystemXmlApplicationContext ctx =
                    new FileSystemXmlApplicationContext(configLocations, true);

        }
    }
</code>```

But I have this error when running the app.

```<code>Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
</code>```

and here the definition from the file dataAccessContext.xml  :

```<code> <!-- The PropertyPlaceholderConfigurer replaces placeholders in Spring bean definitions with the values from the chosen properties files. -->
    <!-- There is an example use in the datasource definition below. Look for the $\{jdbc.*} values. -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:com/nicinc/dao/jdbc-test.properties</value>
                <value>classpath:com/nicinc/dao/dbMessageSource.properties</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform"   value="${hibernate.dialect}"/>
                <property name="generateDdl"        value="false"/>
                <property name="showSql"            value="false" />
            </bean>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</code>```

答:
The javax.naming package comprises the JNDI Api. Since it is just an API its implementation you will have to provide. Generally the implementation is provided by App server. As per the error you are Missing the JNDI implementation.
Possible solution:

If you dont have any javaee related requirement then you should directly use DriverManagerDataSource.

You need to provide your own implementation.Below link might help.
using application data source locally.

Body:
I have an Spring MVC 3.2.8 app, and I want to run StandAlone process to generate a PDF. I want to initialize the container and manage beans from an stand-alone app.
I have this piece of code:

   public class CreatePDF {

        private static final Logger LOGGER = Logger.getLogger   (ImportEcolabelToolboxToECAT.class);

        public static void main(String[] args) {

            String[] configLocations = new String[] {

"C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/resources/com/nicinc/dao/dataAccessContext.xml",

"C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/webapp/WEB-INF/dao/databaseMessageSource.xml",
                                                        "C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/resources/com/nicinc/services/impl/servicesContext.xml",
                                                        "C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/webapp/WEB-INF/applicationContext.xml",
                                                        "C:/Development/Workspaces/EclipseWS/devices/deviceWeb/src/main/resources/com/nicinc/controller/propertyeditors/propertyeditorsContext.xml"};

            FileSystemXmlApplicationContext ctx =
                    new FileSystemXmlApplicationContext(configLocations, true);

        }
    }

But I have this error when running the app.

Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

and here the definition from the file dataAccessContext.xml  :

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:com/nicinc/dao/jdbc-test.properties</value>
                <value>classpath:com/nicinc/dao/dbMessageSource.properties</value>
            </list>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="databasePlatform"   value="${hibernate.dialect}"/>
                <property name="generateDdl"        value="false"/>
                <property name="showSql"            value="false" />
            </bean>
        </property>
    </bean>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />