问:
Get corner items in current CSS grid layout, expanding on hover
I'm using grid-template-columns: repeat(auto-fit, 250px) to keep grid items 250px wide but automatically adjust number of row-items according to screen-width. Now I want that when I hover over an item, it expands taking a bit of its sibling's space, with its sibling getting shrunk. By console.log(), I found nextElementSibling that can be used. So I'm thinking of something like-

```<code>function expand(card){
    card.setAttribute("style","width: 300px;");
    card.nextElementSibling.setAttribute("style","width: 200px");
}
</code>```
```<code>function restore(card){
    card.setAttribute("style","width: 250px;");
    card.nextElementSibling.setAttribute("style","width: 250px");
}
</code>```

This seems pretty bad (I guess!) because I need to manage corner items separately and hence need to know the current number of items in a row. Also, when I hover over a card, the card does expand but because of repeat(auto-fit,250px), the card intersects its sibling because the individual cells remain fixed (250px).
How can I solve the issues? Or any better suggested solutions?
Here is my git repository.

Edit 1-
As to clarify my issues:

How to manage the corner items, i.e., for an item in the right corner I want its previous sibling shrink; not the next.

The cells remain fixed, i.e., the expanding item intercepts the shrinking item's border-

becomes

So how to deal with this behavior caused by auto-fit,250px?

答:
I honestly tried to solve it using grid-template-columns: repeat(auto-fit, minmax(250px,auto)); and a different size of child elements, but in's too unstable and not working that way. But I don't think the grid is require for this task. The easiest way I see how this should be solved - using good old JavaScript (+jQuery) and flex. Although the right way will be resize all elements in a single row, not only nearest siblings of a hovered element. Try it on any screen size.

$(document).ready(function() {
  /* defines main digits */
  let boxWidth = $('#box').innerWidth();
  let itemOuterWidth = $('.item').outerWidth(true);
  let itemInnerWidth = $('.item').innerWidth();
  SetSeparators(boxWidth, itemOuterWidth);

  /* refresh main digits ater page resize */
  $(window).resize(function() {
    $('.item').css({
      "flex": ""
    });
    boxWidth = $('#box').innerWidth();
    itemOuterWidth = $('.item').outerWidth(true);
    itemInnerWidth = $('.item').innerWidth();
    SetSeparators(boxWidth, itemOuterWidth);
  });

  $('#box').on('mouseover', '.item', function(e) {
    GetElementsPosition($(this).index('.item'), $(this), boxWidth, itemOuterWidth, itemInnerWidth);
  });

  $('#box').on('mouseleave', '.item', function(e) {
    $('.item').css({
      "flex": ""
    });
  });

});

/* set separator elemet to avoid blocks to jump from row to row while resizing */
function SetSeparators(boxWidth, itemOuterWidth) {
  $('.separator').remove();
  let countRowItems = Math.floor(boxWidth / itemOuterWidth);
  $('

').insertBefore('.item:nth-child(' + countRowItems + 'n+1)');
}

function GetElementsPosition(index, element, boxWidth, itemOuterWidth, itemInnerWidth) {

  /* calculating row items, column position and row position of a current elemet */
  let countRowItems = Math.floor(boxWidth / itemOuterWidth);
  let colPosition = index % countRowItems;
  let rowPosition = Math.floor(index / countRowItems);
  /* exmanpd size of a hovered element in pixels*/
  let expandSize = 50;

  /* counting number of items in a hovered row */
  let currentRowCounter = 0;
  $('.item').each(function(e) {
    let thisIndex = $(this).index('.item');
    let thisRowPosition = Math.floor(thisIndex / countRowItems);
    if (rowPosition == thisRowPosition) {
      currentRowCounter++;
    }
  });

  /* settting each element widht according to it's position in a list and row */
  $('.item').each(function(e) {
    $(this).css({
      "flex": "0 1 " + itemInnerWidth + "px"
    });
    let thisIndex = $(this).index('.item');
    let thisColPosition = thisIndex % countRowItems;
    let thisRowPosition = Math.floor(thisIndex / countRowItems);
    if ((rowPosition == thisRowPosition) && (colPosition == thisColPosition)) {
      $(this).css({
        "flex": "0 1 " + (itemInnerWidth + expandSize) + "px"
      });
    } else if (rowPosition == thisRowPosition) {
      $(this).css({
        "flex": "0 1 " + (itemInnerWidth - (expandSize / (currentRowCounter - 1))) + "px"
      });
    } else {
      $(this).css({
        "flex": ""
      });
    }
  });

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  margin: 0;
  padding: 0;
}

#box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
}

.item {
  background: gray;
  flex: 0 1 250px;
  height: 50px;
  transition: all .5s ease;
  margin: 0 15px 15px 15px;
}

.separator {
  flex: 0 1 100%;
}</code>```

```

Body:
I'm using grid-template-columns: repeat(auto-fit, 250px) to keep grid items 250px wide but automatically adjust number of row-items according to screen-width. Now I want that when I hover over an item, it expands taking a bit of its sibling's space, with its sibling getting shrunk. By console.log(), I found nextElementSibling that can be used. So I'm thinking of something like-

function expand(card){
    card.setAttribute("style","width: 300px;");
    card.nextElementSibling.setAttribute("style","width: 200px");
}

function restore(card){
    card.setAttribute("style","width: 250px;");
    card.nextElementSibling.setAttribute("style","width: 250px");
}

This seems pretty bad (I guess!) because I need to manage corner items separately and hence need to know the current number of items in a row. Also, when I hover over a card, the card does expand but because of repeat(auto-fit,250px), the card intersects its sibling because the individual cells remain fixed (250px).
How can I solve the issues? Or any better suggested solutions?
Here is my git repository.

Edit 1-
As to clarify my issues:

How to manage the corner items, i.e., for an item in the right corner I want its previous sibling shrink; not the next.

The cells remain fixed, i.e., the expanding item intercepts the shrinking item's border-

becomes

So how to deal with this behavior caused by auto-fit,250px?

Body:
I honestly tried to solve it using grid-template-columns: repeat(auto-fit, minmax(250px,auto)); and a different size of child elements, but in's too unstable and not working that way. But I don't think the grid is require for this task. The easiest way I see how this should be solved - using good old JavaScript (+jQuery) and flex. Although the right way will be resize all elements in a single row, not only nearest siblings of a hovered element. Try it on any screen size.

$(document).ready(function() {
  /* defines main digits */
  let boxWidth = $('#box').innerWidth();
  let itemOuterWidth = $('.item').outerWidth(true);
  let itemInnerWidth = $('.item').innerWidth();
  SetSeparators(boxWidth, itemOuterWidth);

  /* refresh main digits ater page resize */
  $(window).resize(function() {
    $('.item').css({
      "flex": ""
    });
    boxWidth = $('#box').innerWidth();
    itemOuterWidth = $('.item').outerWidth(true);
    itemInnerWidth = $('.item').innerWidth();
    SetSeparators(boxWidth, itemOuterWidth);
  });

  $('#box').on('mouseover', '.item', function(e) {
    GetElementsPosition($(this).index('.item'), $(this), boxWidth, itemOuterWidth, itemInnerWidth);
  });

  $('#box').on('mouseleave', '.item', function(e) {
    $('.item').css({
      "flex": ""
    });
  });

});

/* set separator elemet to avoid blocks to jump from row to row while resizing */
function SetSeparators(boxWidth, itemOuterWidth) {
  $('.separator').remove();
  let countRowItems = Math.floor(boxWidth / itemOuterWidth);
  $('<div class="separator"></div>').insertBefore('.item:nth-child(' + countRowItems + 'n+1)');
}

function GetElementsPosition(index, element, boxWidth, itemOuterWidth, itemInnerWidth) {

  /* calculating row items, column position and row position of a current elemet */
  let countRowItems = Math.floor(boxWidth / itemOuterWidth);
  let colPosition = index % countRowItems;
  let rowPosition = Math.floor(index / countRowItems);
  /* exmanpd size of a hovered element in pixels*/
  let expandSize = 50;

  /* counting number of items in a hovered row */
  let currentRowCounter = 0;
  $('.item').each(function(e) {
    let thisIndex = $(this).index('.item');
    let thisRowPosition = Math.floor(thisIndex / countRowItems);
    if (rowPosition == thisRowPosition) {
      currentRowCounter++;
    }
  });

  /* settting each element widht according to it's position in a list and row */
  $('.item').each(function(e) {
    $(this).css({
      "flex": "0 1 " + itemInnerWidth + "px"
    });
    let thisIndex = $(this).index('.item');
    let thisColPosition = thisIndex % countRowItems;
    let thisRowPosition = Math.floor(thisIndex / countRowItems);
    if ((rowPosition == thisRowPosition) && (colPosition == thisColPosition)) {
      $(this).css({
        "flex": "0 1 " + (itemInnerWidth + expandSize) + "px"
      });
    } else if (rowPosition == thisRowPosition) {
      $(this).css({
        "flex": "0 1 " + (itemInnerWidth - (expandSize / (currentRowCounter - 1))) + "px"
      });
    } else {
      $(this).css({
        "flex": ""
      });
    }
  });

}

* {
  box-sizing: border-box;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  margin: 0;
  padding: 0;
}

#box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
}

.item {
  background: gray;
  flex: 0 1 250px;
  height: 50px;
  transition: all .5s ease;
  margin: 0 15px 15px 15px;
}

.separator {
  flex: 0 1 100%;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box'>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
  <div class='item'></div>
</div>


来源: stackexchange

问:
How to share state (react)between electron's multiple windows?
I am developing a desktop app with react for UI and electron.

So, for now, I am fetching data from the server and saving it in the state using React's Context API to update the UI.

I am keeping the state and the function to add, remove and update state in the renderer process and with IPC I am sharing the data between renderer process through main process (as it should be).

But as the application is scaling I need a better approach. Something like a central state (if that's a thing).

P.S. can I use a database along with the Electron app if there is any real-time database such as rxdb?

答:
I had this exact same problem and I used electron-redux (https://github.com/hardchor/electron-redux).
I was also using react for my UI.</p>

ContentLicense: CC BY-SA 4.0


问:
Array is being overwritten via array_push()
I'm trying to push elements to an array for later averaging but every one that is pushed with array_push() will just overwrite so the expected array output of 10 elements is coming to just one with the last pushed value.

```<code>array:2 [▼
  "raw" => array:10 [▼
    "averagePar3GrossScore" => array:1 [▼
      0 => 5.67
    ]
    "averagePar4GrossScore" => array:1 [▶]
    "averagePar5GrossScore" => array:1 [▶]
    "averagePuttTotal" => array:1 [▶]
    "sumEagles" => array:1 [▶]
    "sumBirdies" => array:1 [▶]
    "sumPars" => array:1 [▶]
    "sumBogeys" => array:1 [▶]
    "sumDoubleBogeys" => array:1 [▶]
    "sumOverDoubleBogeys" => array:1 [▶]
  ]
  "averaged" => []
]
</code>```

```<code>// Temp data
$currentAverages = 0;
$averages = [
    "raw" => [
        "averagePar3GrossScore" => [],
        "averagePar4GrossScore" => [],
        "averagePar5GrossScore" => [],
        "averagePuttTotal" => [],
        "sumEagles" => [], // Use sum for average type
        "sumBirdies" => [], // Use sum for average type
        "sumPars" => [], // Use sum for average type
        "sumBogeys" => [], // Use sum for average type
        "sumDoubleBogeys" => [], // Use sum for average type
        "sumOverDoubleBogeys" => [] // Use sum for average type
    ],
    "averaged" => []
];

// Get initial stats
$stats = json_decode($this->stats($from, $to, $createdAfter, $createdBefore)->getBody());
$currentAverages = $stats->resultsCount;

foreach ($averages["raw"] as $statName => $statValue) {
    $testArr = [];
    foreach ($stats->roundExtendedStats as $roundKey => $round); {
        array_push($averages["raw"][$statName], $round->$statName);
        // $newStat = $round->$statName;
        // echo $newStat;
        //array_push($averages["raw"][$statName], $newStat);
    }
}

dd($averages);
</code>```

答:
foreach ($stats->roundExtendedStats as $roundKey => $round);

The semicolon at the end of this was causing the loop to execute but the code block was not getting run.

Removing that semicolon solved the issue and worked as expected.

Body:
I'm trying to push elements to an array for later averaging but every one that is pushed with array_push() will just overwrite so the expected array output of 10 elements is coming to just one with the last pushed value.

array:2 [▼
  "raw" => array:10 [▼
    "averagePar3GrossScore" => array:1 [▼
      0 => 5.67
    ]
    "averagePar4GrossScore" => array:1 [▶]
    "averagePar5GrossScore" => array:1 [▶]
    "averagePuttTotal" => array:1 [▶]
    "sumEagles" => array:1 [▶]
    "sumBirdies" => array:1 [▶]
    "sumPars" => array:1 [▶]
    "sumBogeys" => array:1 [▶]
    "sumDoubleBogeys" => array:1 [▶]
    "sumOverDoubleBogeys" => array:1 [▶]
  ]
  "averaged" => []
]

// Temp data
$currentAverages = 0;
$averages = [
    "raw" => [
        "averagePar3GrossScore" => [],
        "averagePar4GrossScore" => [],
        "averagePar5GrossScore" => [],
        "averagePuttTotal" => [],
        "sumEagles" => [], // Use sum for average type
        "sumBirdies" => [], // Use sum for average type
        "sumPars" => [], // Use sum for average type
        "sumBogeys" => [], // Use sum for average type
        "sumDoubleBogeys" => [], // Use sum for average type
        "sumOverDoubleBogeys" => [] // Use sum for average type
    ],
    "averaged" => []
];

// Get initial stats
$stats = json_decode($this->stats($from, $to, $createdAfter, $createdBefore)->getBody());
$currentAverages = $stats->resultsCount;

foreach ($averages["raw"] as $statName => $statValue) {
    $testArr = [];
    foreach ($stats->roundExtendedStats as $roundKey => $round); {
        array_push($averages["raw"][$statName], $round->$statName);
        // $newStat = $round->$statName;
        // echo $newStat;
        //array_push($averages["raw"][$statName], $newStat);
    }
}

dd($averages);


问:
relative path to uri
I have a Uri object - what property of it will give me the relative path? Of how can I decipher the relative path the file with this Uri. I am coding in c#.</p>

答:
You can add a relative path to the Uri like below.</p>

```<code>var Url = new Uri("/something/test", UriKind.Relative);
</code>```

ContentLicense: CC BY-SA 3.0

Title: relative path to uri

Body:
You can add a relative path to the Uri like below.

var Url = new Uri("/something/test", UriKind.Relative);


问:
Hudson doesn't checkout using symlinks when using SVN (Subversion)
The problem is that when Hudson checks out the files, it doesn't use symlinks. I've tried the svn13 and svn14 plug ins, but neither worked.</p>

答:
In CentOS, the line you should change reads:

```<code>JAVA_CMD="$JENKINS_JAVA_CMD $JENKINS_JAVA_OPTIONS -DJENKINS_HOME=$JENKINS_HOME -jar $JENKINS_WAR"
</code>```

Change it to:

```<code>JAVA_CMD="$JENKINS_JAVA_CMD $JENKINS_JAVA_OPTIONS -DJENKINS_HOME=$JENKINS_HOME -Dsvnkit.symlinks=true -jar $JENKINS_WAR"
</code>```

And restart jenkins

ContentLicense: CC BY-SA 2.5

Body:
In CentOS, the line you should change reads:

JAVA_CMD="$JENKINS_JAVA_CMD $JENKINS_JAVA_OPTIONS -DJENKINS_HOME=$JENKINS_HOME -jar $JENKINS_WAR"

Change it to:

JAVA_CMD="$JENKINS_JAVA_CMD $JENKINS_JAVA_OPTIONS -DJENKINS_HOME=$JENKINS_HOME -Dsvnkit.symlinks=true -jar $JENKINS_WAR"

And restart jenkins


问:
How to use a time interval for each iteration of a for loop?
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

```<code>let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}
</code>```

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

答:
You have a few errors in your code. First, there is no poemArray, only 'textArray`. In any case, here's my algorithm:

```<code>let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");
let poemArray = text.split(" "); // Array of words

function showWords() {
  if ( poemArray.length ) { // If there are more words to show
    mainId.textContent += (poemArray.shift() + " "); // Remove the first word and show it
    setInterval( showWords, 1000 ); // Show the next word in 1 second
  }
}
showWords() // Kick off the process by showing the first word
</code>```

Body:
I want to show each word of a string of text in 60 seconds intervals on screen and came up with something like this:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");

function showWords() {
  // Print words to the screen one at a time.

  let textArray = text.split(" ");
  for(let i = 0; i < poemArray.length; i++) {
    mainId.textContent = poemArray[i];
  }
}

I know that I should use a setInterval() method here, I'm not just sure how I should use it. I have tried to put the whole for loop as the function part of it and even tried to put the code inside the for loop as the function part and nothing works.

Body:
You have a few errors in your code. First, there is no poemArray, only 'textArray`. In any case, here's my algorithm:

let text = "Aliquam bibendum nulla et ligula vehicula semper. Nulla id posuere lorem, ac dignissim nunc. Quisque leo lorem, fringilla non ante ac, lobortis auctor leo. Fusce sit amet nibh vitae augue convallis iaculis eget ac erat.";

let mainId = document.getElementById("main");
let poemArray = text.split(" "); // Array of words

function showWords() {
  if ( poemArray.length ) { // If there are more words to show
    mainId.textContent += (poemArray.shift() + " "); // Remove the first word and show it
    setInterval( showWords, 1000 ); // Show the next word in 1 second
  }
}
showWords() // Kick off the process by showing the first word


问:
How import custom class in controller Laravel?
I have created a new directory Library in root of Laravel.

Inside I put the file with class:

class My {
  //
}

So, in controller Laravel I try to get access to this class:

```<code>App\Library\My
</code>```

But Laravel does not determine this path.

This is my code:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use View;

use App\Library\My;

class HomeController extends Controller
{
 //
}
</code>```

答:
A complete and functional example based on the posts here:

1 - Folder and file - Create a folder under app/, in this example we will create a folder called Library.

We will also inside the folder create a file with the name of your class, here we will create a class called My.

So we will have app/Library/My.php

2 - Class and method -  Now, for testing, inside the class create a static method called myMethod

```<code><?php

namespace App\Library;

class My
{
    public static function myMethod()
    {
        return 'it\'s work!';
    }
}
</code>```

3 - Controller - Now at the beginning of the Controller, we will declare the namespace of your Class with use:

```<code><?php

namespace App\Http\Controllers;
use App\Library\My;

//rest of the controller code
</code>```

Finally, to create an instance of the My class, in Controller, a new statement must be used:

```<code>//rest of the controller code

public function index()
{
    $whatever = new My;
    return $whatever::myMethod();
}
</code>```

Body:
I have created a new directory Library in root of Laravel.

Inside I put the file with class:

class My {
  //
}

So, in controller Laravel I try to get access to this class:

App\Library\My

But Laravel does not determine this path.

This is my code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use View;

use App\Library\My;

class HomeController extends Controller
{
 //
}

Body:
A complete and functional example based on the posts here:

1 - Folder and file - Create a folder under app/, in this example we will create a folder called Library.

We will also inside the folder create a file with the name of your class, here we will create a class called My.

So we will have app/Library/My.php

2 - Class and method -  Now, for testing, inside the class create a static method called myMethod

<?php

namespace App\Library;

class My
{
    public static function myMethod()
    {
        return 'it\'s work!';
    }
}

3 - Controller - Now at the beginning of the Controller, we will declare the namespace of your Class with use:

<?php

namespace App\Http\Controllers;
use App\Library\My;

//rest of the controller code

Finally, to create an instance of the My class, in Controller, a new statement must be used:

//rest of the controller code

public function index()
{
    $whatever = new My;
    return $whatever::myMethod();
}


问:
How can I run Tomcat with maven:run with my custom configuration file?
I want to run my Tomcat project by mvn tomcat:run

In which path can I put my tomcat-user.xml to load it dynamically ?

答:
Use the tomcat-maven-plugin, it has configuration for this.

See http://mojo.codehaus.org/tomcat-maven-plugin/run-mojo.html#additionalConfigFilesDir.


问:
How to use functions in Javascript to bulid an interactive text?
I'm trying to build an interactive text with Javascript. I can do it by using a new function each element I create, but if I do that I'll have too many functions.

Could somebody tell me what is wrong with the following code and what I should do so it works?
Thanks in advance.

<!DOCTYPE html>

Name:

        <button id="peter" onclick="includeName1(peter)">Peter</button>
        <button id="paul" onclick="includeName1(paul)">Paul</button>

Wife's name

        <button id="mary" onclick="includeName2(mary)">Mary</button>
        <button id="emma" onclick="includeName2(emma)">Emma</button>

How long have you been married?

        <input id="years" type="number" oninput="includeTime()">

My name is . I'm married to . We've been married for  years.

```

答:
You need to wrap the names in apostrophes, at the moment you're trying to pass an object called 'peter' to the function. On the input, you need to use value instead of innerHtml.

<!DOCTYPE html>

Name:

        <button id="peter" onclick="includeName1('peter')">Peter</button>
        <button id="paul" onclick="includeName1('paul')">Paul</button>

Wife's name

        <button id="mary" onclick="includeName2('mary')">Mary</button>
        <button id="emma" onclick="includeName2('emma')">Emma</button>

How long have you been married?

        <input id="years" type="number" oninput="includeTime()">

My name is . I'm married to . We've been married for  years.

```

Body:
You need to wrap the names in apostrophes, at the moment you're trying to pass an object called 'peter' to the function. On the input, you need to use value instead of innerHtml.

<!DOCTYPE html>

<html lang="en">
    <head>
    </head>
    <body>
        <div>
        <p>Name:</p>
        <button id="peter" onclick="includeName1('peter')">Peter</button>
        <button id="paul" onclick="includeName1('paul')">Paul</button>
        <p>Wife's name</p>
        <button id="mary" onclick="includeName2('mary')">Mary</button>
        <button id="emma" onclick="includeName2('emma')">Emma</button>
        <p>How long have you been married?</p>
        <input id="years" type="number" oninput="includeTime()">
        </div>
        <br/>

        <div>
        <p>My name is&nbsp;<span id="name1"></span>.&nbsp;I'm married to&nbsp;<span id="name2"></span>. We've been married for&nbsp;<span id="time"></span>&nbsp;years.
        </p>
        </div>

        <script>
            function includeName1(manName){
                if (manName == "peter") {
                    document.getElementById("name1").innerHTML = "Peter";}
                else if (manName == "paul") {
                    document.getElementById("name1").innerHTML = "Paul";
                }
                }

            function includeName2(womanName){
                if (womanName == "mary") {
                    document.getElementById("name2").innerHTML = "Mary";}
                else if (womanName == "emma") {
                    document.getElementById("name2").innerHTML = "Emma";
                }
                }

            function includeTime(){
                var x = document.getElementById("years").value;
                document.getElementById("time").innerHTML = x;
            }
        </script>
    </body>
</html>


问:
MySQLi Repeat Row Depending on Column Quantity Value
I have created a simple SQL statement to display which products customers have purchased from a woo commerce store.

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

Thanks

```<code>CURRENT VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

DESIRED VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

CODE

<?php

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT wppc_wc_customer_lookup.customer_id, wppc_wc_customer_lookup.first_name,
wppc_wc_customer_lookup.last_name, wppc_wc_customer_lookup.email,
wppc_wc_order_stats.customer_id, wppc_wc_order_stats.total_sales,
wppc_wc_order_stats.order_id, wppc_wc_order_stats.date_created, wppc_wc_order_stats.status,
wppc_woocommerce_order_items.order_id, wppc_woocommerce_order_items.order_item_name,
wppc_woocommerce_order_items.order_item_id, wppc_woocommerce_order_itemmeta.order_item_id,
wppc_woocommerce_order_itemmeta.meta_id, wppc_woocommerce_order_itemmeta.meta_key,
wppc_woocommerce_order_itemmeta.meta_value FROM wppc_wc_customer_lookup

LEFT JOIN wppc_wc_order_stats ON wppc_wc_customer_lookup.customer_id =
wppc_wc_order_stats.customer_id

LEFT JOIN wppc_woocommerce_order_items ON wppc_wc_order_stats.order_id =
wppc_woocommerce_order_items.order_id

LEFT JOIN wppc_woocommerce_order_itemmeta ON wppc_woocommerce_order_items.order_item_id =
wppc_woocommerce_order_itemmeta.order_item_id

WHERE wppc_woocommerce_order_itemmeta.meta_key = '_qty' AND
wppc_woocommerce_order_items.order_item_name = 'Product Name' AND
wppc_wc_order_stats.status = 'wc-completed'

ORDER BY wppc_wc_order_stats.date_created DESC";

$result = $conn->query($sql);

echo "<table border=\"1\"><tr>";
echo "<tr><th>Order ID</hr><th>First Name</hr><th>Last Name</hr><th>Email</hr><th>Total</hr>
<th>Order Date</hr><th>Product Name</hr><th>Quantity</hr>";

if ($result->num_rows > 0) {

// output data of each row
while($row = $result->fetch_assoc()) {

echo "<tr><td>".$row["order_id"]. " </td><td> " .$row["first_name"] . " </td><td> " .
$row["last_name"] . " </td> <td> " . $row["email"] . " </td><td> &pound".$row["total_sales"]
. " </td> <td>".$row["date_created"] . " </td> <td> ".$row["order_item_name"] . " </td> <td>
".$row["meta_value"] . " </td></tr> ";

}

} else {
echo "0 results";
}

echo "</table>";

$conn->close();
?>
</code>```

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

答:
If you are running MySQL 8.0, you can do this with a recursive query. Starting from your existing query, that would be:

```<code>with recursive
    data  as ( <... your query goes here ...> ),
    rcte as (
        select order_id, product_name, qty, 1 rn from data
        union all
        select order_id, product_name, qty, rn + 1 from rcte where rn < qty
)
select order_id, product_name, qty from rcte
</code>```

In earlier versions, you could use a table of numbers. Here is an example that would quantities up to 3:

```<code>select d.*
from ( <... your query goes here ...> ) d
inner join (select 1 qty union all select 2 union all select 3) n
    on n.qty <= d.qty
</code>```

You can expand the subquery with more union alls to handle greater quantities.

Body:
I have created a simple SQL statement to display which products customers have purchased from a woo commerce store.

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

Thanks

CURRENT VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

DESIRED VIEW

ORDER ID.  |   PRODUCT NAME.   | QTY
-------------------------------------
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   123     |       APPLE       |  3
   124     |       ORANGE      |  2
   124     |       ORANGE      |  2
   125     |       PEAR        |  1

CODE

<?php

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
 die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT wppc_wc_customer_lookup.customer_id, wppc_wc_customer_lookup.first_name,
wppc_wc_customer_lookup.last_name, wppc_wc_customer_lookup.email,
wppc_wc_order_stats.customer_id, wppc_wc_order_stats.total_sales,
wppc_wc_order_stats.order_id, wppc_wc_order_stats.date_created, wppc_wc_order_stats.status,
wppc_woocommerce_order_items.order_id, wppc_woocommerce_order_items.order_item_name,
wppc_woocommerce_order_items.order_item_id, wppc_woocommerce_order_itemmeta.order_item_id,
wppc_woocommerce_order_itemmeta.meta_id, wppc_woocommerce_order_itemmeta.meta_key,
wppc_woocommerce_order_itemmeta.meta_value FROM wppc_wc_customer_lookup

LEFT JOIN wppc_wc_order_stats ON wppc_wc_customer_lookup.customer_id =
wppc_wc_order_stats.customer_id

LEFT JOIN wppc_woocommerce_order_items ON wppc_wc_order_stats.order_id =
wppc_woocommerce_order_items.order_id

LEFT JOIN wppc_woocommerce_order_itemmeta ON wppc_woocommerce_order_items.order_item_id =
wppc_woocommerce_order_itemmeta.order_item_id

WHERE wppc_woocommerce_order_itemmeta.meta_key = '_qty' AND
wppc_woocommerce_order_items.order_item_name = 'Product Name' AND
wppc_wc_order_stats.status = 'wc-completed'

ORDER BY wppc_wc_order_stats.date_created DESC";

$result = $conn->query($sql);

echo "

";
echo "
Order ID
First Name
Last Name
Email
Total

Order Date
Product Name
Quantity
";

if ($result->num_rows > 0) {

// output data of each row
while($row = $result->fetch_assoc()) {

echo "
".$row["order_id"]. " 	 " .$row["first_name"] . " 	 " .
$row["last_name"] . " 	  " . $row["email"] . " 	 &pound".$row["total_sales"]
. " 	 ".$row["date_created"] . " 	  ".$row["order_item_name"] . "
".$row["meta_value"] . "
 ";

}

} else {
echo "0 results";
}

echo "
";

$conn->close();
?>

This is working great but i'm struggling to find a SQL function that repeats rows based on a value, maybe one doesn't exist and PHP is required, any help would be great.

Body:
If you are running MySQL 8.0, you can do this with a recursive query. Starting from your existing query, that would be:

with recursive
    data  as ( <... your query goes here ...> ),
    rcte as (
        select order_id, product_name, qty, 1 rn from data
        union all
        select order_id, product_name, qty, rn + 1 from rcte where rn < qty
)
select order_id, product_name, qty from rcte

In earlier versions, you could use a table of numbers. Here is an example that would quantities up to 3:

select d.*
from ( <... your query goes here ...> ) d
inner join (select 1 qty union all select 2 union all select 3) n
    on n.qty <= d.qty

You can expand the subquery with more union alls to handle greater quantities.


问:
Type placeholder in Template Literals?
So I was attempting this:

    if(location.href == `${base}/tours`) {
      console.log("in list")
    } else if (location.href == `${base}/tours/${string}`) {
      console.log("in detail");
    }```

And I get this error:

'string' only refers to a type, but is being used as a value here.

base is indeed a variable, and string I am hoping to just be a placeholder for any string.

I was wondering if it was even possible to have a type as a placeholder in template literals? In the second if I am checking for the baseURL/tours/<any string>, the any string could be tour-one, tour-two, tour-three...

答:
Template literals can only create a single, specific string. They cannot express the concept of "any string".

Instead, use startsWith:

```<code>if (location.href.startsWith(`${base}/tours/`)) {
  console.log("in detail");
}
</code>```

Or use a regular expression:

```<code>const pattern = new RegExp(`^${base}/tours/(.*)`);
const result = pattern.exec(location.href);
if (result) {
  console.log("in detail");
  // The part matched by `(.*)` will also be available as `result[1]`
}
</code>```

Stepping back, the cleanest solution would be to use a router library that handles these URLs for you. For example, in React you can use react-router.

Title: Type placeholder in Template Literals?

Body:
So I was attempting this:

    if(location.href == `${base}/tours`) {
      console.log("in list")
    } else if (location.href == `${base}/tours/${string}`) {
      console.log("in detail");
    }

And I get this error:

'string' only refers to a type, but is being used as a value here.

base is indeed a variable, and string I am hoping to just be a placeholder for any string.

I was wondering if it was even possible to have a type as a placeholder in template literals? In the second if I am checking for the baseURL/tours/<any string>, the any string could be tour-one, tour-two, tour-three...

Body:
Template literals can only create a single, specific string. They cannot express the concept of "any string".

Instead, use startsWith:

if (location.href.startsWith(`${base}/tours/`)) {
  console.log("in detail");
}

Or use a regular expression:

const pattern = new RegExp(`^${base}/tours/(.*)`);
const result = pattern.exec(location.href);
if (result) {
  console.log("in detail");
  // The part matched by `(.*)` will also be available as `result[1]`
}

Stepping back, the cleanest solution would be to use a router library that handles these URLs for you. For example, in React you can use react-router.


问:
Question about Java synchronized
The Java documentation says that "it is not possible for two invocations of synchronized methods on the same object to interleave".  What I need to know is whether synchronized will also prevent a synchronized method in two different instances of the same class from interleaving.

E.g. class Worker has method called process().  We have several instances of Worker running in their own threads.  We want to prevent more than one instance running the process() method simultaneously.  Will synchronized do this?

Thanks.

答:
I slightly disagree with Aasmund -- though agree a bit at the same time:
If you use a construct like this:

```<code>class Worker {
...
 public synchronized void process() {...}
}
</code>```

then Aasmund is right -- that won't prevent multiple instances of the Worker class to execute process() in parallel.
However, you can use the synchronized keyword still to synchronize on a static member to prevent that from happening:

```<code>class Worker {
 static Object o = new Object();
 ...
 public void process() {
  synchronized(o) {
   ...//perform the work here
  }
 }
</code>```

Title: Question about Java synchronized

Body:
I slightly disagree with Aasmund -- though agree a bit at the same time:
If you use a construct like this:

class Worker {
...
 public synchronized void process() {...}
}

then Aasmund is right -- that won't prevent multiple instances of the Worker class to execute process() in parallel.
However, you can use the synchronized keyword still to synchronize on a static member to prevent that from happening:

class Worker {
 static Object o = new Object();
 ...
 public void process() {
  synchronized(o) {
   ...//perform the work here
  }
 }


问:
Is there a particular syntax for using python relative imports alongside connexion?
I am currently trying to build an api using connexion. However, I am having some issues using relative local module imports through the connexion module, which modifies the underlying flask app. Here is a simplified overview of my file structure:

hall_of_fame_api

controller

____init____.py

routes.py

model

____init____.py

routes.py

____init____.py

config.py

create_db.py

swagger.yml

I am getting an error when I try to run 'python config.py' in my terminal. Here is config.py:

```<code>import os
import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

basedir = os.path.abspath(os.path.dirname(__file__))

# Create the Connexion application instance
connex_app = connexion.App(__name__, specification_dir=basedir)

# Get the underlying Flask app instance
app = connex_app.app
connex_app.add_api('swagger.yml')

# Configure the SQLAlchemy part of the app instance
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://doadmin:password@nba-player-db-do-user-7027314-0.db.ondigitalocean.com:25060/nba_test_1?sslmode=require'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create the SQLAlchemy db instance
db = SQLAlchemy(app)

# Initialize Marshmallow
ma = Marshmallow(app)
</code>```

And here is the error it gives:

```<code>Failed to add operation for GET /api/players
Failed to add operation for GET /api/players
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/connexion/apis/abstract.py", line 209, in add_paths
self.add_operation(path, method)
  File "/usr/local/lib/python3.7/site-packages/connexion/apis/abstract.py", line 173, in add_operation
    pass_context_arg_name=self.pass_context_arg_name
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/__init__.py", line 8, in make_operation
    return spec.operation_cls.from_spec(spec, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/swagger2.py", line 137, in from_spec
    **kwargs
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/swagger2.py", line 96, in __init__
    pass_context_arg_name=pass_context_arg_name
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/abstract.py", line 96, in __init__
    self._resolution = resolver.resolve(self)
  File "/usr/local/lib/python3.7/site-packages/connexion/resolver.py", line 40, in resolve
    return Resolution(self.resolve_function_from_operation_id(operation_id), operation_id)
  File "/usr/local/lib/python3.7/site-packages/connexion/resolver.py", line 66, in resolve_function_from_operation_id
    raise ResolverError(str(e), sys.exc_info())
connexion.exceptions.ResolverError: <ResolverError: module 'controller.routes' has no attribute 'read_all'>
</code>```

This error comes specifically from line 12 where connexion is trying to add the swagger.yml file, here is that for reference as well:

```<code>swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Swagger REST Article
consumes:
  - "application/json"
produces:
  - "application/json"

basePath: "/api"

# Paths supported by the server application
paths:
  /players:
    get:
      operationId: "controller.routes.read_all"
      tags:
        - "People"
      summary: "The people data structure supported by the server application"
      description: "Read the list of people"
      responses:
        200:
          description: "Successful read people list operation"
          schema:
            type: "array"
            items:
              properties:
                fname:
                  type: "string"
                lname:
                  type: "string"
                timestamp:
                  type: "string"
</code>```

Now here is where I am confused, because my routes.py file does have a function defined as read_all(), here is that file:

```<code>from model.models import Regseason, RegSchema, Playoffs, PlayoffSchema

def read_all():

    return Regseason.query.all()
</code>```

I have been racking my brain over this bug for almost 24 hours, any guidance would be greatly appreciated. Thanks in advance!

答: Please add a extra field x-openapi-router-controller below operationid. It is used by Connexion to map which module to send requests to. It is combined together with OperationId to go to correct module and function.</p>

Body:
I am currently trying to build an api using connexion. However, I am having some issues using relative local module imports through the connexion module, which modifies the underlying flask app. Here is a simplified overview of my file structure:

hall_of_fame_api

controller

____init____.py

routes.py

model

____init____.py

routes.py

____init____.py

config.py

create_db.py

swagger.yml

I am getting an error when I try to run 'python config.py' in my terminal. Here is config.py:

import os
import connexion
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow

basedir = os.path.abspath(os.path.dirname(__file__))

# Create the Connexion application instance
connex_app = connexion.App(__name__, specification_dir=basedir)

# Get the underlying Flask app instance
app = connex_app.app
connex_app.add_api('swagger.yml')

# Configure the SQLAlchemy part of the app instance
app.config['SQLALCHEMY_ECHO'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://doadmin:password@nba-player-db-do-user-7027314-0.db.ondigitalocean.com:25060/nba_test_1?sslmode=require'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# Create the SQLAlchemy db instance
db = SQLAlchemy(app)

# Initialize Marshmallow
ma = Marshmallow(app)

And here is the error it gives:

Failed to add operation for GET /api/players
Failed to add operation for GET /api/players
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/connexion/apis/abstract.py", line 209, in add_paths
self.add_operation(path, method)
  File "/usr/local/lib/python3.7/site-packages/connexion/apis/abstract.py", line 173, in add_operation
    pass_context_arg_name=self.pass_context_arg_name
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/__init__.py", line 8, in make_operation
    return spec.operation_cls.from_spec(spec, *args, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/swagger2.py", line 137, in from_spec
    **kwargs
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/swagger2.py", line 96, in __init__
    pass_context_arg_name=pass_context_arg_name
  File "/usr/local/lib/python3.7/site-packages/connexion/operations/abstract.py", line 96, in __init__
    self._resolution = resolver.resolve(self)
  File "/usr/local/lib/python3.7/site-packages/connexion/resolver.py", line 40, in resolve
    return Resolution(self.resolve_function_from_operation_id(operation_id), operation_id)
  File "/usr/local/lib/python3.7/site-packages/connexion/resolver.py", line 66, in resolve_function_from_operation_id
    raise ResolverError(str(e), sys.exc_info())
connexion.exceptions.ResolverError: <ResolverError: module 'controller.routes' has no attribute 'read_all'>

This error comes specifically from line 12 where connexion is trying to add the swagger.yml file, here is that for reference as well:

swagger: "2.0"
info:
  description: This is the swagger file that goes with our server code
  version: "1.0.0"
  title: Swagger REST Article
consumes:
  - "application/json"
produces:
  - "application/json"

basePath: "/api"

# Paths supported by the server application
paths:
  /players:
    get:
      operationId: "controller.routes.read_all"
      tags:
        - "People"
      summary: "The people data structure supported by the server application"
      description: "Read the list of people"
      responses:
        200:
          description: "Successful read people list operation"
          schema:
            type: "array"
            items:
              properties:
                fname:
                  type: "string"
                lname:
                  type: "string"
                timestamp:
                  type: "string"

Now here is where I am confused, because my routes.py file does have a function defined as read_all(), here is that file:

from model.models import Regseason, RegSchema, Playoffs, PlayoffSchema

def read_all():

    return Regseason.query.all()

I have been racking my brain over this bug for almost 24 hours, any guidance would be greatly appreciated. Thanks in advance!


问:
Insert Select into with same ID
Insert Split Delimited Strings in a Column with same ID.

Lets say I have demo setup as follows:

```<code>USE DEMODATABASE
GO

CREATE TABLE EMPLOYEEID_Address
  (
     ID            INT ,
     Address VARCHAR(MAX)
  )
</code>```

I declare some variables

```<code>DECLARE @id INT
DECLARE @Addresses VARCHAR(MAX)
DECLARE @SEPARATOR CHAR(1)
SET @id = 1
SET @SEPARATOR='|'
SET @Addresses='159 North Manchester Rd.
Edison, NJ 08817|209 West Fulton Lane
Braintree, MA 02184|...'
</code>```

Note: the @addresses sting is dynamic and not fixed

Now my aim is to insert into table EMPLOYEEID_Address multiple address with same the id using the STRING_SPLIT function.

```<code>/*TARGET TABLE*/
Id  Address
1   159 North Manchester Rd. Edison, NJ 08817
1   209 West Fulton LaneBraintree, MA 02184
1   ...
</code>```

So I tried:

```<code>INSERT INTO EMPLOYEEID_Address
            (ID,Address)
Select @id as ID,
SELECT *
FROM   STRING_SPLIT(@EMPLOYEENAME, @SEPARATOR)
</code>```

But this didn't work, while

```<code>INSERT INTO EMPLOYEEID_Address
            (Address)
SELECT *
FROM   STRING_SPLIT(@EMPLOYEENAME, @SEPARATOR)
</code>```

works with result as:

```<code>Id   Address
NULL 159 North Manchester Rd. Edison, NJ 08817
NULL 209 West Fulton LaneBraintree, MA 02184
</code>```

Is there any way I can achieve this or a better way to achieve my target table with id and string passed as parameters?

答:
I think you want:

```<code>INSERT INTO EMPLOYEEID_Address (ID, Address)
    Select @id as ID, s.value
    from STRING_SPLIT(@EMPLOYEENAME, @SEPARATOR) s;
</code>```

The column returned by string_split() is called value.

Title: Insert Select into with same ID

Body:
Insert Split Delimited Strings in a Column with same ID.

Lets say I have demo setup as follows:

USE DEMODATABASE
GO

CREATE TABLE EMPLOYEEID_Address
  (
     ID            INT ,
     Address VARCHAR(MAX)
  )

I declare some variables

DECLARE @id INT
DECLARE @Addresses VARCHAR(MAX)
DECLARE @SEPARATOR CHAR(1)
SET @id = 1
SET @SEPARATOR='|'
SET @Addresses='159 North Manchester Rd.
Edison, NJ 08817|209 West Fulton Lane
Braintree, MA 02184|...'

Note: the @addresses sting is dynamic and not fixed

Now my aim is to insert into table EMPLOYEEID_Address multiple address with same the id using the STRING_SPLIT function.

/*TARGET TABLE*/
Id  Address
1   159 North Manchester Rd. Edison, NJ 08817
1   209 West Fulton LaneBraintree, MA 02184
1   ...

So I tried:

INSERT INTO EMPLOYEEID_Address
            (ID,Address)
Select @id as ID,
SELECT *
FROM   STRING_SPLIT(@EMPLOYEENAME, @SEPARATOR)

But this didn't work, while

INSERT INTO EMPLOYEEID_Address
            (Address)
SELECT *
FROM   STRING_SPLIT(@EMPLOYEENAME, @SEPARATOR)

works with result as:

Id   Address
NULL 159 North Manchester Rd. Edison, NJ 08817
NULL 209 West Fulton LaneBraintree, MA 02184

Is there any way I can achieve this or a better way to achieve my target table with id and string passed as parameters?

Body:
I think you want:

INSERT INTO EMPLOYEEID_Address (ID, Address)
    Select @id as ID, s.value
    from STRING_SPLIT(@EMPLOYEENAME, @SEPARATOR) s;

The column returned by string_split() is called value.


问:
d3 transition wait for previous?
```<code>d3.select('#' + linkId[0]).transition().duration(2500).attr('stroke', 'green');
d3.select('#' + nodeId[0]).transition().duration(5000).attr('fill', 'blue');
</code>```

I have the above code that is animating a graph traversal. I want the second transition to only activate (and preferably remove the duration) once the link has been transitioned. How would i accomplish this? I have tried putting the whole second line of code within a timeout like so:

```<code>setTimeout(() => {  d3 transition here }, 2500);
</code>```

However this completely messed up the timing of events. Im basically looking for something similar to python where you can call .sleep(milliseconds) to specify code execution wait a certain amount of time.

答:
There are two quick options available:

transition.delay()

You could use transition.delay(time) which allows you to specify a delay before a transition starts. This would look like:

```<code>d3.select('#' + linkId[0]).transition().duration(2500).attr('stroke', 'green');
d3.select('#' + nodeId[0]).transition().delay(2500).duration(5000).attr('fill', 'blue');
</code>```

While simple, I'd suggest using the next approach instead.

transition.on("end", ... )

Another option is to use transition.on("end", function() { /* set up next transition */ }). Now .on("end",callbackFunction) will trigger on the end of each transition (if transitioning many elements, it'll trigger when each element finishes its transition), but you are transitioning single elements (as IDs are unique), so you could use something like this:

```<code>d3.select('#' + linkId[0]).transition()
  .duration(2500)
  .attr('stroke', 'green')
  .on("end", function() {
      d3.select('#' + nodeId[0]).transition().duration(5000).attr('fill', 'blue');
  })
</code>```

If you had many elements transitioning simultaneously you'd need to modify this slightly to check to see if any transitions were still in progress before starting the next transition.

Title: d3 transition wait for previous?

Body:
d3.select('#' + linkId[0]).transition().duration(2500).attr('stroke', 'green');
d3.select('#' + nodeId[0]).transition().duration(5000).attr('fill', 'blue');

I have the above code that is animating a graph traversal. I want the second transition to only activate (and preferably remove the duration) once the link has been transitioned. How would i accomplish this? I have tried putting the whole second line of code within a timeout like so:

setTimeout(() => {  d3 transition here }, 2500);

However this completely messed up the timing of events. Im basically looking for something similar to python where you can call .sleep(milliseconds) to specify code execution wait a certain amount of time.

Body:
There are two quick options available:

transition.delay()

You could use transition.delay(time) which allows you to specify a delay before a transition starts. This would look like:

d3.select('#' + linkId[0]).transition().duration(2500).attr('stroke', 'green');
d3.select('#' + nodeId[0]).transition().delay(2500).duration(5000).attr('fill', 'blue');

While simple, I'd suggest using the next approach instead.

transition.on("end", ... )

Another option is to use transition.on("end", function() { /* set up next transition */ }). Now .on("end",callbackFunction) will trigger on the end of each transition (if transitioning many elements, it'll trigger when each element finishes its transition), but you are transitioning single elements (as IDs are unique), so you could use something like this:

d3.select('#' + linkId[0]).transition()
  .duration(2500)
  .attr('stroke', 'green')
  .on("end", function() {
      d3.select('#' + nodeId[0]).transition().duration(5000).attr('fill', 'blue');
  })

If you had many elements transitioning simultaneously you'd need to modify this slightly to check to see if any transitions were still in progress before starting the next transition.


问:
How do you select a string value left of a specified section of a string, not including empty space?
Using vanilla javascript, how do you select the first string value left of a specified section of a string and not include the empty space?

For example, there is a string 1 hr 30 min

How do you get the 1 value left of hr and how do you get the 30 value left of min?

```<code>var string = "1 hr 30 min";
if (string.includes("hr")) {
    // get the 1 value
}
if (string.includes("min")) {
    // get the 30 value
}
</code>```

答:
this function will split your string into two string, containing only hours and win, then you just have to parse it ton integer : </p>

```<code>const getHoursAndMin = () => {
  const _string = string.replace('min','')
  const [hours,min] = _string.split('hr')
  console.log(parseInt(hours),parseInt(min))
}
</code>```

Body:
Using vanilla javascript, how do you select the first string value left of a specified section of a string and not include the empty space?

For example, there is a string 1 hr 30 min

How do you get the 1 value left of hr and how do you get the 30 value left of min?

var string = "1 hr 30 min";
if (string.includes("hr")) {
    // get the 1 value
}
if (string.includes("min")) {
    // get the 30 value
}

Body:
this function will split your string into two string, containing only hours and win, then you just have to parse it ton integer :

const getHoursAndMin = () => {
  const _string = string.replace('min','')
  const [hours,min] = _string.split('hr')
  console.log(parseInt(hours),parseInt(min))
}


问:
How can I start my Windows service on startup, and prevent users from stopping/restarting it?
i have developed the window service. in this i want to start the service only when starting the computer. user can not start/stop/restart the service.manually these all thing are handle when user start the computer.

or lock the all properties from the user.all working done by coding when we start the computer.

答:
There are two ways to accomplish this that I can recommend.

Permissions.  Normal users should not have permissions to start/stop services.  If they do and are not administrators, you can at least remove permissions to start/stop the particular service you want to protect.  http://msmvps.com/blogs/erikr/archive/2007/09/26/set-permissions-on-a-specific-service-windows.aspx

Restart.  You can have a scheduled task to automatically restart the service if it is stopped.  Again, you can use permissions to make sure the scheduled task is not modified.  You can even run the task remotely as long as the target computer is on the network.


问:
How to set default PyCharm interpreter?
My PyCharm installation has two interpreters available:

Python 3.3.2 (/usr/bin/python3.3m)

Python 2.7.5 (/usr/bin/python2.7)

Whenever I open a new project it sets the interpreter to Python 3. Since I work mostly with 2.7, this means in most cases I have to reconfigure it. How do I change it to use 2.7 by default for new projects?

Update: After setting the default interpreter to Python 2.7.5 in File → Default Settings → Project Interpreter and removing the .idea/misc.xml file, the interpreter is now not set at all in misc.xml. Better than setting it to Python 3.3, but still...

答:
This has now changed again on the latest version of PyCharm. It is now
File > New Project Settings > Settings for New Projects

Screenshot

Title: How to set default PyCharm interpreter?


问:
How to download data from a Ruby on Rails console running on Heroku?
I have an app running on Heroku that has some data in a database that I need to download into a format that will be easy to work with locally (json, csv, serialized Ruby object, etc). I know how to connect to the Rails console remotely:

```<code>heroku run console
</code>```

Then I can fetch my model data from the database:

```<code>records_json = Record.all.to_json
</code>```

Now that I have the data, how do I download it?

答:
If it's not a ton of data, you should just be able to copy and paste the output to a file. Run from the console

```<code>puts Record.all.to_json
</code>```

If it is a lot of data, you can run

```<code>heroku run:detached rails runner "puts Record.all.to_json"
</code>```

Per the documentation, the output will go to your logs so you could copy & paste from there. Read more here: https://devcenter.heroku.com/articles/heroku-cli-commands#heroku-run-detached

If you want to be able to download a json file at any time of just this model, you could add a json response to any controller method, like this

```<code>respond_to do |format|
  format.html
  format.json { render json: Record.all }
end
</code>```

Then just navigate to /the_path_you_chose.json

Body:
I have an app running on Heroku that has some data in a database that I need to download into a format that will be easy to work with locally (json, csv, serialized Ruby object, etc). I know how to connect to the Rails console remotely:

heroku run console

Then I can fetch my model data from the database:

records_json = Record.all.to_json

Now that I have the data, how do I download it?

Body:
If it's not a ton of data, you should just be able to copy and paste the output to a file. Run from the console

puts Record.all.to_json

If it is a lot of data, you can run

heroku run:detached rails runner "puts Record.all.to_json"

Per the documentation, the output will go to your logs so you could copy & paste from there. Read more here: https://devcenter.heroku.com/articles/heroku-cli-commands#heroku-run-detached

If you want to be able to download a json file at any time of just this model, you could add a json response to any controller method, like this

respond_to do |format|
  format.html
  format.json { render json: Record.all }
end

Then just navigate to /the_path_you_chose.json


问:
How to count the number of letters in a word?
I'm trying to create a program where if you input a word, it will print out each letter of the word and how many times the letter appears in that word.

Eg; when I input "aaaarggh", the output should be "a 4 r 1 g 2 h 1".

```<code>def compressed (word):
    count = 0
    index = 0
    while index < len(word):
        letter = word[index]
        for letter in word:
            index = index + 1
            count = count + 1
            print(letter, count)
        break

print("Enter a word:")
word = input()
compressed(word)
</code>```

So far it just prints out each letter and position in the word.
Any help appreciated, thank you!

(no using dict method)

答:
Counter is concise. But here's an alternative using defaultdict, which is a subclass of dict.

from collections import defaultdict

test_input = "aaaarggh"

d = defaultdict(int)
for letter in test_input:
    d[letter] += 1
```

https://docs.python.org/3.6/library/collections.html#defaultdict-examples

Body:
I'm trying to create a program where if you input a word, it will print out each letter of the word and how many times the letter appears in that word.

Eg; when I input "aaaarggh", the output should be "a 4 r 1 g 2 h 1".

def compressed (word):
    count = 0
    index = 0
    while index < len(word):
        letter = word[index]
        for letter in word:
            index = index + 1
            count = count + 1
            print(letter, count)
        break

print("Enter a word:")
word = input()
compressed(word)

So far it just prints out each letter and position in the word.
Any help appreciated, thank you!

(no using dict method)

Body:
Counter is concise. But here's an alternative using defaultdict, which is a subclass of dict.

from collections import defaultdict

test_input = "aaaarggh"

d = defaultdict(int)
for letter in test_input:
    d[letter] += 1

https://docs.python.org/3.6/library/collections.html#defaultdict-examples


问:
Comprehensive JavaDoc-like documentation for Mozilla/Firefox extension developers?
Is there any thing like JavaDoc for Mozilla/Firefox that helps extension developers?

For example where can I find what delayedOpenTab() does and how to use it?

答: IMHO, MDN is the main resource for all things Mozilla. And here is a page about delayedOpenTab().


问:
new PR includes changes from older PR in Github
I have created 2 PR's to a repo; I was making changes to the new PR and did a

```<code>git pull upstream/master
</code>```

and then create a new branch with git checkout -b <new-Pr>
and modified a file and did git add . and then git commit and git push origin <new-Pr> by doing this my files which I modified from older PR(which was not needed) also appeared in the new PR. How can I rectify the same?

答:
You could rebase on top of another base branch:</p>

```<code>git rebase --onto new-base old-pr-branch new-pr-branch
</code>```

Body:
I have created 2 PR's to a repo; I was making changes to the new PR and did a

git pull upstream/master

and then create a new branch with git checkout -b <new-Pr>
and modified a file and did git add . and then git commit and git push origin <new-Pr> by doing this my files which I modified from older PR(which was not needed) also appeared in the new PR. How can I rectify the same?

Body:
You could rebase on top of another base branch:

git rebase --onto new-base old-pr-branch new-pr-branch


问:
Profiling distributed systems
I was wondering about possible ways to track down performance bottlenecks in distributed systems. I am aware of tools like X-Trace and its offspring (e.g. Dapper) but I am more curious about the methodology rather than specific tools.

In other words, given a distributed system without any obvious bottlenecks, how do you study and improve its performance?

答:
Honestly, that's a great question, and there isn't a consensus on what's the best way to do this. One of the most basic ways is logging, where you basically just dump a bunch of system events into a file and you can parse those logs to find the timing between events to figure out how long they take. Another approach is tracing (which is used by Xtrace). In tracing, you keep track of the lifetime of a request. For example, if you send a request to a service that uses a microservice architecture, you will keep track of the thread, process ID, and latency of the request as it goes through the microservices of the system.

The tricky part is figuring out what you want to keep track in the trace of a request, and that will be dependent on what your distributed system is trying to accomplish. For example, an obvious metric of interest for performance is latency, so you will measure how long the request spent on each service. Another metric that could be interesting is contention, so you can measure the contention in the CPU when the request was going through the system. One of the problems with many of these profiling tools is that they give you overall metrics for the system or a request, but when you want to find a performance issue you want to figure out if a request is an outlier or not. It is thus essential to compare the latency, contention, and memory consumption of a request to other similar request in the system to figure out whether it is abnormal.

Title: Profiling distributed systems


问:
Caused by: java.lang.ClassNotFoundException: org.opensaml.xml.validation.ValidatingXMLObject
I am using axis2.war in my ear and I am packing all my jars in APP-INF and pointing them from the of axis2/META-INT/Manifest.in[Class-Path]. I am using ws security.

When I am request it from axis2 client I got the below error.

12:55:05,359 INFO  [STDOUT] [ERROR]
    org/opensaml/xml/validation/ValidatingXMLObject 12:55:05,359 INFO
    [STDOUT] java.lang.NoClassDefFoundError:
    org/opensaml/xml/validation/ValidatingXMLObject 12:55:05,360 INFO
    [STDOUT]     at java.lang.ClassLoader.defineClass1(Native Method)
    12:55:05,360 INFO  [STDOUT]     at
    java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
    12:55:05,360 INFO  [STDOUT]     at
    java.lang.ClassLoader.defineClass(ClassLoader.java:615) 12:55:05,360
    INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoader.access$200(BaseClassLoader.java:52)
    12:55:05,360 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoader$2.run(BaseClassLoader.java:650)
    12:55:05,360 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoader$2.run(BaseClassLoader.java:609)
    12:55:05,360 INFO  [STDOUT]     at
    java.security.AccessController.doPrivileged(Native Method)
    12:55:05,361 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoader.loadClassLocally(BaseClassLoader.java:608)
    12:55:05,361 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoader.loadClassLocally(BaseClassLoader.java:585)
    12:55:05,361 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseDelegateLoader.loadClass(BaseDelegateLoader.java:156)
    12:55:05,361 INFO  [STDOUT]     at
    org.jboss.classloader.spi.filter.FilteredDelegateLoader.doLoadClass(FilteredDelegateLoader.java:141)
    12:55:05,361 INFO  [STDOUT]     at
    org.jboss.classloader.spi.filter.FilteredDelegateLoader.loadClass(FilteredDelegateLoader.java:132)
    12:55:05,361 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.ClassLoadingTask$ThreadTask.run(ClassLoadingTask.java:461)
    12:55:05,362 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.ClassLoaderManager.nextTask(ClassLoaderManager.java:262)
    12:55:05,362 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.ClassLoaderManager.process(ClassLoaderManager.java:161)
    12:55:05,362 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:280)
    12:55:05,362 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:1172)
    12:55:05,362 INFO  [STDOUT]     at
    org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:886)

12:55:05,362 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.doLoadClass(BaseClassLoader.java:505)
  12:55:05,362 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:450)
  12:55:05,363 INFO  [STDOUT]     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:247) 12:55:05,365
  INFO  [STDOUT]     at java.lang.ClassLoader.defineClass1(Native
  Method) 12:55:05,366 INFO  [STDOUT]     at
  java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
  12:55:05,367 INFO  [STDOUT]     at
  java.lang.ClassLoader.defineClass(ClassLoader.java:615) 12:55:05,369
  INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.access$200(BaseClassLoader.java:52)
  12:55:05,370 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader$2.run(BaseClassLoader.java:650)
  12:55:05,372 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader$2.run(BaseClassLoader.java:609)
  12:55:05,373 INFO  [STDOUT]     at
  java.security.AccessController.doPrivileged(Native Method)
  12:55:05,374 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClassLocally(BaseClassLoader.java:608)
  12:55:05,375 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClassLocally(BaseClassLoader.java:585)
  12:55:05,376 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseDelegateLoader.loadClass(BaseDelegateLoader.java:156)
  12:55:05,377 INFO  [STDOUT]     at
  org.jboss.classloader.spi.filter.FilteredDelegateLoader.doLoadClass(FilteredDelegateLoader.java:141)
  12:55:05,378 INFO  [STDOUT]     at
  org.jboss.classloader.spi.filter.FilteredDelegateLoader.loadClass(FilteredDelegateLoader.java:132)
  12:55:05,379 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.ClassLoadingTask$ThreadTask.run(ClassLoadingTask.java:461)
  12:55:05,380 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.ClassLoaderManager.nextTask(ClassLoaderManager.java:262)
  12:55:05,381 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.ClassLoaderManager.process(ClassLoaderManager.java:161)
  12:55:05,382 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:280)
  12:55:05,384 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:1172)
  12:55:05,386 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:886)
  12:55:05,387 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.doLoadClass(BaseClassLoader.java:505)
  12:55:05,388 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:450)
  12:55:05,389 INFO  [STDOUT]     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:247) 12:55:05,390
  INFO  [STDOUT]     at
  org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:89)
  12:55:05,391 INFO  [STDOUT]     at
  org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
  12:55:05,392 INFO  [STDOUT]     at
  org.apache.axis2.engine.Phase.invoke(Phase.java:313) 12:55:05,393 INFO
  [STDOUT]     at
  org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:262)
  12:55:05,394 INFO  [STDOUT]     at
  org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:168)
  12:55:05,395 INFO  [STDOUT]     at
  org.apache.axis2.transport.http.HTTPTransportUtils.processHTTPPostRequest(HTTPTransportUtils.java:172)
  12:55:05,396 INFO  [STDOUT]     at
  org.apache.axis2.transport.http.AxisServlet.doPost(AxisServlet.java:146)
  12:55:05,397 INFO  [STDOUT]     at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
  12:55:05,398 INFO  [STDOUT]     at
  javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
  12:55:05,399 INFO  [STDOUT]     at
  org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324)
  12:55:05,401 INFO  [STDOUT]     at
  org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242)
  12:55:05,403 INFO  [STDOUT]     at
  org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
  12:55:05,404 INFO  [STDOUT]     at
  org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
  12:55:05,405 INFO  [STDOUT]     at
  org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:181)
  12:55:05,406 INFO  [STDOUT]     at
  org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.event(CatalinaContext.java:285)
  12:55:05,407 INFO  [STDOUT]     at
  org.jboss.modcluster.catalina.CatalinaContext$RequestListenerValve.invoke(CatalinaContext.java:261)
  12:55:05,408 INFO  [STDOUT]     at
  org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:88)
  12:55:05,409 INFO  [STDOUT]     at
  org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:100)
  12:55:05,410 INFO  [STDOUT]     at
  org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
  12:55:05,411 INFO  [STDOUT]     at
  org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
  12:55:05,412 INFO  [STDOUT]     at
  org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
  12:55:05,413 INFO  [STDOUT]     at
  org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
  12:55:05,415 INFO  [STDOUT]     at
  org.jboss.web.tomcat.service.request.ActiveRequestResponseCacheValve.invoke(ActiveRequestResponseCacheValve.java:53)
  12:55:05,416 INFO  [STDOUT]     at
  org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:362)
  12:55:05,417 INFO  [STDOUT]     at
  org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
  12:55:05,419 INFO  [STDOUT]     at
  org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:654)
  12:55:05,420 INFO  [STDOUT]     at
  org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:951)
  12:55:05,422 INFO  [STDOUT]     at
  java.lang.Thread.run(Thread.java:662) 12:55:05,423 INFO  [STDOUT]
  Caused by: java.lang.ClassNotFoundException:
  org.opensaml.xml.validation.ValidatingXMLObject 12:55:05,424 INFO
  [STDOUT]     at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
  12:55:05,425 INFO  [STDOUT]     at
  java.security.AccessController.doPrivileged(Native Method)
  12:55:05,426 INFO  [STDOUT]     at
  java.net.URLClassLoader.findClass(URLClassLoader.java:190)
  12:55:05,427 INFO  [STDOUT]     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:306) 12:55:05,428
  INFO  [STDOUT]     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
  12:55:05,429 INFO  [STDOUT]     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:247) 12:55:05,430
  INFO  [STDOUT]     at java.lang.Class.forName0(Native Method)
  12:55:05,431 INFO  [STDOUT]     at
  java.lang.Class.forName(Class.java:249) 12:55:05,432 INFO  [STDOUT]

  at
  org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:304)
  12:55:05,433 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoaderDomain.loadClass(BaseClassLoaderDomain.java:1172)
  12:55:05,434 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClassFromDomain(BaseClassLoader.java:886)
  12:55:05,436 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.doLoadClass(BaseClassLoader.java:505)
  12:55:05,438 INFO  [STDOUT]     at
  org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:450)
  12:55:05,439 INFO  [STDOUT]     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:247) 12:55:05,440
  INFO  [STDOUT]     ... 70 more

Note: In -verbose:class log org.opensaml.xml.validation.ValidatingXMLObject is loaded from the xmltooling.jar and I am using jboss 6

[Loaded org.opensaml.xml.validation.ValidatingXMLObject from vfs:/D:/maven/Server/jboss-6.1.0/server/default/deploy/bpms.ear/APP-INF/lib/xmltooling-1.2.0.jar/]

答: Verify if you have correctly set the dependency for xmltooling.jar</p>


问:
Split a Javascript class (ES6) over multiple files?
I have a Javascript class (in ES6) that is getting quite long. To organize it better I'd like to split it over 2 or 3 different files. How can I do that?

Currently it looks like this in a single file:

```<code>class foo extends bar {
   constructor(a, b) {} // Put in file 1
   methodA(a, b) {} // Put in file 1
   methodB(a, b) {} // Put in file 2
   methodC(a, b) {} // Put in file 2
}
</code>```

Thanks!

Body:
I have a Javascript class (in ES6) that is getting quite long. To organize it better I'd like to split it over 2 or 3 different files. How can I do that?

Currently it looks like this in a single file:

class foo extends bar {
   constructor(a, b) {} // Put in file 1
   methodA(a, b) {} // Put in file 1
   methodB(a, b) {} // Put in file 2
   methodC(a, b) {} // Put in file 2
}

Thanks!

Body:
Here's my solution. It:

uses regular modern classes and .bind()ing, no prototype. (EDIT: Actually, see the comments for more on this, it may not be desirable.)

works with modules. (I'll show an alternative option if you don't use modules.)

supports easy conversion from existing code.

yields no concern for function order (if you do it right).

yields easy to read code.

is low maintenance.

unfortunately does not play well with static functions in the same class, you'll need to split those off.

First, place this in a globals file or as the first <script> tag etc.:

BindToClass(functionsObject, thisClass) {
    for (let [ functionKey, functionValue ] of Object.entries(functionsObject)) {
        thisClass[functionKey] = functionValue.bind(thisClass);
    }
}

This loops through an object and assigns and binds each function, in that object, by its name, to the class. It .bind()'s it for the this context, so it's like it was in the class to begin with.

Then extract your function(s) from your class into a separate file like:

//Use this if you're using NodeJS/Webpack. If you're using regular modules,
//use `export` or `export default` instead of `module.exports`.
//If you're not using modules at all, you'll need to map this to some global
//variable or singleton class/object.
module.exports = {
    myFunction: function() {
        //...
    },

    myOtherFunction: function() {
        //...
    }
};

Finally, require the separate file and call BindToClass like this in the constructor() {} function of the class, before any other code that might rely upon these split off functions:

//If not using modules, use your global variable or singleton class/object instead.
let splitFunctions = require('./SplitFunctions');

class MySplitClass {
    constructor() {
        BindToClass(splitFunctions, this);
    }
}

Then the rest of your code remains the same as it would if those functions were in the class to begin with:

let msc = new MySplitClass();
msc.myFunction();
msc.myOtherFunction();

Likewise, since nothing happens until the functions are actually called, as long as BindToClass() is called first, there's no need to worry about function order.  Each function, inside and outside of the class file, can still access any property or function within the class, as usual.


问:
How to mock the npm module that exports the default and the object
I have created a library that exports the default object that includes a few utility functions. Along with default, I have also exported a couple of enums. Here is how my exports look like in the root file of the library

```<code>exports.default = new _oAuth2.default();
var OAUTH_LOG_LEVELS = exports.LOG_LEVELS = {DEBUG: 10, WARN: 20};
var OAUTH_VERSIONS = exports.VERSIONS = {V1: '1.0', v2: '2.0'}
</code>```

In my react app I am importing and using the values this like

```<code>import lib1, {VERSIONS, LOG_LEVELS} from 'mylib';

lib1.init({
  verion: VERSIONS.V1,
})
</code>```

Everything is working fine in the app. Now, I want to add a unit test in the app using Jest, I tried to mock the library. Here is my mock

```<code>jest.mock('myLib', () => ({
  init: jest.fn(),
}));
</code>```

Now, my question is, how to mock the library to include the enums along with defaults? I tried multiple ways but did not succeed. Without that, I cannot use the enums exposed by the library. When I try to use that, the unit test is throwing an error that VERSIONS is not defined.

答:
Use jest.requireActual to get the actual exported values and override just the ones you need to.

```<code>jest.mock('myLib', () => ({
  ...jest.requireActual('myLib'),
  init: jest.fn(),
}));
</code>```

You might need something like ...jest.requireActual('myLib').default instead depending on how you have your exports set up.

Body:
I have created a library that exports the default object that includes a few utility functions. Along with default, I have also exported a couple of enums. Here is how my exports look like in the root file of the library

exports.default = new _oAuth2.default();
var OAUTH_LOG_LEVELS = exports.LOG_LEVELS = {DEBUG: 10, WARN: 20};
var OAUTH_VERSIONS = exports.VERSIONS = {V1: '1.0', v2: '2.0'}

In my react app I am importing and using the values this like

import lib1, {VERSIONS, LOG_LEVELS} from 'mylib';

lib1.init({
  verion: VERSIONS.V1,
})

Everything is working fine in the app. Now, I want to add a unit test in the app using Jest, I tried to mock the library. Here is my mock

jest.mock('myLib', () => ({
  init: jest.fn(),
}));

Now, my question is, how to mock the library to include the enums along with defaults? I tried multiple ways but did not succeed. Without that, I cannot use the enums exposed by the library. When I try to use that, the unit test is throwing an error that VERSIONS is not defined.

Body:
Use jest.requireActual to get the actual exported values and override just the ones you need to.

jest.mock('myLib', () => ({
  ...jest.requireActual('myLib'),
  init: jest.fn(),
}));

You might need something like ...jest.requireActual('myLib').default instead depending on how you have your exports set up.


问:
What is a Covered Index?
I've just heard the term covered index in some database discussion - what does it mean?</p>

答:
Covering index is just an ordinary index. It's called "covering" if it can satisfy query without necessity to analyze data.

example:

```<code>CREATE TABLE MyTable
(
  ID INT IDENTITY PRIMARY KEY,
  Foo INT
)

CREATE NONCLUSTERED INDEX index1 ON MyTable(ID, Foo)

SELECT ID, Foo FROM MyTable -- All requested data are covered by index
</code>```

This is one of the fastest methods to retrieve data from SQL server.

OwnerDisplayName: BelowNinety

Title: What is a Covered Index?

Body:
Covering index is just an ordinary index. It's called "covering" if it can satisfy query without necessity to analyze data.

example:

CREATE TABLE MyTable
(
  ID INT IDENTITY PRIMARY KEY,
  Foo INT
)

CREATE NONCLUSTERED INDEX index1 ON MyTable(ID, Foo)

SELECT ID, Foo FROM MyTable -- All requested data are covered by index

This is one of the fastest methods to retrieve data from SQL server.

OwnerDisplayName: aku


问:
NULL pointer with boost::shared_ptr?
What's the equivalent to the following:

```<code>std::vector<Foo*> vec;
vec.push_back(NULL);
</code>```

when dealing with boost::shared_ptr? Is it the following code?

```<code>std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());
</code>```

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

```<code>boost::shared_ptr<Foo> nullPtr;
</code>```

答:
Well, this is legal:

```<code>shared_ptr<Foo> foo;  /* don't assign */
</code>```

And in this state, it doesn't point to anything.  You can even test this property:

```<code>if (foo) {
    // it points to something
} else {
    // no it doesn't
}
</code>```

So why not do this:

```<code>std::vector < shared_ptr<Foo> > vec;
vec.push_back (shared_ptr<Foo>);   // push an unassigned one
</code>```

OwnerDisplayName: Frank

Title: NULL pointer with boost::shared_ptr?

Body:
What's the equivalent to the following:

std::vector<Foo*> vec;
vec.push_back(NULL);

when dealing with boost::shared_ptr? Is it the following code?

std::vector< boost::shared_ptr<Foo> > vec;
vec.push_back(boost::shared_ptr<Foo>());

Note: I may push back a lot of such objects. Should I declare a global static nullPtr object somewhere? That way only one of them would have to be constructed:

boost::shared_ptr<Foo> nullPtr;

Body:
Well, this is legal:

shared_ptr<Foo> foo;  /* don't assign */

And in this state, it doesn't point to anything.  You can even test this property:

if (foo) {
    // it points to something
} else {
    // no it doesn't
}

So why not do this:

std::vector < shared_ptr<Foo> > vec;
vec.push_back (shared_ptr<Foo>);   // push an unassigned one

OwnerDisplayName: Larry Gritz


问:
Using Android NDK for encryption of data passed from normal android app
Is it possible and worth trying to develop some server application using android NDK which will encrypt data (or just use some built in Linux encryption library) passed to it from normal Java based application?

I tried using Cipher library, but it took almost a minute to encrypt 2MB file with AES. And blowfish is not available in Cipher until Android 2.3(?). And I doubt it will be much faster.

I was using blowfish for encryption on Symbian and it was much faster (under 5-10 seconds) so I think in android it is slower because of using Java virtual machine and I'd like to try native app for it.

Have someone done it before?

EDIT: Encrypting in NDK is so much faster. Do it there. There is a similar question with the same answer for AES: AES decryption on Android too slow to be usable. Will NDK be faster? Other ideas?

答: Of course it is possible to use external library to do crypto. You can use openssl for example https://github.com/guardianproject/openssl-android. The only question is how large will be the impact of JNI layer that exist between Java and C code. If you need to pass lot of date to C and back then benefit from having native library could be negated by JNI layer. It would be much better to move more functionality from Java to C in a way that data that should be encrypted could be processed in C only. For example network stack and encryption could be in C while user interface in Java. This is just proposal you should know better if this is possible or not.</p>


问:
printing the array by method call
```<code>import java.util.Arrays;

public class Q5
{
    public static void main(String[] args){

         double[] v1 = {5, 2, 3};
         double[] v2 = {-1, 2, 0};
         double[]sum = (v1[i] * v2[i]);

             System.out.println(Arrays.toString(sum));

    }

         public static double[] product(double[] v1, double[] v2){

              double[] sum = new double[v1.length];

              for(int i = 0; i < sum.length; i++){
                  sum[i]= v1[i] * v2[i];
              }
              return sum;
        }

}
</code>```

答:
You should use your 'product' method in your 'main'</p>

```<code>    public static void main(String[] args) {
        double[] v1 = {5, 2, 3};
        double[] v2 = {-1, 2, 0};
        double[] sum = product(v1 , v2);

        System.out.println(Arrays.toString(sum));
    }

</code>```

Title: printing the array by method call

Body:
You should use your 'product' method in your 'main'

    public static void main(String[] args) {
        double[] v1 = {5, 2, 3};
        double[] v2 = {-1, 2, 0};
        double[] sum = product(v1 , v2);

        System.out.println(Arrays.toString(sum));
    }


问:
How to download updated sqlite Database from AWS EB? (Django app)
I have deployed my django app on AWS Elastic beanstalk, using the sqlite database.  The site has been running for a while.

Now I have made some changes to the website and want to deploy again, but by keeping the changes the database went through(by form inputs)

But I am not able to find a way to download the updated database or any files. The only version of the app I am able to download is the one I already uploaded when I first deployed.

How can I download the current running app version and deploy with the same database?

答:
you may use scp to connect to remote server and download all your files.

as commented, you should better use dumpdata and then i/o that file (instead of the db or full site).

however, if your remote system python version is not the same as your django site, then the dumpdata may not work (this is my case), so I managed to download the whole site folder back to local and then use dumpdata

aws elastic beanstalk Python app's files in /opt/python/current/app

just use scp -r to download the whole site to local.


问:
Find and replace text in files with xonsh
How would one replace text in all files within a given directory (recursively) while in the xonsh shell?

For example, how would I rewrite the below bash command:

```<code>find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +
</code>```

答:
I might try this:</p>

```<code>for fpath in pg`*baz*`:
    if not fpath.is_file():
        continue
    fpath.write_text(fpath.read_text().replace('foo', 'bar'))
</code>```

Body:
How would one replace text in all files within a given directory (recursively) while in the xonsh shell?

For example, how would I rewrite the below bash command:

find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +

Body:
I might try this:

for fpath in pg`*baz*`:
    if not fpath.is_file():
        continue
    fpath.write_text(fpath.read_text().replace('foo', 'bar'))


问:
django elasticbeanstalk deployment issue with YML config
For testing purpose I am trying to upload a django project
in AWS elastic beanstalk. But environment create command eb create my-env gives me this error :

```<code>ERROR: InvalidParameterValueError - The configuration file .ebextensions/django.config in application version app-8036-200522_133554 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token
found character         '\t' that cannot start any token
 in "<reader>", line 2, column 1:
        aws:elasticbeanstalk:container: ...
    ^
, JSON exception: Invalid JSON: Unexpected character (o) at position 0.. Update the configuration file.
</code>```

Here is my folder structure.

```<code>.
├── db.sqlite3
├── .ebextensions
│   └── django.config
├── .elasticbeanstalk
│   └── config.yml
├── .gitignore
├── manage.py
├── requirements.txt
├── static
└── TaxKH_API
    ├── asgi.py
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py
</code>```

and here is my .ebextensions/django.config
I have validated the YML using online tool. There is no problem regarding
YML formatting and validation.

```<code>option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: TaxAPI/wsgi.py

</code>```

Here is a screenshot of that I am not using any type of tab in my file
screenshot

答:
You have to do the below steps:

Remove any tabs in django.config and use spaces only (2 spaces for indentation)

You have to add and commit your changes to your local repo before running eb command like eb create or eb deploy to reflect the changes. eb CLI reads only the files from your repo.

Body:
For testing purpose I am trying to upload a django project
in AWS elastic beanstalk. But environment create command eb create my-env gives me this error :

ERROR: InvalidParameterValueError - The configuration file .ebextensions/django.config in application version app-8036-200522_133554 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token
found character         '\t' that cannot start any token
 in "<reader>", line 2, column 1:
        aws:elasticbeanstalk:container: ...
    ^
, JSON exception: Invalid JSON: Unexpected character (o) at position 0.. Update the configuration file.

Here is my folder structure.

.
├── db.sqlite3
├── .ebextensions
│   └── django.config
├── .elasticbeanstalk
│   └── config.yml
├── .gitignore
├── manage.py
├── requirements.txt
├── static
└── TaxKH_API
    ├── asgi.py
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

and here is my .ebextensions/django.config
I have validated the YML using online tool. There is no problem regarding
YML formatting and validation.

option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: TaxAPI/wsgi.py

Here is a screenshot of that I am not using any type of tab in my file
screenshot


问:
Allowing overflow:visible only for input or select fields
I'm having this issue with a Lightning Web Component in Salesforce, but I think the root of it is universal.

I have a container div which houses row divs showing select/combobox fields, which I need to have hang over the top/bottom of the container when selected. I can get this by setting overflow:visible on the container.

I can add more rows and the container expands normally:

But what I want to do is add y-axis scroll bars when the container reaches a max-height. By definition, overflow:visible doesn't add scroll bars and the contents flow out the bottom of the container

Any ideas would be appreciated.

答:
You will need to set two overflows.
 overflow:visible only on the select boxes. For the container you can use auto or scroll depending on the code that for some reason you did not add.</p>


问:
Understanding python nested iteration inside a list comprehension
I am having a hard time interpreting nested iteration inside a list comprehension. Below code

```<code>movie = []
genre = []
for movie_ids in ratings["movie_id"].values:
  movie.append(movie_ids)
  genre.append([x for movie_id in movie_ids for x in genres_dict[movie_id]])
</code>```

If I print genre[0] suppose I see a result [a,b,c]

My understanding from this and many others on the internet was that I can replace the line

```<code>genre.append([x for movie_id in movie_ids for x in genres_dict[movie_id]])
</code>```

With

```<code>for movie_id in movie_ids:
    if movie_id in genres_dict:
      genre.append(genres_dict[movie_id])
</code>```

But that gives a different result when I print genre[0]

What am I missing?

Please suggest

答:
With the list comprehension, you are also iterating over the contents of genres_dict[movie_id]. This code would not quite translate into the for loop you provided, but instead into

for movie_id in movie_ids:
    for x in genres_dict[movie_id]
        genre.append(x)
```

<p>I have omitted the <code>if</code> statement because, although it is not a bad idea to test whether the key exists, the nested iteration does not perform this test either. Nested iteration essentially performs the for loops you provide, nested, from the left to the right, and then appends the result of the expression.</p>

<p>Furthermore, appending the result of a list comprehension does not add every element of the list comprehension individually, but instead the entire list as one element. So the code actually performs</p>

<pre class="lang-py prettyprint-override"><code>list_out = []
for movie_id in movie_ids:
    for x in genres_dict[movie_id]
        list_out.append(x)
genre.append(list_out)
</code>```

If you want to add all of the elements of the list comprehension, you should instead use list.extend, which takes an iterable as an argument and adds every element to the list. In your original code this would be
genre.extend([x for movie_id in movie_ids for x in genres_dict[movie_id]]).

Body:
I am having a hard time interpreting nested iteration inside a list comprehension. Below code

movie = []
genre = []
for movie_ids in ratings["movie_id"].values:
  movie.append(movie_ids)
  genre.append([x for movie_id in movie_ids for x in genres_dict[movie_id]])

If I print genre[0] suppose I see a result [a,b,c]

My understanding from this and many others on the internet was that I can replace the line

genre.append([x for movie_id in movie_ids for x in genres_dict[movie_id]])

With

for movie_id in movie_ids:
    if movie_id in genres_dict:
      genre.append(genres_dict[movie_id])

But that gives a different result when I print genre[0]

What am I missing?

Please suggest

Body:
With the list comprehension, you are also iterating over the contents of genres_dict[movie_id]. This code would not quite translate into the for loop you provided, but instead into

for movie_id in movie_ids:
    for x in genres_dict[movie_id]
        genre.append(x)

I have omitted the if statement because, although it is not a bad idea to test whether the key exists, the nested iteration does not perform this test either. Nested iteration essentially performs the for loops you provide, nested, from the left to the right, and then appends the result of the expression.

Furthermore, appending the result of a list comprehension does not add every element of the list comprehension individually, but instead the entire list as one element. So the code actually performs

list_out = []
for movie_id in movie_ids:
    for x in genres_dict[movie_id]
        list_out.append(x)
genre.append(list_out)

If you want to add all of the elements of the list comprehension, you should instead use list.extend, which takes an iterable as an argument and adds every element to the list. In your original code this would be
genre.extend([x for movie_id in movie_ids for x in genres_dict[movie_id]]).