问:
Get bounding box of individual countries from topojson
I want to get bounding boxes for each country from a topojson, but when I add them as svg rectangles they are bundled together towards 0,0.

Ive re-read the API and played around with the order of the bound coordinates, but that didn't change anything! Also, I tried to use the SVG method getBBox() on the country paths but that produced the same result.

Any ideas?

```<code>var width = 700,
  height = 400,
  bboxes = [];

d3.queue()
  .defer(d3.json, "data/world.topojson")
  .await(ready);

//Map projection
var proj = d3.geoMercator()
  .scale(100)
  .center([-0.0018057527730242487, 11.258678472759552]) //projection center
  .translate([width / 2, height / 2]) //translate to center the map in view

//Generate paths based on projection
var myPath = d3.geoPath().projection(proj);

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

//Group for the map features
var map = svg.append("g")
  .attr("class", "map");

function ready(error, geodata) {
  if (error) return console.log(error); //unknown error, check the console

  //Create a path for each map feature in the data
  map.selectAll("path")
    .data(topojson.feature(geodata, geodata.objects.subunits).features) //generate features from TopoJSON
    .enter()
    .append("path")
    .attr("class", "country")
    .attr("id", function(d) {
      return d.id;
    })
    .attr("d", myPath);

    bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.subunits).features);

    svg.selectAll("rect")
    .data(bboxes)
    .enter()
    .append("rect")
    .attr("id", function(d){
      return d.id;
    })
    .attr("class", "bb")
    .attr("x1", function(d) {
      return d.x;
    })
    .attr("y1", function(d) {
      return d.y;
    })
    .attr("width", function(d) {
      return d.width;
    })
    .attr("height", function(d) {
      return d.height;
    })
}

function boundingExtent(features) {
var bounds= [];
  for (var x in features) {
    var boundObj = {};
    thisBounds = myPath.bounds(features[x]);
    boundObj.id = features[x].id;
    boundObj.x = thisBounds[0][0];
    boundObj.y = thisBounds[0][1];
    boundObj.width = thisBounds[1][0] - thisBounds[0][0];
    boundObj.height = thisBounds[1][1] - thisBounds[0][1];
    boundObj.path = thisBounds;
    bounds.push(boundObj)
  }
  return bounds;
}

function boundExtentBySvg(){
  var countries = svg.selectAll(".country")
  countries.each(function(d){
      var box = d3.select(this).node().getBBox();
      bboxes.push({id: d.id, x: box.x, y : box.y, width: box.width, height : box.height})
  })
}
</code>```

答:
In these lines:

```<code>.attr("x1", function(d) {
  return d.x;
})
.attr("y1", function(d) {
  return d.y;
})
</code>```

rect does not have an attribute of x1 or y1, I think you meant just x and y.

Here's your code running (note, I switched out the topojson file which caused slight code changes):

<!DOCTYPE html>

    <svg width="700" height="400"></svg>

```

Body:
I want to get bounding boxes for each country from a topojson, but when I add them as svg rectangles they are bundled together towards 0,0.

Ive re-read the API and played around with the order of the bound coordinates, but that didn't change anything! Also, I tried to use the SVG method getBBox() on the country paths but that produced the same result.

Any ideas?

var width = 700,
  height = 400,
  bboxes = [];

d3.queue()
  .defer(d3.json, "data/world.topojson")
  .await(ready);

//Map projection
var proj = d3.geoMercator()
  .scale(100)
  .center([-0.0018057527730242487, 11.258678472759552]) //projection center
  .translate([width / 2, height / 2]) //translate to center the map in view

//Generate paths based on projection
var myPath = d3.geoPath().projection(proj);

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

//Group for the map features
var map = svg.append("g")
  .attr("class", "map");

function ready(error, geodata) {
  if (error) return console.log(error); //unknown error, check the console

  //Create a path for each map feature in the data
  map.selectAll("path")
    .data(topojson.feature(geodata, geodata.objects.subunits).features) //generate features from TopoJSON
    .enter()
    .append("path")
    .attr("class", "country")
    .attr("id", function(d) {
      return d.id;
    })
    .attr("d", myPath);

    bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.subunits).features);

    svg.selectAll("rect")
    .data(bboxes)
    .enter()
    .append("rect")
    .attr("id", function(d){
      return d.id;
    })
    .attr("class", "bb")
    .attr("x1", function(d) {
      return d.x;
    })
    .attr("y1", function(d) {
      return d.y;
    })
    .attr("width", function(d) {
      return d.width;
    })
    .attr("height", function(d) {
      return d.height;
    })
}

function boundingExtent(features) {
var bounds= [];
  for (var x in features) {
    var boundObj = {};
    thisBounds = myPath.bounds(features[x]);
    boundObj.id = features[x].id;
    boundObj.x = thisBounds[0][0];
    boundObj.y = thisBounds[0][1];
    boundObj.width = thisBounds[1][0] - thisBounds[0][0];
    boundObj.height = thisBounds[1][1] - thisBounds[0][1];
    boundObj.path = thisBounds;
    bounds.push(boundObj)
  }
  return bounds;
}

function boundExtentBySvg(){
  var countries = svg.selectAll(".country")
  countries.each(function(d){
      var box = d3.select(this).node().getBBox();
      bboxes.push({id: d.id, x: box.x, y : box.y, width: box.width, height : box.height})
  })
}

Body:
In these lines:

.attr("x1", function(d) {
  return d.x;
})
.attr("y1", function(d) {
  return d.y;
})

rect does not have an attribute of x1 or y1, I think you meant just x and y.

Here's your code running (note, I switched out the topojson file which caused slight code changes):

<!DOCTYPE html>
<html>

  <head>
    <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
    <script data-require="topojson.min.js@3.0.0" data-semver="3.0.0" src="https://unpkg.com/topojson@3.0.0"></script>
  </head>

  <body>
    <svg width="700" height="400"></svg>
    <script>
    var width = 700,
      height = 400,
      bboxes = [];

    d3.queue()
      .defer(d3.json, "https://unpkg.com/world-atlas@1/world/110m.json")
      .await(ready);

    //Map projection
    var proj = d3.geoMercator()
      .scale(100)
      .center([-0.0018057527730242487, 11.258678472759552]) //projection center
      .translate([width / 2, height / 2]) //translate to center the map in view

    //Generate paths based on projection
    var myPath = d3.geoPath().projection(proj);

    var svg = d3.select("svg"),
      width = +svg.attr("width"),
      height = +svg.attr("height");

    //Group for the map features
    var map = svg.append("g")
      .attr("class", "map");

    function ready(error, geodata) {

      if (error) return console.log(error); //unknown error, check the console

      //Create a path for each map feature in the data
      map.selectAll("path")
        .data(topojson.feature(geodata, geodata.objects.countries).features) //generate features from TopoJSON
        .enter()
        .append("path")
        .attr("class", "country")
        .attr("id", function(d) {
          return d.id;
        })
        .attr("d", myPath);

      bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.countries).features);

      svg.selectAll("rect")
        .data(bboxes)
        .enter()
        .append("rect")
        .attr("id", function(d) {
          return d.id;
        })
        .attr("class", "bb")
        .attr("x", function(d) {
          return d.x;
        })
        .attr("y", function(d) {
          return d.y;
        })
        .attr("width", function(d) {
          return d.width;
        })
        .attr("height", function(d) {
          return d.height;
        })
        .style("fill", "none")
        .style("stroke", "steelblue");
    }

    function boundingExtent(features) {
      var bounds = [];
      for (var x in features) {
        var boundObj = {};
        thisBounds = myPath.bounds(features[x]);
        boundObj.id = features[x].id;
        boundObj.x = thisBounds[0][0];
        boundObj.y = thisBounds[0][1];
        boundObj.width = thisBounds[1][0] - thisBounds[0][0];
        boundObj.height = thisBounds[1][1] - thisBounds[0][1];
        boundObj.path = thisBounds;
        bounds.push(boundObj)
      }
      console.log(bounds)

      return bounds;
    }

    function boundExtentBySvg() {
      var countries = svg.selectAll(".country")
      countries.each(function(d) {
        var box = d3.select(this).node().getBBox();
        bboxes.push({
          id: d.id,
          x: box.x,
          y: box.y,
          width: box.width,
          height: box.height
        })
      })
    }
  </script>
  </body>

</html>


来源: stackexchange

问:
Linking to local video file for video background HTML/CSS
I've been stuck trying to make a video on my computer be the video in the background. My video is titled "runbg.avi" and it is in the same folder as my HTML and CSS files.

These are a couple of many websites that I visited to search for an answer.

Using file:// instead of http:// when trying to get video from my computer rather than the web.

I can point to video on the web but not locally.

My program so far.

/* BACKGROUND */
video#vid {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
background-size: cover;
margin: 0 auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
<title>Seb's Fitness</title>

<link rel = "stylesheet"
      type = "text/css"
      href = "css.css" />

      <video autoplay loop poster="" id="vid">
    <source src="file://runbg.avi" type="video/avi">
    </video></code>```

答:
```<code><video autoplay loop poster="" id="vid">
    <source src="/runbg.avi" type="video/avi">
 </video>
</code>```

/runbg.avi means start in the root folder (/) and then search runbh.avi file.

learn more relative and absolute paths

ContentLicense: CC BY-SA 3.0

Body:
I've been stuck trying to make a video on my computer be the video in the background. My video is titled "runbg.avi" and it is in the same folder as my HTML and CSS files.

These are a couple of many websites that I visited to search for an answer.

Using file:// instead of http:// when trying to get video from my computer rather than the web.

I can point to video on the web but not locally.

My program so far.

/* BACKGROUND */
video#vid {
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
width: auto;
height: auto;
z-index: -100;
background-size: cover;
margin: 0 auto;
}

<!DOCTYPE html>

<title>Seb's Fitness</title>

<link rel = "stylesheet"
      type = "text/css"
      href = "css.css" />

      <video autoplay loop poster="" id="vid">
    <source src="file://runbg.avi" type="video/avi">
    </video>

Body:
<video autoplay loop poster="" id="vid">
    <source src="/runbg.avi" type="video/avi">
 </video>

/runbg.avi means start in the root folder (/) and then search runbh.avi file.

learn more relative and absolute paths


问:
Sort listview with array adapter
I have a listview connected to a custom array adapter. This list shows information received by a TCP connection which changes the dataSet...

I am able to sort the listview with sort (Comparator<? super T> comparator), but when the dataSet is changed, the listview is no more sorted...

I can use sort () every time the dataSet is changed, but I think this is not the best option...

How can I do that? Any suggestions?

EDIT

I am having problems in implementing the solutions presented...

MyComparatorB.java

```<code>public class MyComparatorB implements Comparator<DeviceB> {

private byte orderType;

public MyComparatorB(byte type) {

    this.orderType = type;

}

public int compare(DeviceB lhs, DeviceB rhs) {

    int res = 0;
    if (orderType == SortType.ALPHA) {
            res = (lhs.getName()).compareTo(rhs.getName());
        }
        else if (orderType == SortType.LAST_ACT) {
            res = (rhs.getTime().getTime()).compareTo(lhs.getTime().getTime());
        }
        return res;
    }

}
</code>```

Snippet of my customArrayAdapter.java

```<code>    @Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
}

//-----------Order the content of the arrayAdapter------------//
public void sort(byte sortType) {

    super.sort(new MyComparatorB(sortType));
    notifyDataSetChanged();
}
</code>```

In my MyActivity.java

```<code>myDevAdapter.sort(SortType.ALPHA);
</code>```

When I am debugging, the method super.sort(new MyComparatorB(sortType)); is called and the constructor of MyComparatorB is called too. But the method compare(DeviceB lhs, DeviceB rhs) is never called and my arrayList is not sorted...
What I am doing wrong?

答:
Based on waqaslam and KristianR's answer :

```<code>@Override
public void notifyDataSetChanged() {
    this.setNotifyOnChange(false);

    this.sort(new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            return s1.compareTo(s2);
        }
    });

    super.notifyDataSetChanged();
    this.setNotifyOnChange(true);
}
</code>```

Hope it helps.

Title: Sort listview with array adapter

Body:
I have a listview connected to a custom array adapter. This list shows information received by a TCP connection which changes the dataSet...

I am able to sort the listview with sort (Comparator<? super T> comparator), but when the dataSet is changed, the listview is no more sorted...

I can use sort () every time the dataSet is changed, but I think this is not the best option...

How can I do that? Any suggestions?

EDIT

I am having problems in implementing the solutions presented...

MyComparatorB.java

public class MyComparatorB implements Comparator<DeviceB> {

private byte orderType;

public MyComparatorB(byte type) {

    this.orderType = type;

}

public int compare(DeviceB lhs, DeviceB rhs) {

    int res = 0;
    if (orderType == SortType.ALPHA) {
            res = (lhs.getName()).compareTo(rhs.getName());
        }
        else if (orderType == SortType.LAST_ACT) {
            res = (rhs.getTime().getTime()).compareTo(lhs.getTime().getTime());
        }
        return res;
    }

}

Snippet of my customArrayAdapter.java

    @Override
public void notifyDataSetChanged() {
    super.notifyDataSetChanged();
}

//-----------Order the content of the arrayAdapter------------//
public void sort(byte sortType) {

    super.sort(new MyComparatorB(sortType));
    notifyDataSetChanged();
}

In my MyActivity.java

myDevAdapter.sort(SortType.ALPHA);

When I am debugging, the method super.sort(new MyComparatorB(sortType)); is called and the constructor of MyComparatorB is called too. But the method compare(DeviceB lhs, DeviceB rhs) is never called and my arrayList is not sorted...
What I am doing wrong?

Body:
Based on waqaslam and KristianR's answer :

@Override
public void notifyDataSetChanged() {
    this.setNotifyOnChange(false);

    this.sort(new Comparator<String>() {

        @Override
        public int compare(String s1, String s2) {
            return s1.compareTo(s2);
        }
    });

    super.notifyDataSetChanged();
    this.setNotifyOnChange(true);
}

Hope it helps.


问:
How do you set the proxy IP with Phproxy?
I just downloaded PhProxy from here. When I went to some IP locator site my IP was a Dallas/Texas IP. Is there any way to change the IP PhProxy uses? I couldn't find a way to do it.</p>

答:
PHProxy - like all proxies - accepts requests from any of a number of IPs and acts on their behalf to fulfill that request. The IP you're seeing is almost certainly the IP address of your webserver, and no you can't edit some setting to change it. Your server makes a request to some address and includes its own address - this is how the remote end knows how to answer back. You couldn't change this with a PHProxy setting even if you wanted to - if you could, your packets wouldn't get back to you.

You could get a different webhost, if a Dallas-located IP is a real problem, but it would be locked to the new webhost just the same. Webservers can't exactly IP-hop...

ContentLicense: CC BY-SA 2.5


问:
How to easily install and uninstall docker on MacOs
My question is

How to easily install docker to have it available in terminal and how to uninstall docker on osx?

答:
By command line

INSTALL

Install with

brew install --cask docker

And run docker by

open /Applications/Docker.app

(or by macOs bottom menu> launchpad > docker - on first run docker will ask you about password)

Thats all :)

UNINSTALL

Type brew uninstall --cask docker

thats all :)

To clean everything (including images/containers) execute below commands:

```<code>sudo rm -Rf /Applications/Docker
sudo rm -f /usr/local/bin/docker
sudo rm -f /usr/local/bin/docker-machine
sudo rm -f /usr/local/bin/docker-compose
sudo rm -f /usr/local/bin/docker-credential-osxkeychain
sudo rm -Rf ~/.docker
sudo rm -Rf $HOME/Library/Containers/com.docker.docker  # here we delete stored images
</code>```

Body:
By command line

INSTALL

Install with

brew install --cask docker

And run docker by

open /Applications/Docker.app

(or by macOs bottom menu> launchpad > docker - on first run docker will ask you about password)

Thats all :)

UNINSTALL

Type brew uninstall --cask docker

thats all :)

To clean everything (including images/containers) execute below commands:

sudo rm -Rf /Applications/Docker
sudo rm -f /usr/local/bin/docker
sudo rm -f /usr/local/bin/docker-machine
sudo rm -f /usr/local/bin/docker-compose
sudo rm -f /usr/local/bin/docker-credential-osxkeychain
sudo rm -Rf ~/.docker
sudo rm -Rf $HOME/Library/Containers/com.docker.docker  # here we delete stored images

ContentLicense: CC BY-SA 4.0


问:
Javascript foreach loop on list items
I have a basic HTML list like below...

```<code><ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>
</code>```

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string.  I have this so far..

```<code>var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}
</code>```

This isn't working for me, is it because it is not really an array?

答:
My understanding is, you want to loop through this list of items and find a match of the item based on a specified string.

What you've done so far with the classes is good. This will allow you to reference all the list items, but there isn't really a need for the IDs based on what I think it is that you're trying to do.

If I were you, I would utilize a querySelectorAll, which returns an iterable array of HTML nodes that we can do whatever we want with.

Here's my code.

let listItemArray = document.querySelectorAll('.item');
console.log(listItemArray);
const SEARCH_STRING = 'Item 1'

for(let i=0; i<listItemArray.length; i++) {
  if(listItemArray[i].innerText === SEARCH_STRING) {
    console.log(`The item was found! ${listItemArray[i]}`); // This syntax is called a query string. Powerful stuff. Look them up.
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul></code>```

Title: Javascript foreach loop on list items

Body:
I have a basic HTML list like below...

        Item 1

        Item 2

        Item 3

        Item 4

I am using javascript to try and grab the id of each list item and then use a loop to check each one against a string.  I have this so far..

var myvariable
myvariable = "item2"
items = document.getElementsByClassName("item");
for (i = 0; i < items.length; i++) {
    console.log(i);
    console.log(item[i]);
}

This isn't working for me, is it because it is not really an array?

Body:
My understanding is, you want to loop through this list of items and find a match of the item based on a specified string.

What you've done so far with the classes is good. This will allow you to reference all the list items, but there isn't really a need for the IDs based on what I think it is that you're trying to do.

If I were you, I would utilize a querySelectorAll, which returns an iterable array of HTML nodes that we can do whatever we want with.

Here's my code.

let listItemArray = document.querySelectorAll('.item');
console.log(listItemArray);
const SEARCH_STRING = 'Item 1'

for(let i=0; i<listItemArray.length; i++) {
  if(listItemArray[i].innerText === SEARCH_STRING) {
    console.log(`The item was found! ${listItemArray[i]}`); // This syntax is called a query string. Powerful stuff. Look them up.
  }
}

<ul class="test_ul">
    <li class="item" id="item1">
        Item 1
    </li>
    <li class="item" id="item2">
        Item 2
    </li>
    <li class="item" id="item3">
        Item 3
    </li>
    <li class="item" id="item4">
        Item 4
    </li>
</ul>


问:
navbar-right does not work
Self-explanatory. Why does navbar-right not close out the two nav bar elements to the right? I have added the proper code so I am confused as to why it does not work.

```<code><nav class="navbar fixed-top navbar-toggleable-md navbar-inverse navbar-expanded" id="mainNav">
  <div class="container">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-="data-" toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="nav navbar-nav navbar-left">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#about">About</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#services">Products</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#pricing">Pricing</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#contact">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-up" style="background-color:blue; border-radius:5px">Sign Up</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-in" style="background-color:blue; border-radius:5px">Log In</a></li>
      </ul>
    </div>
  </div>
</nav>
</code>```

答:
You need to close your collapse button and you have a bunch of errors in the attributes of that tag.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    <button class="navbar-toggle navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">menu</button>

          About

          Products

          Pricing

          Contact

          Sign Up

          Log In

```

Title: navbar-right does not work

Body:
Self-explanatory. Why does navbar-right not close out the two nav bar elements to the right? I have added the proper code so I am confused as to why it does not work.

    <button class="navbar-toggler navbar-toggler-right" type="button" data-="data-" toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

          About

          Products

          Pricing

          Contact

          Sign Up

          Log In

Body:
You need to close your collapse button and you have a bunch of errors in the attributes of that tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<nav class="navbar fixed-top navbar-toggleable-md navbar-inverse navbar-expanded" id="mainNav">
  <div class="container">
    <button class="navbar-toggle navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">menu</button>
    <div class="collapse navbar-collapse" id="navbarResponsive">
      <ul class="nav navbar-nav navbar-left">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#about">About</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#services">Products</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#pricing">Pricing</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="#contact">Contact</a></li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-up" style="background-color:blue; border-radius:5px">Sign Up</a></li>
        <li class="nav-item">
          <a class="nav-link page-scroll" href="sign-in" style="background-color:blue; border-radius:5px">Log In</a></li>
      </ul>
    </div>
  </div>
</nav>


问:
'Beautiful arrays' CodeChef, how to input data
Here's the problem statement:

An array a is called beautiful if for every pair of numbers ai, aj, (i
≠ j), there exists an ak such that ak = ai * aj. Note that k can be
equal to i or j too.

Find out whether the given array a is beautiful or not!

Input

First line of the input contains an integer T denoting the number of
test cases. T test cases follow.

First line of each test case contains an integer n denoting number of
elements in a.

Next line contains n space separated integers denoting the array a.
Output

For each test case, output a single line containing "yes" or "no"
(without quotes) corresponding to the answer of the problem.
Constraints

```<code>1 ≤ T ≤ 106
1 ≤ n ≤ 105
Sum of n over all the test cases ≤ 106
-109 ≤ ai ≤ 109
</code>```

Example

Input

3

2

0 1

2

1 2

2

5 6

Output:

yes

yes

no

I am new to CodeChef and can't work out how to correctly take in an input, I have some code that I am trying to use to solve the beautiful arrays problem but when I run it I get a NZEC.

```<code>from collections import Counter
numCase = int(input())
for i in range(numCase):
    length = input()
    array = Counter(input().split(''))
    answer = "no"
    for i in range(length - 1):
        if array[i] == 0 or array[i] == 1:
            answer = "yes"

    print(answer)
</code>```

When I change the inputs and manually input some data the code works for me, can anybody tell me why this code doesn't work? Thanks

答:
First, your code as-is crashes when you run it by hand. Minimally you need to change length = input() to length = int(input()). The NZEC is a runtime error, which is CodeChef telling you that your code is crashing.

Second, it's best not to reference external sites. Give your potential answerers a fighting chance and give us the problem. It's not convenient to look up CodeChef, what it is, and where I can find the problem statement. Additionally, CodeChef might go away, or might be down, and then you obviously can't get an answer. That being said, I've put the problem statement in your question.

Lastly, your solution is fundamentally flawed in terms of logic (not just crashing). It does not suffice to check whether the first two items in the array are 0 and 1 respectively. You are sort of close to having an efficient solution, though. Observe the following input/output:

```<code>1

3

1 -4 -1

# Output should be "no", since -4 * -1 == 4, and 4 is not in the list.
</code>```

Also, consider

```<code>1

5

0 1 2 3 4 5

# Output should be "no" since 2 * 3 == 6, but 6 is not in the list
</code>```

The base case (if the array len == 1) is a "yes" output. This is not correct in my opinion (i cannot equal j, pairs are not well defined for input of length one, I could go on...). So I'm willing to give you that part of the solution since it fooled me too and it's not particularly clear.

As a side note, it seems that I've seen some misinterpretations of the problem on this thread, so I'll try to add some clarification.

An array a is called beautiful if for every pair of numbers ai, aj, (i
  ≠ j), there exists an ak such that ak = ai * aj. Note that k can be
  equal to i or j too.

The important words here are "for every pair of numbers ai, aj there exists ak", not just some pair. This means that if we have input array [2, 3, 6], the answer is "no", because 3 * 6 == 18, but 18 is not in the array. It's tempting to think that the answer should be "yes" because 2 * 3 == 6, but that's just some pair that satisfies the relation. The question makes it clear that every pair must satisfy the relation.

Here's my solution. I was tempted not to post it, but if you really get stuck, this can be your reference. I strongly suggest you do not look at the solution right away, give yourself at least a full day to solve it, and be sure to sleep on it. You won't learn anything by copy/pasting my solution into CodeChef. Hover over the section below to see my solution.

```
numCase = int(input())
for i in range(numCase):
    length = int(input())
    array = [int(x) for x in input().split(' ')]
    num_neg_ones = len([x for x in array if x == -1])
    num_ones = len([x for x in array if x == 1])
    num_other = len([x for x in array if x not in [0, -1, 1]])

    answer = "yes"
    if num_other > 1:
        answer = "no"
    if num_other == 1 and num_neg_ones > 0:
        answer = "no"
    if num_neg_ones > 1 and num_ones == 0:
        answer = "no"
    print(answer)
```

Body:
Here's the problem statement:

An array a is called beautiful if for every pair of numbers ai, aj, (i
≠ j), there exists an ak such that ak = ai * aj. Note that k can be
equal to i or j too.

Find out whether the given array a is beautiful or not!

Input

First line of the input contains an integer T denoting the number of
test cases. T test cases follow.

First line of each test case contains an integer n denoting number of
elements in a.

Next line contains n space separated integers denoting the array a.
Output

For each test case, output a single line containing "yes" or "no"
(without quotes) corresponding to the answer of the problem.
Constraints

1 ≤ T ≤ 106
1 ≤ n ≤ 105
Sum of n over all the test cases ≤ 106
-109 ≤ ai ≤ 109

Example

Input

3

2

0 1

2

1 2

2

5 6

Output:

yes

yes

no

I am new to CodeChef and can't work out how to correctly take in an input, I have some code that I am trying to use to solve the beautiful arrays problem but when I run it I get a NZEC.

from collections import Counter
numCase = int(input())
for i in range(numCase):
    length = input()
    array = Counter(input().split(''))
    answer = "no"
    for i in range(length - 1):
        if array[i] == 0 or array[i] == 1:
            answer = "yes"

    print(answer)

When I change the inputs and manually input some data the code works for me, can anybody tell me why this code doesn't work? Thanks

Body:
First, your code as-is crashes when you run it by hand. Minimally you need to change length = input() to length = int(input()). The NZEC is a runtime error, which is CodeChef telling you that your code is crashing.

Second, it's best not to reference external sites. Give your potential answerers a fighting chance and give us the problem. It's not convenient to look up CodeChef, what it is, and where I can find the problem statement. Additionally, CodeChef might go away, or might be down, and then you obviously can't get an answer. That being said, I've put the problem statement in your question.

Lastly, your solution is fundamentally flawed in terms of logic (not just crashing). It does not suffice to check whether the first two items in the array are 0 and 1 respectively. You are sort of close to having an efficient solution, though. Observe the following input/output:

1

3

1 -4 -1

# Output should be "no", since -4 * -1 == 4, and 4 is not in the list.

Also, consider

1

5

0 1 2 3 4 5

# Output should be "no" since 2 * 3 == 6, but 6 is not in the list

The base case (if the array len == 1) is a "yes" output. This is not correct in my opinion (i cannot equal j, pairs are not well defined for input of length one, I could go on...). So I'm willing to give you that part of the solution since it fooled me too and it's not particularly clear.

As a side note, it seems that I've seen some misinterpretations of the problem on this thread, so I'll try to add some clarification.

An array a is called beautiful if for every pair of numbers ai, aj, (i
  ≠ j), there exists an ak such that ak = ai * aj. Note that k can be
  equal to i or j too.

The important words here are "for every pair of numbers ai, aj there exists ak", not just some pair. This means that if we have input array [2, 3, 6], the answer is "no", because 3 * 6 == 18, but 18 is not in the array. It's tempting to think that the answer should be "yes" because 2 * 3 == 6, but that's just some pair that satisfies the relation. The question makes it clear that every pair must satisfy the relation.

Here's my solution. I was tempted not to post it, but if you really get stuck, this can be your reference. I strongly suggest you do not look at the solution right away, give yourself at least a full day to solve it, and be sure to sleep on it. You won't learn anything by copy/pasting my solution into CodeChef. Hover over the section below to see my solution.

numCase = int(input())
for i in range(numCase):
    length = int(input())
    array = [int(x) for x in input().split(' ')]
    num_neg_ones = len([x for x in array if x == -1])
    num_ones = len([x for x in array if x == 1])
    num_other = len([x for x in array if x not in [0, -1, 1]])

    answer = "yes"
    if num_other > 1:
        answer = "no"
    if num_other == 1 and num_neg_ones > 0:
        answer = "no"
    if num_neg_ones > 1 and num_ones == 0:
        answer = "no"
    print(answer)


问:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?
I have a string like:

```<code> SomeCamel WasEnteringText
</code>```

I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.

Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.

I tried:

```<code>    my $camel = "SomeCamel WasEnteringText";
    #or
    my $camel = " SomeCamel WasEntering Text";
    $camel =~ s/^[A-Z]/\s[A-Z]/g;
    #and
    $camel =~ s/([\w']+)/\u$1/g;
</code>```

and many more combinations of =~s//g; after much reading.

I need a guru to direct this camel towards an oasis of answers.

OK, based on the input below I now have:

```<code>$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Which gets it done but seems excessive. Works though.

答:
Try :
    s/(?<=[a-z])(?=[A-Z])/ /g

This inserts as space after a lower case character (ie not a space or start of string) and before and upper case character.

Body:
I have a string like:

 SomeCamel WasEnteringText

I have found various means of splitting up the string and inserting spaces with php str_replace but, i need it in perl.

Sometimes there may be a space before the string, sometimes not. Sometimes there will be a space in the string but, sometimes not.

I tried:

    my $camel = "SomeCamel WasEnteringText";
    #or
    my $camel = " SomeCamel WasEntering Text";
    $camel =~ s/^[A-Z]/\s[A-Z]/g;
    #and
    $camel =~ s/([\w']+)/\u$1/g;

and many more combinations of =~s//g; after much reading.

I need a guru to direct this camel towards an oasis of answers.

OK, based on the input below I now have:

$camel =~ s/([A-Z])/ $1/g;
$camel =~ s/^ //; # Strip out starting whitespace
$camel =~ s/([^[:space:]]+)/\u$1/g;

Which gets it done but seems excessive. Works though.


问:
Where to find google-api-services-youtube jar file
I am at my wit's end and this should not be so difficult. Youtube v2 APIs are deprecated rendering my application useless. So, based on this website (https://developers.google.com/youtube/v3/code_samples/java#search_by_keyword), I am trying to run the sample. I downloaded google v3 client libraries from this location (https://code.google.com/p/google-api-java-client/). Now in the code sample there are multiple imports for com.google.api.services.*. But this jar is not included in the client libraries and I have spent more than 2 hours to figure out where to get this jar. I am going around circular references not finding anything. Is there some obvious stuff that I am missing. I am not familiar with maven, so if it is straightforward maven stuff, please just point me to the google site where I can download latest jar.

Thanks in advance.

答:
Go to this maven central repository link.

You can either download the jar directly or get maven/gradle dependency.

You can get all the google libraries in the maven central repository's google group

Note:  Always use a build system, it will make your job easy. You don't need to manually download the file, extract to the right folder blah,blah,blah... Just include the dependency in the maven/gradle file and it will take care of the rest


问:
Sequelize how to join 2 tables 1:N
I have 2 models: User and Foto

Each User has a lot of fotos, and each foto can have just 1 user related.

To do that i use include, the problem is, i can use the include just when i am querying the user and not when i query the foto.

I get there is no relationshop between User and foto problem.

So at the moment i have this:

Model User:

```<code>"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var Foto = require('./Foto');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { username: value } })
            .then(function (user) {
              // reject if a different user wants to use the same username
              if (user && self.id !== user.id) {
                return next('username already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { email: value } })
            .then(function (user) {
              // reject if a different user wants to use the same email
              if (user && self.id !== user.id) {
                return next('Email already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    typeOfUser: {
      type: DataTypes.INTEGER,
      allowNull:false,
      defaultValue:2
    },

    country: {
      type: DataTypes.STRING,
      allowNull:true,
      defaultValue:null
    },

    birthDate:{
      type: DataTypes.DATEONLY,
      allowNull:true,
      defaultValue:null
    },

    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    password: {
      type: DataTypes.STRING,
      allowNull:false
    },

    numberFotos: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    }
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        associate: function(models){
          User.hasMany(models.Foto,{foreignKey: "userId", as: "Fotos"});
        }

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }

    });

  return User;
}
</code>```

Model Foto:

```<code>"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var User = require('./User');

module.exports = function (sequelize, DataTypes) {
  var Foto = sequelize.define("Foto", {
    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false
    },
    date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    lat: {
      type: DataTypes.STRING,
      allowNull: true
    },
    lon: {
      type: DataTypes.STRING,
      allowNull: true
    },
    altitude: {
      type: DataTypes.STRING,
      allowNull: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    plantId: {
      type: DataTypes.INTEGER,
      allowNull: true
    },
  },
    {
      associate: function (models) {
        Foto.belongsToMany(models.User, {as:'Users'});
      }
    }
  );

  return Foto;
}
</code>```

then i try to get something like this in a json three:

```<code>[{
FotoA:{
prop1:value1,
prop2:value2,
user:{
userProp1
}
}
FotoB:{

}

}]
</code>```

on my route i do the following:

```<code>allPictures: function (req, res) {
    Foto.findAll({include: [{ model: User, as: "Users",where:{userId: User.id} }]})
    .then(function (fotos) {
        res.send(fotos);
    })
},
</code>```

if there is a better way to do this instad of eager loading please share it, i just need to get the userId and the username.

Thanks

答:
I guess you defined the association wrong, as you mentioned a Foto should belong to one User.

try

```<code>Foto.belongsTo(model.User);
</code>```

instead of

```<code>associate: function (models) {
  Foto.belongsToMany(models.User, {as:'Users'});
}
</code>```

And also there should be no need for the where clause when selecting. If your associations are defined correctly, you can simply do

```<code>Foto.findAll({include: [models.User]})
</code>```

Title: Sequelize how to join 2 tables 1:N

Body:
I have 2 models: User and Foto

Each User has a lot of fotos, and each foto can have just 1 user related.

To do that i use include, the problem is, i can use the include just when i am querying the user and not when i query the foto.

I get there is no relationshop between User and foto problem.

So at the moment i have this:

Model User:

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var Foto = require('./Foto');

module.exports = function (sequelize, DataTypes) {
  var User = sequelize.define("User", {
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { username: value } })
            .then(function (user) {
              // reject if a different user wants to use the same username
              if (user && self.id !== user.id) {
                return next('username already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    email: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        isUnique: function (value, next) {
          var self = this;
          User.find({ where: { email: value } })
            .then(function (user) {
              // reject if a different user wants to use the same email
              if (user && self.id !== user.id) {
                return next('Email already in use!');
              }
              return next();
            })
            .catch(function (err) {
              return next(err);
            });
        }
      }
    },

    typeOfUser: {
      type: DataTypes.INTEGER,
      allowNull:false,
      defaultValue:2
    },

    country: {
      type: DataTypes.STRING,
      allowNull:true,
      defaultValue:null
    },

    birthDate:{
      type: DataTypes.DATEONLY,
      allowNull:true,
      defaultValue:null
    },

    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    points: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },

    password: {
      type: DataTypes.STRING,
      allowNull:false
    },

    numberFotos: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    }
  }, {
      classMethods: {
        generateHash: function (password) {
          return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
        },
        associate: function(models){
          User.hasMany(models.Foto,{foreignKey: "userId", as: "Fotos"});
        }

      },
      instanceMethods: {
        validPassword: function (password) {
          return bcrypt.compareSync(password, this.password);
        }
      }

    });

  return User;
}

Model Foto:

"use strict";
var sequelize = require('./index');
var bcrypt = require('bcrypt-nodejs');
var User = require('./User');

module.exports = function (sequelize, DataTypes) {
  var Foto = sequelize.define("Foto", {
    reports: {
      type: DataTypes.INTEGER,
      defaultValue: 0
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false
    },
    date: {
      type: DataTypes.DATE,
      allowNull: true
    },
    lat: {
      type: DataTypes.STRING,
      allowNull: true
    },
    lon: {
      type: DataTypes.STRING,
      allowNull: true
    },
    altitude: {
      type: DataTypes.STRING,
      allowNull: true
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false
    },
    plantId: {
      type: DataTypes.INTEGER,
      allowNull: true
    },
  },
    {
      associate: function (models) {
        Foto.belongsToMany(models.User, {as:'Users'});
      }
    }
  );

  return Foto;
}

then i try to get something like this in a json three:

[{
FotoA:{
prop1:value1,
prop2:value2,
user:{
userProp1
}
}
FotoB:{

}

}]

on my route i do the following:

allPictures: function (req, res) {
    Foto.findAll({include: [{ model: User, as: "Users",where:{userId: User.id} }]})
    .then(function (fotos) {
        res.send(fotos);
    })
},

if there is a better way to do this instad of eager loading please share it, i just need to get the userId and the username.

Thanks

Body:
I guess you defined the association wrong, as you mentioned a Foto should belong to one User.

try

Foto.belongsTo(model.User);

instead of

associate: function (models) {
  Foto.belongsToMany(models.User, {as:'Users'});
}

And also there should be no need for the where clause when selecting. If your associations are defined correctly, you can simply do

Foto.findAll({include: [models.User]})


问:
How to remind user when the specific date comes in Watson Conversation Service.or JSON
So I am trying to make a reminder chatbot and the code I made is not working as well as I expected.

What I did was, for example, if I were to send a reminder after a day, response conditions would be like the following:

```<code>"conditions": now().reformatDateTime().toInt()+1
</code>```

then followed by output-text-value as usual.

Is this valid? Any kinds of suggestion will be more than welcome. Thanks!

答:
You user need to call the day for you get before you did something.
Active your sys entitie: @sys-date for get days.

And, for example, user will ask:

What I need to do today?

Save the day with one context variable, like:

```<code>{
  "context": {
    "verifiedDate": <? @sys-date ?>;
  },
  "output": {
    "text": {
      "values": [
        "Please wait and I'll verified your request."
      ],
      "selection_policy": "sequential"
    }
  }
}
</code>```

And, only if user asks, you will do something within your application for remember the user.

Like:

Example (app.js):

```<code>function updateMessage(input, data, req, res) {
  if (data.context.verifiedDate){
    searchRequest(data, req, res);
    } else if (data.output && data.output.text) {
      return res.json(data);
    }
    return data;
}
</code>```

You can use the data for sending something within conversation flow.

```<code>function searchRequest(data, req, res){
    // something to do and return value
    var sendRequest = "Thanks for wait, the request is" + valueRequest;
    data.output.text[0] = sendRequest;
    return data;
}
</code>```

This example is with Nodejs, data have all return from Watson Conversation, like entities, intents, context variables, node flows, etc. The logic is the same, you need to access the data returned from your conversation, and after, access the context variables to do something within your app.

Add days:

```<code>Date.prototype.addDays = function(days) {
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + days);
  return dat;
}

var dat = new Date();

alert(dat.addDays(5))
</code>```

You can add days with the days parameter or with one number, like my example.

Body:
So I am trying to make a reminder chatbot and the code I made is not working as well as I expected.

What I did was, for example, if I were to send a reminder after a day, response conditions would be like the following:

"conditions": now().reformatDateTime().toInt()+1

then followed by output-text-value as usual.

Is this valid? Any kinds of suggestion will be more than welcome. Thanks!

Body:
You user need to call the day for you get before you did something.
Active your sys entitie: @sys-date for get days.

And, for example, user will ask:

What I need to do today?

Save the day with one context variable, like:

{
  "context": {
    "verifiedDate": <? @sys-date ?>;
  },
  "output": {
    "text": {
      "values": [
        "Please wait and I'll verified your request."
      ],
      "selection_policy": "sequential"
    }
  }
}

And, only if user asks, you will do something within your application for remember the user.

Like:

Example (app.js):

function updateMessage(input, data, req, res) {
  if (data.context.verifiedDate){
    searchRequest(data, req, res);
    } else if (data.output && data.output.text) {
      return res.json(data);
    }
    return data;
}

You can use the data for sending something within conversation flow.

function searchRequest(data, req, res){
    // something to do and return value
    var sendRequest = "Thanks for wait, the request is" + valueRequest;
    data.output.text[0] = sendRequest;
    return data;
}

This example is with Nodejs, data have all return from Watson Conversation, like entities, intents, context variables, node flows, etc. The logic is the same, you need to access the data returned from your conversation, and after, access the context variables to do something within your app.

Add days:

Date.prototype.addDays = function(days) {
  var dat = new Date(this.valueOf());
  dat.setDate(dat.getDate() + days);
  return dat;
}

var dat = new Date();

alert(dat.addDays(5))

You can add days with the days parameter or with one number, like my example.


问:
Why I can't create firebase user
I am trying to create a firebase user, but my code fails, keep getting the Authentication failed message, can you please tell me why?
Also, I don't know how the new firebase is connecting to my account, I used to create a Firebase object and pass my link to it, but now is different, and I can't see where it does it (It asked to login in my webbrowser and that's it, I can't find a reference for it in the code)</p>

```<code>@Override
    public void onClick(View v) {
        pass.setText(pass.getText().toString().trim());
        email.setText(email.getText().toString().trim());
        mAuth.createUserWithEmailAndPassword(email.getText().toString(), pass.getText().toString())
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FirebaseUser user = mAuth.getCurrentUser();
                        } else {
                            Toast.makeText(MainActivityC.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
</code>```

答:
Check below code for your reference.. It will help you.</p>

```<code>    private FirebaseAuth mAuth;
    String mUserEmail = "sagar@example.com";
    String mPassword = "password";

  mAuth.createUserWithEmailAndPassword(mUserEmail, mPassword)
 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                Log.d(LOG_TAG, getString(R.string.log_message_auth_successful) + " createUserWithEmail:onComplete:" + task.isSuccessful());
             // if task is successful  then AuthStateListener  will get notified you can get user details there.
                // if task is not successful show error
                if (!task.isSuccessful()) {

                    try {
                        throw task.getException();
                    } catch (FirebaseAuthUserCollisionException e) {
                        // log error here

                  } catch (FirebaseNetworkException e) {
                        // log error here
                    } catch (Exception e) {
                     // log error here
                     }

                    } else {

              // successfully user account created
             // now the AuthStateListener runs the onAuthStateChanged callback

                }
            }

        });
     }
</code>```

Title: Why I can't create firebase user

Body:
I am trying to create a firebase user, but my code fails, keep getting the Authentication failed message, can you please tell me why?
Also, I don't know how the new firebase is connecting to my account, I used to create a Firebase object and pass my link to it, but now is different, and I can't see where it does it (It asked to login in my webbrowser and that's it, I can't find a reference for it in the code)

@Override
    public void onClick(View v) {
        pass.setText(pass.getText().toString().trim());
        email.setText(email.getText().toString().trim());
        mAuth.createUserWithEmailAndPassword(email.getText().toString(), pass.getText().toString())
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            FirebaseUser user = mAuth.getCurrentUser();
                        } else {
                            Toast.makeText(MainActivityC.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

Body:
Check below code for your reference.. It will help you.

    private FirebaseAuth mAuth;
    String mUserEmail = "sagar@example.com";
    String mPassword = "password";

  mAuth.createUserWithEmailAndPassword(mUserEmail, mPassword)
 .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {

                Log.d(LOG_TAG, getString(R.string.log_message_auth_successful) + " createUserWithEmail:onComplete:" + task.isSuccessful());
             // if task is successful  then AuthStateListener  will get notified you can get user details there.
                // if task is not successful show error
                if (!task.isSuccessful()) {

                    try {
                        throw task.getException();
                    } catch (FirebaseAuthUserCollisionException e) {
                        // log error here

                  } catch (FirebaseNetworkException e) {
                        // log error here
                    } catch (Exception e) {
                     // log error here
                     }

                    } else {

              // successfully user account created
             // now the AuthStateListener runs the onAuthStateChanged callback

                }
            }

        });
     }


问:
Wait for specific text in DOM element before continuing
I have a function that should wait for some text to change before it returns a value:

```<code>function getElementText() {
   while(isLoading()) {
   }
   return $('#element').text();
}

function isLoading() {
    return  $('#element')[0] &&
            $('#element').text().indexOf('Loading') >= 0;
}
</code>```

However I think the empty while is not a good option (will it block the event loop?)

答:
Elegant way with rxjs:

var source = document.getElementById('source');
var target = document.getElementById('target');

Rx.Observable.fromEvent(source, 'keyup')
  .filter( (e) => e.target.value === 'Admin' )
  .subscribe( () => target.innerText = "Matched." );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.min.js"></script>

<input id="source" /> <strong>input 'Admin' to trigger</strong>
<p id="target">Not match.</p></code>```

Body:
I have a function that should wait for some text to change before it returns a value:

function getElementText() {
   while(isLoading()) {
   }
   return $('#element').text();
}

function isLoading() {
    return  $('#element')[0] &&
            $('#element').text().indexOf('Loading') >= 0;
}

However I think the empty while is not a good option (will it block the event loop?)

Body:
Elegant way with rxjs:

var source = document.getElementById('source');
var target = document.getElementById('target');

Rx.Observable.fromEvent(source, 'keyup')
  .filter( (e) => e.target.value === 'Admin' )
  .subscribe( () => target.innerText = "Matched." );

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.min.js"></script>

<input id="source" /> <strong>input 'Admin' to trigger</strong>
<p id="target">Not match.</p>


问:
Android: remove notification from notification bar
I have created an application and  with an event I manage to add notification in android notification bar.  Now  I need sample how to remove that notification from notification bar on an event ?? </p>

答:
this will help:

```<code>NotificationManager mNotificationManager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();
</code>```

this should remove all notifications made by the app

and if you create a notification by calling

```<code>startForeground();
</code>```

inside a Service.you may have to call

```<code>stopForeground(false);
</code>```

first,then cancel the notification.

Body:
this will help:

NotificationManager mNotificationManager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancelAll();

this should remove all notifications made by the app

and if you create a notification by calling

startForeground();

inside a Service.you may have to call

stopForeground(false);

first,then cancel the notification.


问:
Angular 4 application on Github Pages
I have a simple Angular (4) application which I want to host on Github Pages, the option to do this from Angular CLI seems removed. Is there a way to do this, if so how?

this is my package.json

```<code>{
  "name": "e-portfolio",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/cli": "^1.0.6",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.26",
    "@ngx-translate/core": "^6.0.1",
    "bootstrap": "^4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.6",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}
</code>```

When trying to use ng build I get this message

As a forewarning, we are moving the CLI npm package to "@angular/cli" with the next release,
which will only support Node 6.9 and greater. This package will be officially deprecated
shortly after.

To disable this warning use "ng set --global warnings.packageDeprecation=false".

You have to be inside an angular-cli project in order to use the build command.

my debuglog

```<code>0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start' ]
2 info using npm@3.10.10
3 info using node@v6.9.5
4 verbose stack Error: ENOENT: no such file or directory, open 'C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json'
4 verbose stack     at Error (native)
5 verbose cwd C:\Users\User\Documents\School\Portfolio\ePortfolio
6 error Windows_NT 10.0.15063
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
8 error node v6.9.5
9 error npm  v3.10.10
10 error path C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json
11 error code ENOENT
12 error errno -4058
13 error syscall open
14 error enoent ENOENT: no such file or directory, open 'C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json'
15 error enoent ENOENT: no such file or directory, open 'C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json'
15 error enoent This is most likely not a problem with npm itself
15 error enoent and is related to npm not being able to find a file.
16 verbose exit [ -4058, true ]
</code>```

答:
When using this commad ng build --prod --base-href "https://USERNAME.github.io/REPOSITORY_NAME/"

I switched out to my repository which is called ePortfolio, I typed it in as eportfolio, It seems that the letter P had to be capital for it to work.

Title: Angular 4 application on Github Pages

Body:
I have a simple Angular (4) application which I want to host on Github Pages, the option to do this from Angular CLI seems removed. Is there a way to do this, if so how?

this is my package.json

{
  "name": "e-portfolio",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/cli": "^1.0.6",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "@ng-bootstrap/ng-bootstrap": "^1.0.0-alpha.26",
    "@ngx-translate/core": "^6.0.1",
    "bootstrap": "^4.0.0-alpha.6",
    "core-js": "^2.4.1",
    "font-awesome": "^4.7.0",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@angular/cli": "1.0.6",
    "@angular/compiler-cli": "^4.0.0",
    "@types/jasmine": "2.5.38",
    "@types/node": "~6.0.60",
    "codelyzer": "~2.0.0",
    "jasmine-core": "~2.5.2",
    "jasmine-spec-reporter": "~3.2.0",
    "karma": "~1.4.1",
    "karma-chrome-launcher": "~2.1.1",
    "karma-cli": "~1.0.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-coverage-istanbul-reporter": "^0.2.0",
    "protractor": "~5.1.0",
    "ts-node": "~2.0.0",
    "tslint": "~4.5.0",
    "typescript": "~2.2.0"
  }
}

When trying to use ng build I get this message

As a forewarning, we are moving the CLI npm package to "@angular/cli" with the next release,
which will only support Node 6.9 and greater. This package will be officially deprecated
shortly after.

To disable this warning use "ng set --global warnings.packageDeprecation=false".

You have to be inside an angular-cli project in order to use the build command.

my debuglog

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start' ]
2 info using npm@3.10.10
3 info using node@v6.9.5
4 verbose stack Error: ENOENT: no such file or directory, open 'C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json'
4 verbose stack     at Error (native)
5 verbose cwd C:\Users\User\Documents\School\Portfolio\ePortfolio
6 error Windows_NT 10.0.15063
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
8 error node v6.9.5
9 error npm  v3.10.10
10 error path C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json
11 error code ENOENT
12 error errno -4058
13 error syscall open
14 error enoent ENOENT: no such file or directory, open 'C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json'
15 error enoent ENOENT: no such file or directory, open 'C:\Users\User\Documents\School\Portfolio\ePortfolio\package.json'
15 error enoent This is most likely not a problem with npm itself
15 error enoent and is related to npm not being able to find a file.
16 verbose exit [ -4058, true ]


问:
Optionally adding items to a Scala Map
I am looking for an idiomatic solution to this problem.

I am building a val Scala (immutable) Map and would like to optionally add one or more items:

```<code>val aMap =
  Map(key1 -> value1,
      key2 -> value2,
      (if (condition) (key3 -> value3) else ???))
</code>```

How can this be done without using a var? What should replace the ???? Is it better to use the + operator?

```<code>val aMap =
  Map(key1 -> value1,
      key2 -> value2) +
  (if (condition) (key3 -> value3) else ???))
</code>```

One possible solution is:

```<code>val aMap =
  Map(key1 -> value1,
      key2 -> value2,
      (if (condition) (key3 -> value3) else (null, null))).filter {
        case (k, v) => k != null && v != null
      }
</code>```

Is this the best way?

答:
You can add directly to the map:</p>

```<code>scala> val map = Map(1 -> 2, 3 -> 4)
scala> val some = Some(5 -> 6)
scala> val none = None
scala> val combinedMap = map ++ some ++ none
combinedMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4, 5 -> 6)
</code>```

Title: Optionally adding items to a Scala Map

Body:
I am looking for an idiomatic solution to this problem.

I am building a val Scala (immutable) Map and would like to optionally add one or more items:

val aMap =
  Map(key1 -> value1,
      key2 -> value2,
      (if (condition) (key3 -> value3) else ???))

How can this be done without using a var? What should replace the ???? Is it better to use the + operator?

val aMap =
  Map(key1 -> value1,
      key2 -> value2) +
  (if (condition) (key3 -> value3) else ???))

One possible solution is:

val aMap =
  Map(key1 -> value1,
      key2 -> value2,
      (if (condition) (key3 -> value3) else (null, null))).filter {
        case (k, v) => k != null && v != null
      }

Is this the best way?

Body:
You can add directly to the map:

scala> val map = Map(1 -> 2, 3 -> 4)
scala> val some = Some(5 -> 6)
scala> val none = None
scala> val combinedMap = map ++ some ++ none
combinedMap: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 3 -> 4, 5 -> 6)


问:
"Marshall" or "Marshal"? "Marshalling" or "Marshaling"?
Which one is it in a programming context?  Is there a difference?  I've seen it both ways and I don't want to spell it wrong in my code.</p>

答: I'd go with "Marshal" and "Marshalling".</p>


问:
GIT - Multiple repos - List all touched/dirty files (example Android build system)
In a typical multiple repo scenario like Android build system (where kernel is a git repo, framework/base is a different git repo, bootable/bootlaoder/lk  etc..) it becomes difficult to track all the changed files in all the repos.

A practical issue is say if most of your changes are spread across  1 or 2 major components (like kernel and framwork/base) you might miss to commit a minor change in a different repo.

Question is: Is there a single command that I can fire from the root folder that does the job

Pls note if possible I would try to avoid installing new software/packages - any working solution with repo /git would be greatly appreciated

答:
Found a solution using repo forall :-

```<code>zhossain@zhossain-linux:/local/mnt/workspace/LE.UM.0.0_2_13$ repo forall -pc "git diff --name-only"

project bootable/bootloader/lk/
target/msm8909/init.c

project frameworks/
av/media/mtp/MtpMain.cpp

project kernel/msm-3.18/
arch/arm/boot/dts/qcom/apq8017-no-pmi-wcd-rome-cdp.dts
arch/arm/boot/dts/qcom/msm8917-pinctrl.dtsi
arch/arm64/configs/msm8937_defconfig
zhossain@zhossain-linux:/local/mnt/workspace/LE.UM.0.0_2_13$
</code>```

Body:
Found a solution using repo forall :-

zhossain@zhossain-linux:/local/mnt/workspace/LE.UM.0.0_2_13$ repo forall -pc "git diff --name-only"

project bootable/bootloader/lk/
target/msm8909/init.c

project frameworks/
av/media/mtp/MtpMain.cpp

project kernel/msm-3.18/
arch/arm/boot/dts/qcom/apq8017-no-pmi-wcd-rome-cdp.dts
arch/arm/boot/dts/qcom/msm8917-pinctrl.dtsi
arch/arm64/configs/msm8937_defconfig
zhossain@zhossain-linux:/local/mnt/workspace/LE.UM.0.0_2_13$


问:
Spark Framework CSRF Protection
I'm developping a REST-Service with the Spark Framework. So far i haven't found any possibility to implement CSRF Protection.

Is there the possibility to implement CSRF Protection using integrated functions? Or do i have to use external modules like Pac4j?

答:
I've figured it out, and it is really easy to implement. All you need is to add a custom Filter.</p>

```<code>before((request, response) -> {
    List<String> safeMethods = Arrays.asList("GET", "OPTIONS", "HEAD");
    if (!safeMethods.contains(request.requestMethod())) {
        if (!request.headers().contains("X-Requested-By")) {
            halt(400);
        }
    }
});
</code>```

Title: Spark Framework CSRF Protection

Body:
I've figured it out, and it is really easy to implement. All you need is to add a custom Filter.

before((request, response) -> {
    List<String> safeMethods = Arrays.asList("GET", "OPTIONS", "HEAD");
    if (!safeMethods.contains(request.requestMethod())) {
        if (!request.headers().contains("X-Requested-By")) {
            halt(400);
        }
    }
});


问:
Printing Ancestors of a node in Binary Tree
I need to print the ancestors of a node in binary tree. e.g Node 7 has ancestors as 1,3 . I have written the below code but output is coming as 7. Can you suggest the issues in this code?</p>

```<code>    1
   / \
  2   3
 / \ / \
4  5 6  7

 public static String findAncestor(BinaryTreeNode root , int number,  boolean matched) {

    if (root != null) {

        int rootData = root.getData();

        BinaryTreeNode left = root.getLeft();
        BinaryTreeNode right = root.getRight();

        if (left != null && right != null) {
            return findAncestor (root.getLeft(), number, matched ) + findAncestor (root.getRight(), number, matched);
        }

        if (left != null) {
            return findAncestor (root.getLeft(), number, matched ) ;
        }

        if (right != null) {
            return findAncestor (root.getRight(), number, matched ) ;
        }

        if (rootData == number) {
            matched = true;
            return String.valueOf(rootData);
        }
        if (matched) {
            return String.valueOf(rootData);
        }
    }
    return "";
}
</code>```

答:
This piece of code work fine for giving all the ancestors a particular node , node is root node and value is the value of the node for which we have to find all the ancestor.</p>

```<code>static boolean flag=false;
  static void AnchersterOf(AnchesterNode node,int value) {
        // TODO Auto-generated method stub
      if(node==null)
          return ;

      if(node.value==value){

          flag=true;
          return;
      }

     if(flag==false){
      AnchersterOf(node.left,value);
      if(flag==true){
            AnchersterOf(node,value);

      } if(flag==true)
      System.out.println(node.value);
    AnchersterOf(node.right,value);
    if(flag==true)
          System.out.println(node.value);
     }

    }
</code>```

Body:
I need to print the ancestors of a node in binary tree. e.g Node 7 has ancestors as 1,3 . I have written the below code but output is coming as 7. Can you suggest the issues in this code?

    1
   / \
  2   3
 / \ / \
4  5 6  7

 public static String findAncestor(BinaryTreeNode root , int number,  boolean matched) {

    if (root != null) {

        int rootData = root.getData();

        BinaryTreeNode left = root.getLeft();
        BinaryTreeNode right = root.getRight();

        if (left != null && right != null) {
            return findAncestor (root.getLeft(), number, matched ) + findAncestor (root.getRight(), number, matched);
        }

        if (left != null) {
            return findAncestor (root.getLeft(), number, matched ) ;
        }

        if (right != null) {
            return findAncestor (root.getRight(), number, matched ) ;
        }

        if (rootData == number) {
            matched = true;
            return String.valueOf(rootData);
        }
        if (matched) {
            return String.valueOf(rootData);
        }
    }
    return "";
}

Body:
This piece of code work fine for giving all the ancestors a particular node , node is root node and value is the value of the node for which we have to find all the ancestor.

static boolean flag=false;
  static void AnchersterOf(AnchesterNode node,int value) {
        // TODO Auto-generated method stub
      if(node==null)
          return ;

      if(node.value==value){

          flag=true;
          return;
      }

     if(flag==false){
      AnchersterOf(node.left,value);
      if(flag==true){
            AnchersterOf(node,value);

      } if(flag==true)
      System.out.println(node.value);
    AnchersterOf(node.right,value);
    if(flag==true)
          System.out.println(node.value);
     }

    }


问:
SQL ORACLE Get week numbers from multiple datetime rows
I have 70.000 rows of data, including a date time column (YYYY-MM-DD HH24-MM-SS.).
I want to split this data into 3 separate columns; Hour, day and Week number.

The date time column name is 'REGISTRATIONDATE' from the table 'CONTRACTS'.

This is what I have so far for the day and hour columns:

```<code>SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour"
FROM CONTRACTS;
</code>```

I have seen the options to get a week number for specific dates, this assignment concerns 70.000 dates so this is not an option.

答:
Assuming your REGISTRATIONDATE  if formatted as 'MM/DD/YYYY'

the simples  (and the faster  ) query is based  ond to to_char(to_date(REGISTRATIONDATE,'MM/DD/YYYY'),'WW')
(otherwise   convert you column in a proper date and perform the conversio to week number)

```<code>SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour",
to_char(to_date(REGISTRATIONDATE,'MM/DD/YYYY'),'WW') as "Week"
FROM CONTRACTS;
</code>```

Body:
I have 70.000 rows of data, including a date time column (YYYY-MM-DD HH24-MM-SS.).
I want to split this data into 3 separate columns; Hour, day and Week number.

The date time column name is 'REGISTRATIONDATE' from the table 'CONTRACTS'.

This is what I have so far for the day and hour columns:

SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour"
FROM CONTRACTS;

I have seen the options to get a week number for specific dates, this assignment concerns 70.000 dates so this is not an option.

Body:
Assuming your REGISTRATIONDATE  if formatted as 'MM/DD/YYYY'

the simples  (and the faster  ) query is based  ond to to_char(to_date(REGISTRATIONDATE,'MM/DD/YYYY'),'WW')
(otherwise   convert you column in a proper date and perform the conversio to week number)

SELECT substr(REGISTRATIONDATE, 0, 10) AS "Date",
substr(REGISTRATIONDATE, 11, 9) AS "Hour",
to_char(to_date(REGISTRATIONDATE,'MM/DD/YYYY'),'WW') as "Week"
FROM CONTRACTS;


问:
First request to rails app extremely slow
The first request to my rails app is extremely slow in all environments.

This should not be due different way of caching/loading gems. It was fine two hours ago and no major changes are made.

What I did the hours before I noticed my app turned slow:

I messed around in production.rb (NOT in development.rb): I was playing around with config.serve_static_assets = true

I did a bunch of tasks to diagnose why asset pipeline did not load my stylesheets and images in production (like rake assets:precompile RAILS_ENV=production and rake:clean assets:precompile).

Afterwards I obviously tried to undo all the changes I made, but for some reason my app is now slow in development, while it was perfectly fine before.

How can I fix this?

Thanks in advance :-)

UPDATE 1

When I send a request for localhost:3000, only after 12-13 seconds I receive:
Started GET "/" for ::1 at random time

Rendering behaving is normal. All requests after the first one are fine.

UPDATE 2

In an older version of my application I did the following:

Replace the old 'app'-folder with the newer one

Replace the old 'db'-files with the newer one

Replace the old 'config'-files with the newer one

Everything is running smoothly and still have no clue as to what was wrong in the first place. Please note that the version of the app from yesterday still runs slow, so this is not a non-rails related issue.

答:
I have this problem too, and i found bottleneck.
Problem in realization OpenSSL::Random.random_bytes on Windows (see this: https://github.com/rails/rails/issues/25805). It used for cookies.

I wrote this solution for my debug machine. But this is very dangerous and not must be used in production

```<code>module OpenSSL
  module Random
    def self.random_bytes(length)
      ::Random.new.bytes(length)
    end
  end
end
</code>```

Body:
I have this problem too, and i found bottleneck.
Problem in realization OpenSSL::Random.random_bytes on Windows (see this: https://github.com/rails/rails/issues/25805). It used for cookies.

I wrote this solution for my debug machine. But this is very dangerous and not must be used in production

module OpenSSL
  module Random
    def self.random_bytes(length)
      ::Random.new.bytes(length)
    end
  end
end


问:
How to handle send intent (share menu item) in react native app?
I have successfully configured iOS app to handle audio document types (not deeplinks!) so I can use share dialog to open audio files in my app, this works fine.

I have successfully configured Android intent-filter in the AndroidManifest.xml to hande audiofiles same way, this is also recognized fine by Android system and I see my app when I use share menu on audiofiles. However, Android implementation of Linking component seems to ignore SEND intent actions and only care about View intent actions as I saw on IntentModule.java:55:

```<code>    if (Intent.ACTION_VIEW.equals(action) && uri != null) {
      initialURL = uri.toString();
    }
</code>```

I tried to patch intent in my MainActivity.java to make it return same uri with VIEW action, but this always produces an error in runtime.

```<code>@Override
public Intent getIntent() {
    Intent origIntent = super.getIntent();
    if (origIntent != null && Intent.ACTION_SEND.equals(origIntent.getAction())) {
        return new Intent(Intent.ACTION_VIEW, origIntent.getData());
    }
    return origIntent;
}
</code>```

However I always get an error indicating that getData is null.

I saw this answer, but having a share extension is an overkill for me.

答:
I discovered that Intent might contain additional information called ClipData, which can contain Uri as well. My luck was that I had exactly one Uri (I guess it can contain multiple Uri objects if I share multiple audiofiles at once. So this code worked, I can now share files to react native app

```<code>@Override
public Intent getIntent() {
    Intent origIntent = super.getIntent();
    if (origIntent != null && Intent.ACTION_SEND.equals(origIntent.getAction())) {
        return new Intent(Intent.ACTION_VIEW, this.uriFromClipData(origIntent.getClipData()));
    }
    return origIntent;
}

private Uri uriFromClipData(ClipData clip) {
    if (clip != null && clip.getItemCount() > 0) {
        return clip.getItemAt(0).getUri();
    }
    return null;
}
</code>```

Body:
I have successfully configured iOS app to handle audio document types (not deeplinks!) so I can use share dialog to open audio files in my app, this works fine.

I have successfully configured Android intent-filter in the AndroidManifest.xml to hande audiofiles same way, this is also recognized fine by Android system and I see my app when I use share menu on audiofiles. However, Android implementation of Linking component seems to ignore SEND intent actions and only care about View intent actions as I saw on IntentModule.java:55:

    if (Intent.ACTION_VIEW.equals(action) && uri != null) {
      initialURL = uri.toString();
    }

I tried to patch intent in my MainActivity.java to make it return same uri with VIEW action, but this always produces an error in runtime.

@Override
public Intent getIntent() {
    Intent origIntent = super.getIntent();
    if (origIntent != null && Intent.ACTION_SEND.equals(origIntent.getAction())) {
        return new Intent(Intent.ACTION_VIEW, origIntent.getData());
    }
    return origIntent;
}

However I always get an error indicating that getData is null.

I saw this answer, but having a share extension is an overkill for me.

Body:
I discovered that Intent might contain additional information called ClipData, which can contain Uri as well. My luck was that I had exactly one Uri (I guess it can contain multiple Uri objects if I share multiple audiofiles at once. So this code worked, I can now share files to react native app

@Override
public Intent getIntent() {
    Intent origIntent = super.getIntent();
    if (origIntent != null && Intent.ACTION_SEND.equals(origIntent.getAction())) {
        return new Intent(Intent.ACTION_VIEW, this.uriFromClipData(origIntent.getClipData()));
    }
    return origIntent;
}

private Uri uriFromClipData(ClipData clip) {
    if (clip != null && clip.getItemCount() > 0) {
        return clip.getItemAt(0).getUri();
    }
    return null;
}


问:
post time don't change in loop - wordpress
I want a simple loop to get latest five posts, which only consist of post title and time i wrote the loop below and the title generates fine, however the time doesn't change. as it get the first post in the loop's time for other posts as well. so all the post time is same.

Please advise why time don't loop ?

<?php
   $args = array( 'numberposts' => '5' );
   $recent_posts = wp_get_recent_posts( $args );
   foreach( $recent_posts as $recent ){ ?>

                           " class="ticker-a">
                              <?php echo get_the_time($recent["g:i a"]); ?>
                              <?php echo $recent["post_title"]; ?>

 <?php  }
   wp_reset_query();
?>```

答:
Try this one </p>

```<code>echo get_the_time('', $recent["ID"]);
</code>```

Body:
I want a simple loop to get latest five posts, which only consist of post title and time i wrote the loop below and the title generates fine, however the time doesn't change. as it get the first post in the loop's time for other posts as well. so all the post time is same.

Please advise why time don't loop ?

<?php
   $args = array( 'numberposts' => '5' );
   $recent_posts = wp_get_recent_posts( $args );
   foreach( $recent_posts as $recent ){ ?>

                           <a href="<?php echo get_permalink($recent["ID"]); ?>" class="ticker-a">
                              <?php echo get_the_time($recent["g:i a"]); ?>
                              <?php echo $recent["post_title"]; ?>

 <?php  }
   wp_reset_query();
?>

Body:
Try this one

echo get_the_time('', $recent["ID"]);


答: Marshal, marshalling.</p>

Title: "Marshall" or "Marshal"? "Marshalling" or "Marshaling"?

Body: Which one is it in a programming context?  Is there a difference?  I've seen it both ways and I don't want to spell it wrong in my code.

Body: Marshal, marshalling.


问:
Put text in the middle of a circle using. d3.js
I have this piece of code in which circles are drawn, I need to put a text inside each circle, I would also like to know how I can put a certain size to each of the elements of the circle.
Thank you very much.</p>

```<code>  svg = d3.select(selector)
    .append('svg')
    .attr('width', width)
    .attr('height', height);

  // Bind nodes data to what will become DOM elements to represent them.
  bubbles = svg.selectAll('.bubble')
    .data(nodes, function (d) { return d.id; });

  // Create new circle elements each with class `bubble`.
  // There will be one circle.bubble for each object in the nodes array.
  // Initially, their radius (r attribute) will be 0.

  bubbles.enter().append('circle')
    .classed('bubble', true)
    .attr('r', 0)
    .attr('fill', function (d) {  return  fillColor(d.group); })
    .attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker(); })
    .attr('stroke-width', 2)
    .on('mouseover', showDetail)
    .on('mouseout', hideDetail);

  // Fancy transition to make bubbles appear, ending with the
  // correct radius
  bubbles.transition()
    .duration(2000)
    .attr('r', function (d) { return d.radius; });
</code>```

答:
A good practice would be to create a group element for each bubble because they will be composed of two elements - a circle and text.

```<code>// Bind nodes data to what will become DOM elements to represent them.
bubbles = svg.selectAll('.bubble')
  .data(nodes, function(d) {
    return d.id;
  })
  .enter()
  .append('g')
  .attr("transform", d => `translate(${d.x}, ${d.y})`)
  .classed('bubble', true)
  .on('mouseover', showDetail)
  .on('mouseout', hideDetail)
</code>```

After that, circles and texts can be appended:

```<code>circles = bubbles.append('circle')
  .attr('r', 0)
  .attr('stroke-width', 2)

texts = bubbles.append('text')
  .attr('text-anchor', 'middle')
  .attr('alignment-baseline', 'middle')
  .style('font-size', d => d.radius * 0.4 + 'px')
  .attr('fill-opacity', 0)
  .attr('fill', 'white')
  .text(d => d.text)

// Fancy transition to make bubbles appear, ending with the
// correct radius
circles.transition()
  .duration(2000)
  .attr('r', function(d) {
    return d.radius;
  });
</code>```

For hiding/showing text, you can use fill-opacity attribute and set it 0 when the text should be hidden, and 1 if it should be shown:

```<code>function showDetail(d, i) {
  d3.select(this.childNodes[1]).attr('fill-opacity', 1)
}

function hideDetail(d, i) {
  d3.select(this.childNodes[1]).attr('fill-opacity', 0)
}
</code>```

example: https://jsfiddle.net/r880wm24/

Body:
I have this piece of code in which circles are drawn, I need to put a text inside each circle, I would also like to know how I can put a certain size to each of the elements of the circle.
Thank you very much.

  svg = d3.select(selector)
    .append('svg')
    .attr('width', width)
    .attr('height', height);

  // Bind nodes data to what will become DOM elements to represent them.
  bubbles = svg.selectAll('.bubble')
    .data(nodes, function (d) { return d.id; });

  // Create new circle elements each with class `bubble`.
  // There will be one circle.bubble for each object in the nodes array.
  // Initially, their radius (r attribute) will be 0.

  bubbles.enter().append('circle')
    .classed('bubble', true)
    .attr('r', 0)
    .attr('fill', function (d) {  return  fillColor(d.group); })
    .attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker(); })
    .attr('stroke-width', 2)
    .on('mouseover', showDetail)
    .on('mouseout', hideDetail);

  // Fancy transition to make bubbles appear, ending with the
  // correct radius
  bubbles.transition()
    .duration(2000)
    .attr('r', function (d) { return d.radius; });

Body:
A good practice would be to create a group element for each bubble because they will be composed of two elements - a circle and text.

// Bind nodes data to what will become DOM elements to represent them.
bubbles = svg.selectAll('.bubble')
  .data(nodes, function(d) {
    return d.id;
  })
  .enter()
  .append('g')
  .attr("transform", d => `translate(${d.x}, ${d.y})`)
  .classed('bubble', true)
  .on('mouseover', showDetail)
  .on('mouseout', hideDetail)

After that, circles and texts can be appended:

circles = bubbles.append('circle')
  .attr('r', 0)
  .attr('stroke-width', 2)

texts = bubbles.append('text')
  .attr('text-anchor', 'middle')
  .attr('alignment-baseline', 'middle')
  .style('font-size', d => d.radius * 0.4 + 'px')
  .attr('fill-opacity', 0)
  .attr('fill', 'white')
  .text(d => d.text)

// Fancy transition to make bubbles appear, ending with the
// correct radius
circles.transition()
  .duration(2000)
  .attr('r', function(d) {
    return d.radius;
  });

For hiding/showing text, you can use fill-opacity attribute and set it 0 when the text should be hidden, and 1 if it should be shown:

function showDetail(d, i) {
  d3.select(this.childNodes[1]).attr('fill-opacity', 1)
}

function hideDetail(d, i) {
  d3.select(this.childNodes[1]).attr('fill-opacity', 0)
}

example: https://jsfiddle.net/r880wm24/