问:
Select form parameter passes through but cannot use Rails include?
Ok Rails 4.2 simple stuff here....basic select tag multiple:

```<code> <%= select_tag('status_ids', options_for_select(Status.to_a), :multiple => true,  :include_blank => true, :class => "form-control  js-example-basic-multiple") %>
</code>```

HTML params =

```<code>    {"utf8"=>"✓","search_term"=>"","status_ids"=>["1", "2"],"commit"=>"Search"}
</code>```

Now in the controller i can do a query like and it works fine

```<code>    x=searchresults.where(status_ids: params[:status_ids])
</code>```

what i cannot do is this:

```<code>    if params[:status_ids].include?(2)
</code>```

or

```<code>    if 2.in?(params[:status_ids])
</code>```

i can do this in the console and return a => true
but not in the controller

what is the issue here?

danke

答:
Because your status_ids are strings, not integers like in your comparison code. You need to convert them to integers first..</p>

```<code>if params[:status_ids].map(:&to_i).include?(2)
</code>```

Body:
Ok Rails 4.2 simple stuff here....basic select tag multiple:

 <%= select_tag('status_ids', options_for_select(Status.to_a), :multiple => true,  :include_blank => true, :class => "form-control  js-example-basic-multiple") %>

HTML params =

    {"utf8"=>"✓","search_term"=>"","status_ids"=>["1", "2"],"commit"=>"Search"}

Now in the controller i can do a query like and it works fine

    x=searchresults.where(status_ids: params[:status_ids])

what i cannot do is this:

    if params[:status_ids].include?(2)

or

    if 2.in?(params[:status_ids])

i can do this in the console and return a => true
but not in the controller

what is the issue here?

danke

Body:
Because your status_ids are strings, not integers like in your comparison code. You need to convert them to integers first..

if params[:status_ids].map(:&to_i).include?(2)


来源: stackexchange

问:
MySQL - Keep finding superiors of employees until the most superior employee is reached
I have an employees table in which all employees report to a superior except for one employee who reports to no one as he is the boss.

```<code>employeeNumber | reportsTo
---------------|-----------------
1002           | null
1056           | 1002
1143           | 1056
1165           | 1143
...
</code>```

I want to be able to show the employee numbers of all employees who are superiors of a particular employee. (i.e. the person he reportsTo, and the employee who that person reportsTo, ... all the way up)

For e.g. employeeNumber 1165 should yield

```<code>   | employeeNumber |
   |----------------|
   | null           |
   | 1002           |
   | 1056           |
   | 1143           |
</code>```

I have written a MySQL statement which carries out the query but I believe this is a bit too complex to read and understand:

```<code>select reportsTo as employeeNumber from employees where employeeNumber in
(select reportsTo from employees where employeeNumber in (select reportsTo from employees where
employeeNumber = 1165)) union select reportsTo from employees where employeeNumber in
(select reportsTo from employees where employeeNumber = 1165) union select reportsTo from employees
where employeeNumber = 1165;
</code>```

What simple MySQL statement can I use to get the same result?

答:
This procedure should help you out

Loop until you get the NULL superior and temporary table

```<code>CREATE PROCEDURE GetList(me int)
BEGIN

create table mytable (id int, reportsto int);

create table mytemp  (id int);

insert into mytable
values
(1002, NULL ),
(1056, 1002 ),
(1143, 1056 ),
(1165, 1143 );

set @parent:=me;

insert into mytemp
values (@parent);

WHILE @parent IS NOT NULL DO

  insert into mytemp
  select reportsto from mytable where id=@parent;

  select @parent:=reportsto  from mytable where id=@parent;

end while;

select * from mytemp;

drop table mytable;
drop table mytemp;

END;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an employees table in which all employees report to a superior except for one employee who reports to no one as he is the boss.

employeeNumber | reportsTo
---------------|-----------------
1002           | null
1056           | 1002
1143           | 1056
1165           | 1143
...

I want to be able to show the employee numbers of all employees who are superiors of a particular employee. (i.e. the person he reportsTo, and the employee who that person reportsTo, ... all the way up)

For e.g. employeeNumber 1165 should yield

   | employeeNumber |
   |----------------|
   | null           |
   | 1002           |
   | 1056           |
   | 1143           |

I have written a MySQL statement which carries out the query but I believe this is a bit too complex to read and understand:

select reportsTo as employeeNumber from employees where employeeNumber in
(select reportsTo from employees where employeeNumber in (select reportsTo from employees where
employeeNumber = 1165)) union select reportsTo from employees where employeeNumber in
(select reportsTo from employees where employeeNumber = 1165) union select reportsTo from employees
where employeeNumber = 1165;

What simple MySQL statement can I use to get the same result?

Body:
This procedure should help you out

Loop until you get the NULL superior and temporary table

CREATE PROCEDURE GetList(me int)
BEGIN

create table mytable (id int, reportsto int);

create table mytemp  (id int);

insert into mytable
values
(1002, NULL ),
(1056, 1002 ),
(1143, 1056 ),
(1165, 1143 );

set @parent:=me;

insert into mytemp
values (@parent);

WHILE @parent IS NOT NULL DO

  insert into mytemp
  select reportsto from mytable where id=@parent;

  select @parent:=reportsto  from mytable where id=@parent;

end while;

select * from mytemp;

drop table mytable;
drop table mytemp;

END;


问:
What are some uses for the "flash" scope in JSF?
I'm in the process of learning JSF 2.1, and the "flash" scope seems to overlap other scopes. Does this bring any value, or should I disregard it as a modern GOTO: statement? Does it have a higher usage? Is it preferable to use over other types of scope (view, request, etc)?</p>

答:
It's main usage is as follows:

you submit a form

it is handled by an action method in a managed bean

then a redirecting navigation rule is returned

you need to show an object obtained in the action method on the result page

If it weren't for the flash scope, you would either need to pass the result in a serialized form in the URL, or use forward rather than redirect. But this is bad user experience (if he presses refresh)

ContentLicense: CC BY-SA 2.5


问:
Erase an element from a map then put it back
Suppose I have a backtracking algorithm where I need to remove an element from a map, do something, then put it back. I am not sure if there is a good way to do it:

```<code>func(std::<K, V> map &dict) {
    for (auto i : dict) {
       remove i from dict;
       func(dict);
       put i back to dict;
    }
}
</code>```

I know there are ways to delete an element from map in here but I am not sure if there are ways to achieve what I described above. I am aware that I can create a new dict in for loop and pass it in func but I am wondering if it can be done using the same dict.

答:
This question has an answer here.

However, your problem may be that you would like the function to ignore the key K while processing dict.  How about a second parameter "K ignore" and make the function skip that pair?  You could give it a default value in the declaration if that breaks other code, or overload the function.

Body:
Suppose I have a backtracking algorithm where I need to remove an element from a map, do something, then put it back. I am not sure if there is a good way to do it:

func(std::<K, V> map &dict) {
    for (auto i : dict) {
       remove i from dict;
       func(dict);
       put i back to dict;
    }
}

I know there are ways to delete an element from map in here but I am not sure if there are ways to achieve what I described above. I am aware that I can create a new dict in for loop and pass it in func but I am wondering if it can be done using the same dict.


问:
Is it the driver or the workers who reads the text file when sc.textfile is used?
I am wondering how is sc.textfile used in Spark. My guess is that the driver reads a portion of the file at a time, and distributes the read text to the workers, to process. Or is it that the workers read the text directly themselves from the file without the involvement of the driver?</p>

答:
textfile creates an RDD, as mentioned in the ref:

Text file RDDs can be created using SparkContext’s textFile method.

There is also this note:

If using a path on the local filesystem, the file must also be
  accessible at the same path on worker nodes. Either copy the file to
  all workers or use a network-mounted shared file system.

which implies that your guess about the driver parsing the file and then distributing the data to the slaves is wrong.


问:
How can I add an unremovable prefix to an HTML input field?
Using jQuery, how can I add a default value of http:// into an input field that can’t be removed, but that still allows you to type a URL after it?

Default: http://

Url: http://www.domain.name

答:
UPDATE: Guillaumesm's answer to Ecmascript 5:

```<code>Form.prototype.set_HttpPrefix = function (e) {
    if (e.data.$url.val().length < 7) {
        e.data.$url.val('http://')

    }
    else if (e.data.$url.val().indexOf('http://') !== 0) {
        e.data.$url.val('http://' + String.fromCharCode(e.which))
    }
}
</code>```

Body:
UPDATE: Guillaumesm's answer to Ecmascript 5:

Form.prototype.set_HttpPrefix = function (e) {
    if (e.data.$url.val().length < 7) {
        e.data.$url.val('http://')

    }
    else if (e.data.$url.val().indexOf('http://') !== 0) {
        e.data.$url.val('http://' + String.fromCharCode(e.which))
    }
}


问:
Drop a database using entity framework
I'm trying to remove a database form my application using entity framework.
The code I use is the following:

```<code>using (var dbContext = container.Resolve<ApplicationDbContext>())
    {
      dbContext.Database.Delete();
    }
</code>```

According to msdn this should work but nothing happens.

the dbContext is registered using ContainerControlledLifetimeManager and should be the same instance used to create the DB.

答:
After @moguzalp and this (MSDN Database.Delete Function), I came with a solution for my case:

```<code>using System.Data.Entity;

Database.Delete("connectionStringOrName");
</code>```

In my case I was trying to Recreate a mssqllocalDb database for test purposes. But whenever I used the same DbContext (or an immediately new one, disposing the first and opening another), it looked like the database was still up when I tried to create it.

Bad Example: (x)

```<code>public static void RecreateDatabase(string schemaScript)
{
    using (DbContext context = new DbContext("connectionStringName"))
    {
        context.Database.Delete(); // Delete returns true, but...
        Database database = context.Database;
        database.Create(); // Database already exists!
        database.ExecuteSqlCommand(schemaScript);
    }
}
</code>```

Working example: (/)

```<code>public static void RecreateDatabase(string schemaScript)
{
    Database.Delete(); // Opens and disposes its own connection

    using (DbContext context = new DbContext("connectionStringName")) // New connection
    {
        Database database = context.Database;
        database.Create(); // Works!
        database.ExecuteSqlCommand(schemaScript);
    }
}
</code>```

Context: I'm using this on an [AssemblyInitialize] function to test my ModelContexts

Title: Drop a database using entity framework

Body:
I'm trying to remove a database form my application using entity framework.
The code I use is the following:

using (var dbContext = container.Resolve<ApplicationDbContext>())
    {
      dbContext.Database.Delete();
    }

According to msdn this should work but nothing happens.

the dbContext is registered using ContainerControlledLifetimeManager and should be the same instance used to create the DB.

Body:
After @moguzalp and this (MSDN Database.Delete Function), I came with a solution for my case:

using System.Data.Entity;

Database.Delete("connectionStringOrName");

In my case I was trying to Recreate a mssqllocalDb database for test purposes. But whenever I used the same DbContext (or an immediately new one, disposing the first and opening another), it looked like the database was still up when I tried to create it.

Bad Example: (x)

public static void RecreateDatabase(string schemaScript)
{
    using (DbContext context = new DbContext("connectionStringName"))
    {
        context.Database.Delete(); // Delete returns true, but...
        Database database = context.Database;
        database.Create(); // Database already exists!
        database.ExecuteSqlCommand(schemaScript);
    }
}

Working example: (/)

public static void RecreateDatabase(string schemaScript)
{
    Database.Delete(); // Opens and disposes its own connection

    using (DbContext context = new DbContext("connectionStringName")) // New connection
    {
        Database database = context.Database;
        database.Create(); // Works!
        database.ExecuteSqlCommand(schemaScript);
    }
}

Context: I'm using this on an [AssemblyInitialize] function to test my ModelContexts


问:
AttributeError: 'NoneType' object has no attribute 'children'
```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

for child in bsObj.find("table",{"id":"giftlist"}).children:
    print(child)
</code>```

Could anyone tell me what wrong with my code is? :((( What should i do next?

答:
One option is to put the offending loop construct into a try, then handle the exception that appears when the interator returns None:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

try:
    for child in bsObj.find("table",{"id":"giftlist"}).children:
        print(child)
except AttributeError:
    # do what you want to do when bsObj.find() returns None
</code>```

Or you could check the resulting list for None before entering the loop:

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

result = bsObj.find("table",{"id":"giftlist"})
if result:
    for child in result.children:
        print(child)
else:
    # do what you want to do when bsObj.find() returns None
</code>```

Body:
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

for child in bsObj.find("table",{"id":"giftlist"}).children:
    print(child)

Could anyone tell me what wrong with my code is? :((( What should i do next?

Body:
One option is to put the offending loop construct into a try, then handle the exception that appears when the interator returns None:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

try:
    for child in bsObj.find("table",{"id":"giftlist"}).children:
        print(child)
except AttributeError:
    # do what you want to do when bsObj.find() returns None

Or you could check the resulting list for None before entering the loop:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html,"html.parser")

result = bsObj.find("table",{"id":"giftlist"})
if result:
    for child in result.children:
        print(child)
else:
    # do what you want to do when bsObj.find() returns None


问:
Graph correlation discovery algorithm
I'm not a mathematician, so I'll try to describe this in a layperson's terms.

I'm trying to take two time series, which could represent any variable quantity, maximum daily temperature, stock price high of the day, etc.  These would be multiplied by a factor that would make their maxima and minima correspond.  (E.g., two temperature series might range between different coldest and warmest temperatures, but in both I'd treat coldest as 0% and warmest as 100%.)

Given this, I want to find out what relative shift in their start times would produce the "most" correlation.  That is, the longest sample period with a "high" correlation.  (I know that's a bit fuzzy.)

As a simple example, given last year's temperatures for several cities, it might choose two cities that both had a period of several weeks in which every other day had a maximum temperature that was 2/3 of the preceding day.  This didn't necessarily start for both cities on the same day.  That's where the time shifting trials come in.

A pointer to a discussion, pseudo code, or actual utility library would be good.

答: You are trying to calculate Cross-Correlations.</p>

Title: Graph correlation discovery algorithm


问:
Full size popup when address bar is showing and not showing - mobile chrome
My popup is supposed to be full screen height minus the header.

However, when the address bar is not showing up (after scrolling down), the space is left blank.

```<code>var currencyHeight = $(window).innerHeight() - headerHeight;
</code>```

$(window).innerHeight() returns 559 both when the address bar is showing and not showing. When it is showing, the popup works fine, full screen minus the header:

but when it is not showing up you can see the empty space:

How do people usually solve this?

Minimal example:

https://jsfiddle.net/zzuxvg4p/4/

But because jsfiddle uses an iframe, you cannot test it on android properly, so this page has the code from that jsfiddle:

https://annotated-dev.limebuild.net/media/test.html (click on the blue box in the footer. If the address bar isn't showing then the black box is not full screen, but if it is showing then it is full screen).

Here is the issue even after I add the no-scroll class to body with overflow hidden:

答:
Took me a while to figure this one out. Starting from scratch, here's what I came up with, tested on android and it does disable top bar from hiding:

var resizer = function(){
  $("html, body, #wrapper").css({
    height: $(window).height()
  });
}, openPopup = function(){
   $('.popup').addClass('open');
}, closePopup = function(){
   $('.popup').removeClass('open');
};

$(window).on('load resize',resizer);
$('.trigger').on('click tap', openPopup);
$('.popup').on('click tap', closePopup);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

* {
  box-sizing: border-box;
}

body #wrapper {
  overflow-y: auto;
  color: white;
}

body #wrapper div {
  padding: 1rem;
}

.test {
  min-height: 150vh;
  background-color: red;
}

.trigger {
  background-color: blue;
  min-height: 10em;
}

.popup {
  position: fixed;
  width: 100%;
  min-height: 100%;
  bottom: 0;
  background-color: black;
  transform: translateY(100%);
  transition: transform .6s cubic-bezier(.4, 0, .2, 1);
  pointer-events: none;
}

.popup.open {
  transform: translateY(0);
  pointer-events: all;
}</code>```

 I'd be the test

I'd open the popup

I'd be the popup

```

Body:
My popup is supposed to be full screen height minus the header.

However, when the address bar is not showing up (after scrolling down), the space is left blank.

var currencyHeight = $(window).innerHeight() - headerHeight;

$(window).innerHeight() returns 559 both when the address bar is showing and not showing. When it is showing, the popup works fine, full screen minus the header:

but when it is not showing up you can see the empty space:

How do people usually solve this?

Minimal example:

https://jsfiddle.net/zzuxvg4p/4/

But because jsfiddle uses an iframe, you cannot test it on android properly, so this page has the code from that jsfiddle:

https://annotated-dev.limebuild.net/media/test.html (click on the blue box in the footer. If the address bar isn't showing then the black box is not full screen, but if it is showing then it is full screen).

Here is the issue even after I add the no-scroll class to body with overflow hidden:

Body:
Took me a while to figure this one out. Starting from scratch, here's what I came up with, tested on android and it does disable top bar from hiding:

var resizer = function(){
  $("html, body, #wrapper").css({
    height: $(window).height()
  });
}, openPopup = function(){
   $('.popup').addClass('open');
}, closePopup = function(){
   $('.popup').removeClass('open');
};

$(window).on('load resize',resizer);
$('.trigger').on('click tap', openPopup);
$('.popup').on('click tap', closePopup);

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
}

* {
  box-sizing: border-box;
}

body #wrapper {
  overflow-y: auto;
  color: white;
}

body #wrapper div {
  padding: 1rem;
}

.test {
  min-height: 150vh;
  background-color: red;
}

.trigger {
  background-color: blue;
  min-height: 10em;
}

.popup {
  position: fixed;
  width: 100%;
  min-height: 100%;
  bottom: 0;
  background-color: black;
  transform: translateY(100%);
  transition: transform .6s cubic-bezier(.4, 0, .2, 1);
  pointer-events: none;
}

.popup.open {
  transform: translateY(0);
  pointer-events: all;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
  <div class="test"> I'd be the test</div>
  <div class="trigger">I'd open the popup</div>
  <div class="popup">I'd be the popup</div>
</div>


问:
how to populate existing list / array
I am new at reason / ocaml / functional programming.

I know about List.append and [] @ [] but these functions will create new list but how to populate existing list / array?

What is the best way to populate list?

What is the best way to populate array? Means if coords type is let coords: array point = [];

Or this is wrong flow (algorithm) for such case?

Reason code:

```<code>type point = {x: int, y: int};

let coords: list point = [];

let append raw =>
  Array.iter
    (
      fun data => {
        let p = {x: data.x, y: data.y};
        /* how to append p to coords */
        ()
      }
    )
    raw;
</code>```

JS analogue:

```<code>const coords = [];
const append = raw => raw.forEach({x, y} => {
  coords.push({
    x: process(x),
    y: process(y)
  });
});
</code>```

答:
Welcome to Reason!

In Reason/OCaml, lists are immutable. Under the hood they're simple singly-linked list. You create new ones each time you "modify" them. Here's an example:

```<code>let a = [1, 2, 3];
let b = [0, ...a];
</code>```

This is akin to JavaScript's array "spread", except here you're taking the existing a, linking a new node 0 at the front, and calling it b. a still points to [1, 2, 3] (thus "immutable"). b is now [0, 1, 2, 3]. This is efficient since the [1, 2, 3] part is shared.

The advantage of this is that you don't have to worry about passing your list around and accidentally have an obscure function modify it. List's immutability allows you to reason about your code purely by looking at the value you're staring right now (since it'll never change!).

The drawback of list is that it's inefficient to add something at the end:

```<code>let c = a @ [4]
</code>```

That operation's basically taking a list of one item, [4], and successively attaching each item of [1, 2, 3] to it. So linear in terms of perf. But judging by the simplicity of the list implementation, it was historically deemed worth the tradeoff.

So 3. it's the wrong flow if you're trying to set a list item.

The best way to populate a list in your case is by mapping over it non-mutatively, from the old list: let newList = List.map (fun blabla => ...) raw

Same for array. Map over it. There's Array.of_list and Array.to_list if you're ever stuck.

More on array: OCaml array is mutable, and its size is unchangeable. Think of it as a block of memory. You'd allocate a new array through Array.make newSize, then populate it through Array.set. This wouldn't make sense if you're resizing the array a lot, so choose the right data structure.

For JS compilation, BuckleScript compiles an ocaml array to a JS array. It's thus mutable and resizable. You'll find your familiar JS array operations under Js.Array

As a general heuristic, if you'd like to change the length: try filter. If you'd like to change the length and the contained items, try fold_left. Otherwise, map.

More recently, we've started implementing some immutable, resizable, optionally mutable array. Stay tuned!

ContentLicense: CC BY-SA 4.0

Title: how to populate existing list / array

Body:
I am new at reason / ocaml / functional programming.

I know about List.append and [] @ [] but these functions will create new list but how to populate existing list / array?

What is the best way to populate list?

What is the best way to populate array? Means if coords type is let coords: array point = [];

Or this is wrong flow (algorithm) for such case?

Reason code:

type point = {x: int, y: int};

let coords: list point = [];

let append raw =>
  Array.iter
    (
      fun data => {
        let p = {x: data.x, y: data.y};
        /* how to append p to coords */
        ()
      }
    )
    raw;

JS analogue:

const coords = [];
const append = raw => raw.forEach({x, y} => {
  coords.push({
    x: process(x),
    y: process(y)
  });
});

Body:
Welcome to Reason!

In Reason/OCaml, lists are immutable. Under the hood they're simple singly-linked list. You create new ones each time you "modify" them. Here's an example:

let a = [1, 2, 3];
let b = [0, ...a];

This is akin to JavaScript's array "spread", except here you're taking the existing a, linking a new node 0 at the front, and calling it b. a still points to [1, 2, 3] (thus "immutable"). b is now [0, 1, 2, 3]. This is efficient since the [1, 2, 3] part is shared.

The advantage of this is that you don't have to worry about passing your list around and accidentally have an obscure function modify it. List's immutability allows you to reason about your code purely by looking at the value you're staring right now (since it'll never change!).

The drawback of list is that it's inefficient to add something at the end:

let c = a @ [4]

That operation's basically taking a list of one item, [4], and successively attaching each item of [1, 2, 3] to it. So linear in terms of perf. But judging by the simplicity of the list implementation, it was historically deemed worth the tradeoff.

So 3. it's the wrong flow if you're trying to set a list item.

The best way to populate a list in your case is by mapping over it non-mutatively, from the old list: let newList = List.map (fun blabla => ...) raw

Same for array. Map over it. There's Array.of_list and Array.to_list if you're ever stuck.

More on array: OCaml array is mutable, and its size is unchangeable. Think of it as a block of memory. You'd allocate a new array through Array.make newSize, then populate it through Array.set. This wouldn't make sense if you're resizing the array a lot, so choose the right data structure.

For JS compilation, BuckleScript compiles an ocaml array to a JS array. It's thus mutable and resizable. You'll find your familiar JS array operations under Js.Array

As a general heuristic, if you'd like to change the length: try filter. If you'd like to change the length and the contained items, try fold_left. Otherwise, map.

More recently, we've started implementing some immutable, resizable, optionally mutable array. Stay tuned!


问:
Plot.ly in Timemode: fixed grid size
I have a timemode chart with timestamps on the x-axis.
The dataset is appromximately 20 seconds long and plot.ly automatically sets a tick label every 2 seconds on the x-axis, which is fine.

However, the x-axis grid lines are automatically set to the positions of the ticks.
I would like to have fix grildlines every second, independent from the x-axis timestamps/ticks.

Is that possible?

答:
As far as I know you cannot do that directly but you could add the grid yourself via shapes.

var data =   {
    x: [],
    y: [],
    type: 'scatter'
  };
var lines = [];

//get a random time series
var startTime = new Date().getTime();
for (var i = 0; i < 20; i += 1) {
    data.x.push(startTime + i * 1000);
    data.y.push(i % 5 * Math.random())
}

//create a line every 1000 msecs
for (i = Math.min(...data.x); i < Math.max(...data.x); i += 1000) {
  lines.push({type: 'line',
              xref: 'x0',
              x0: i,
              x1: i,
              y0: Math.min(...data.y),
              y1: Math.max(...data.y),
              layer: 'below',
              line: {color: 'gray'}
             }
            );
}

var layout = {xaxis: {type: 'date',
                      dtick: 2000,
                      showgrid: false
                     },
              yaxis: {showgrid: false},
              shapes: lines
             };
Plotly.newPlot('myDiv', [data], layout);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div></code>```

Title: Plot.ly in Timemode: fixed grid size

Body:
As far as I know you cannot do that directly but you could add the grid yourself via shapes.

var data =   {
    x: [],
    y: [],
    type: 'scatter'
  };
var lines = [];

//get a random time series
var startTime = new Date().getTime();
for (var i = 0; i < 20; i += 1) {
    data.x.push(startTime + i * 1000);
    data.y.push(i % 5 * Math.random())
}

//create a line every 1000 msecs
for (i = Math.min(...data.x); i < Math.max(...data.x); i += 1000) {
  lines.push({type: 'line',
              xref: 'x0',
              x0: i,
              x1: i,
              y0: Math.min(...data.y),
              y1: Math.max(...data.y),
              layer: 'below',
              line: {color: 'gray'}
             }
            );
}

var layout = {xaxis: {type: 'date',
                      dtick: 2000,
                      showgrid: false
                     },
              yaxis: {showgrid: false},
              shapes: lines
             };
Plotly.newPlot('myDiv', [data], layout);

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv"></div>


问:
Does the android screen capture file contain any informations about the source device?
Is we have a screen capture token on android  , what information can we get from that file about the source device ( we can know the screen resolution for exemple , but what else  ? ) .</p>

答:
as I know, the basic screenshot have the default jpg metadata, which contain just basic date and maybe the android version of the device.
but if you want to look into the metadata of a photo you can try to look for EXIF tool to get it.</p>


问:
Wait for return statement from "then" of angular $q.all
I have a function and inside the function, I have a $q.all call as follows

```<code>function test()
{
    $q.all(promises).then(function(response)
    {
         return response;
    });
}
</code>```

But my function doesn't return anything as it is not waiting for the response. Also, what should I do if I have to return from the then part of a $q.all inside a $q.all

答:
You return the promise itself and chain .then handlers from there.

```<code>function test() {
  return $q.all(promises);
}

test().then(function (response) {
  // do stuff with response
});
</code>```

Returning a promise from a .then handler adds it to the outer promise chain, so you can chain promises together like so:

```<code>function test() {
  $q.all(promises).then(function (response) {
    return $q.all(morePromises);
  });
}

test().then(function (morePromisesResponse) {
  // do stuff
});
</code>```

You can also just return a non-promise value from a .then handler and it is wrapped in a promise and returned to the outer chain so you can get the value in the next .then handler.

```<code>function test() {
  $q.all(promises).then(function (response) {
    return 123;
  });
}

test().then(function (result) {
  // result is 123
});
</code>```

I'm happy to give a more specific answer if you're still confused. I'd just need a code sample from you and what you're trying to accomplish so I can help.

Body:
I have a function and inside the function, I have a $q.all call as follows

function test()
{
    $q.all(promises).then(function(response)
    {
         return response;
    });
}

But my function doesn't return anything as it is not waiting for the response. Also, what should I do if I have to return from the then part of a $q.all inside a $q.all

Body:
You return the promise itself and chain .then handlers from there.

function test() {
  return $q.all(promises);
}

test().then(function (response) {
  // do stuff with response
});

Returning a promise from a .then handler adds it to the outer promise chain, so you can chain promises together like so:

function test() {
  $q.all(promises).then(function (response) {
    return $q.all(morePromises);
  });
}

test().then(function (morePromisesResponse) {
  // do stuff
});

You can also just return a non-promise value from a .then handler and it is wrapped in a promise and returned to the outer chain so you can get the value in the next .then handler.

function test() {
  $q.all(promises).then(function (response) {
    return 123;
  });
}

test().then(function (result) {
  // result is 123
});

I'm happy to give a more specific answer if you're still confused. I'd just need a code sample from you and what you're trying to accomplish so I can help.


问:
Interface type in method, how do I access it?
I would like to define a custom Interface "Sorting" with a custom compareTo method

```<code>public class Testing implements Sorting{

    public static void main(String [] args){
        Testing x1 = new Testing (4);
        Testing x2 = new Testing (5);
        System.out.println(x1.compareTo(x2));
    }
    private final int x;

    public Testing(int x){
        this.x= x;
    }

    @Override
    public int compareTo(Sorting s) {

        if(this == s)
        return 0;
        if(this.x> ((Testing) s).x) return 1;
        if(this.x<((Testing) s).x) return -1;
        return 0;
    }
}
</code>```

I don't know how to access said compareTo method to compare the values, but I would like to be able to use this for ints, for Strings and all kinds of types that fit to Sorting.

Also, does

```<code>public class Testing<Integer> implements Sorting<Integer>{..}
</code>```

help any bit if I use Testing for int only?

Edit: Thank you for the replies, I want to point out that I can't use Comparable.
To be more exact: I want to compare two objects, one is of Testing type, the other one is of type "Sorting" which is given to the method. How can I convert Sorting into the Testing type while still being able to compare those two?

Edit2: I think I managed it, I'll update the code above and then you can maybe understand what I'm struggling with, I still don't know why that exactly is possible, but it seems to work.

答:
Use the Interfaces not the concrete types. That way you can mix different concrete types that implement the same interface.

Either you have to change to compareTo(V other) or you have to add something more to your interface like this:

```<code>public interface Sorting <V> {
    V getValue();
    int compareTo(Sorting<V> other);
}

public class Testing implements Sorting<Integer>{

    public static void main(String [] args){
        Sorting<Integer> x1 = new Testing (4);
        Sorting<Integer> x2 = new Testing (5);
        System.out.println(String.format("compareTo is %d", x1.compareTo(x2));
    }

    private final int value;

    public Testing(int value){
        this.value = value;
    }

    @Override
    int getValue(){
        return value;
    }

    @Override
    public int compareTo(Sorting<Integer> other) {
        int otherValue = other.getValue();
        if(value > otherValue)
            return 1;
        else if(value < otherValue)
            return -1;
        return 0; // must be ==
    }
}
</code>```

Note that you don't really gain much by doing compareTo(Sorting<Integer> other) as opposed to compareTo(Integer other) as the other's implementation isn't important, which is why Comparable does just that. You also won't be able to use a lambda now as your interface has 2 abstract methods, you can still use an anonymous class though.

```<code> int someInt = 12344;
 x1.compareTo(new Sorting<Integer>() {
    @Override int getValue(){ return someInt; }
    @Override int compareTo(Sorting<Integer> other) { return 0; }// who cares isn't used
}
</code>```

Body:
I would like to define a custom Interface "Sorting" with a custom compareTo method

public class Testing implements Sorting{

    public static void main(String [] args){
        Testing x1 = new Testing (4);
        Testing x2 = new Testing (5);
        System.out.println(x1.compareTo(x2));
    }
    private final int x;

    public Testing(int x){
        this.x= x;
    }

    @Override
    public int compareTo(Sorting s) {

        if(this == s)
        return 0;
        if(this.x> ((Testing) s).x) return 1;
        if(this.x<((Testing) s).x) return -1;
        return 0;
    }
}

I don't know how to access said compareTo method to compare the values, but I would like to be able to use this for ints, for Strings and all kinds of types that fit to Sorting.

Also, does

public class Testing<Integer> implements Sorting<Integer>{..}

help any bit if I use Testing for int only?

Edit: Thank you for the replies, I want to point out that I can't use Comparable.
To be more exact: I want to compare two objects, one is of Testing type, the other one is of type "Sorting" which is given to the method. How can I convert Sorting into the Testing type while still being able to compare those two?

Edit2: I think I managed it, I'll update the code above and then you can maybe understand what I'm struggling with, I still don't know why that exactly is possible, but it seems to work.

Body:
Use the Interfaces not the concrete types. That way you can mix different concrete types that implement the same interface.

Either you have to change to compareTo(V other) or you have to add something more to your interface like this:

public interface Sorting <V> {
    V getValue();
    int compareTo(Sorting<V> other);
}

public class Testing implements Sorting<Integer>{

    public static void main(String [] args){
        Sorting<Integer> x1 = new Testing (4);
        Sorting<Integer> x2 = new Testing (5);
        System.out.println(String.format("compareTo is %d", x1.compareTo(x2));
    }

    private final int value;

    public Testing(int value){
        this.value = value;
    }

    @Override
    int getValue(){
        return value;
    }

    @Override
    public int compareTo(Sorting<Integer> other) {
        int otherValue = other.getValue();
        if(value > otherValue)
            return 1;
        else if(value < otherValue)
            return -1;
        return 0; // must be ==
    }
}

Note that you don't really gain much by doing compareTo(Sorting<Integer> other) as opposed to compareTo(Integer other) as the other's implementation isn't important, which is why Comparable does just that. You also won't be able to use a lambda now as your interface has 2 abstract methods, you can still use an anonymous class though.

 int someInt = 12344;
 x1.compareTo(new Sorting<Integer>() {
    @Override int getValue(){ return someInt; }
    @Override int compareTo(Sorting<Integer> other) { return 0; }// who cares isn't used
}


问:
How should I properly capture submitted form values with Contact Form 7 (wp)?
I've recently done a GTM set up to track checkboxes for a WordPress Contact Form with contact form 7. I've obviously read this article from from Simo but to be honest I didn't really understand it so here is what I've finally done :

A custom Javascript :

```<code>function checkbox_selector() {var array = ["group-963","group-964","group-965"];
    if ( document.getElementById(array[0]).style.display == "block" ) { return "Checkbox#1" }
    else if ( document.getElementById(array[1]).style.display == "block" ) { return "Checkbox#2" }
    else if ( document.getElementById(array[2]).style.display == "block" ) { return "Checkbox#3" }
    else { return "unchecked" }
}
</code>```

I used this custom Javascript to fill the event action tracking parameters in an event tag. The tag itself was fired on a simple form submission trigger.

Reading my custom Javascript you will understand that I didn't found any other solution than playing with display style of some elements.

Is there any way I could have done this job better ?

答:
Created an example for you to play around with:

$('input[type=checkbox]').on('click', function() {
 var $this = $(this);

  var checkVal = $(this).is(':checked');
  var checkName = $(this).attr('name');

  // do your push to GTM here
  alert(checkName + ', ' + checkVal);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="tony" value="tony" />
<input type="checkbox" name="pepper" value="pepper" /></code>```

The fiddle here:
https://jsfiddle.net/mrpharderwijk/56ef50og/1/

Body:
I've recently done a GTM set up to track checkboxes for a WordPress Contact Form with contact form 7. I've obviously read this article from from Simo but to be honest I didn't really understand it so here is what I've finally done :

A custom Javascript :

function checkbox_selector() {var array = ["group-963","group-964","group-965"];
    if ( document.getElementById(array[0]).style.display == "block" ) { return "Checkbox#1" }
    else if ( document.getElementById(array[1]).style.display == "block" ) { return "Checkbox#2" }
    else if ( document.getElementById(array[2]).style.display == "block" ) { return "Checkbox#3" }
    else { return "unchecked" }
}

I used this custom Javascript to fill the event action tracking parameters in an event tag. The tag itself was fired on a simple form submission trigger.

Reading my custom Javascript you will understand that I didn't found any other solution than playing with display style of some elements.

Is there any way I could have done this job better ?

Body:
Created an example for you to play around with:

$('input[type=checkbox]').on('click', function() {
 var $this = $(this);

  var checkVal = $(this).is(':checked');
  var checkName = $(this).attr('name');

  // do your push to GTM here
  alert(checkName + ', ' + checkVal);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="tony" value="tony" />
<input type="checkbox" name="pepper" value="pepper" />

The fiddle here:
https://jsfiddle.net/mrpharderwijk/56ef50og/1/


问:
CSS sticky footer does not work on the 8250 BlackBerry device
I wanted the footer on a mobile site I was working on to stick to the bottom of the page. I found the CSS Sticky Footer example by Ryan Fait and implemented it. On every browser I could conceivably test, I found the footer to stick nicely to the bottom.

And, then it happened. The clients complained about the footer throwing itself all over the place. On painfully requesting details, I found out that the problem occurred on only one model of BlackBerry mobile devices: the 8250 model. I pulled out a Windows VM, downloaded and installed the BlackBerry 8250 simulator, and sure enough, I saw the problem.

For a page the height of two BlackBerry screens, the footer sticks to the middle of the first screen, on top of everything else. The footer does not move as you scroll, and if you scroll down to the lower half of the page, the footer is not visible. It stays fixed to the middle of the top screen.

I will post the HTML and CSS to the end of this question. If I could get any pointers or clues as to why this is happening on the 8250 BlackBerry model, and not least, how it could be fixed, I would be very very grateful.

Thank you!

```<code><html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;"/>
        <style type="text/css">
            * { margin: 0; padding: 0; }
            html { height: 100%; }
            body { height: 100%; }
            .page {
                width: 100%;
                min-height: 100%;
                height: auto !important;
                height: 100%;
                margin: 0 auto -4em;
            }
            .push {
                height: 4em;
            }
            #footer {
                clear: both;
                position: relative;
                z-index: 10;
                height: 4em;
                margin-top: -4em;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="page">
            <!-- lots of other DIVs here for actual content -->
            <div class="push"></div>
        </div>
        <div id="footer">
            <!-- footer content over here -->
        </div>
    </body>
</html>
</code>```

I found this jQuery Sticky Footer hack. I am not too sure of whether this is going to be something people would suggest I should go with. I've not tested it yet, though.

Update: This is a small update to say that I toyed with the jQuery Sticky Footer hack linked right above. It didn't work for the BlackBerry device mentioned, either.

答:
After trying a couple of different things, I stumbled into the CSSStickyFooter solution. I implemented it and found it to work well on the Black Berry device in question, along with the rest of everything I have tested it on. I am going to paste the HTML and CSS code below:</p>

```<code><html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;"/>
        <title>Another CSS Sticky Footer that works on Black Berry</title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }

            html {
                height: 100%;
            }

            body {
                height: 100%;
            }

            .page {
                width: 100%;
                min-height: 100%;
            }

            .push {
                padding-bottom: 4em;
                overflow: auto;
            }

            #footer {
                position: relative;
                margin-top: -4em;
                height: 4em;
                clear: both;

                background-color: red;
            }
        </style>
    </head>

    <body>
        <div class="page">
            <div id="content">
                <p>Some body content will come here</p>
                <p>And over here as well.</p>
            </div>
            <div class="push"></div>
        </div>
        <div id="footer">
            <p>This is the footer block.</p>
        </div>
    </body>
</html>
</code>```

Body:
I wanted the footer on a mobile site I was working on to stick to the bottom of the page. I found the CSS Sticky Footer example by Ryan Fait and implemented it. On every browser I could conceivably test, I found the footer to stick nicely to the bottom.

And, then it happened. The clients complained about the footer throwing itself all over the place. On painfully requesting details, I found out that the problem occurred on only one model of BlackBerry mobile devices: the 8250 model. I pulled out a Windows VM, downloaded and installed the BlackBerry 8250 simulator, and sure enough, I saw the problem.

For a page the height of two BlackBerry screens, the footer sticks to the middle of the first screen, on top of everything else. The footer does not move as you scroll, and if you scroll down to the lower half of the page, the footer is not visible. It stays fixed to the middle of the top screen.

I will post the HTML and CSS to the end of this question. If I could get any pointers or clues as to why this is happening on the 8250 BlackBerry model, and not least, how it could be fixed, I would be very very grateful.

Thank you!

        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;"/>

I found this jQuery Sticky Footer hack. I am not too sure of whether this is going to be something people would suggest I should go with. I've not tested it yet, though.

Update: This is a small update to say that I toyed with the jQuery Sticky Footer hack linked right above. It didn't work for the BlackBerry device mentioned, either.

Body:
After trying a couple of different things, I stumbled into the CSSStickyFooter solution. I implemented it and found it to work well on the Black Berry device in question, along with the rest of everything I have tested it on. I am going to paste the HTML and CSS code below:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;"/>
        <title>Another CSS Sticky Footer that works on Black Berry</title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }

            html {
                height: 100%;
            }

            body {
                height: 100%;
            }

            .page {
                width: 100%;
                min-height: 100%;
            }

            .push {
                padding-bottom: 4em;
                overflow: auto;
            }

            #footer {
                position: relative;
                margin-top: -4em;
                height: 4em;
                clear: both;

                background-color: red;
            }
        </style>
    </head>

    <body>
        <div class="page">
            <div id="content">
                <p>Some body content will come here</p>
                <p>And over here as well.</p>
            </div>
            <div class="push"></div>
        </div>
        <div id="footer">
            <p>This is the footer block.</p>
        </div>
    </body>
</html>


问:
Android: How to turn on screen when new notification received?
I've tried almost everything and I can't understand how to turn on phone screen when new notification received in background mode.

I'm using FCM. When app is in background, notifications received are managed by system tray. How can I ask system tray to turn on the screen when something new received? Thank you!

答:
Finally, the answer is here.

If you are using Firebase API to send notifications from your server to device, remember that onMessageReceived() method from extended FirebaseMessagingService only calls in BACKGROUND if you send notifications like this:

```<code>                        $msg = array
                        (
                            'body'  => $newsObj['description'],
                        );
                        $fields = array
                        (
                            'registration_ids'  => $registrationIds,
                            'data'          => $msg,
                            'priority'  => "high"
                        );
</code>```

You see, if you change that "data" property to "notification", onMessageReceived() method only will be called if the app is in FOREGROUND.

For turning screen on when new notification is received, put the following code into your onMessageReceived() method:

```<code>        // Turn on the screen for notification
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        boolean result= Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isInteractive()|| Build.VERSION.SDK_INT< Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isScreenOn();

        if (!result){
            PowerManager.WakeLock wl = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MH24_SCREENLOCK");
            wl.acquire(10000);
            PowerManager.WakeLock wl_cpu = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MH24_SCREENLOCK");
            wl_cpu.acquire(10000);
        }
</code>```

In AndroidManifest.xml:

```<code>    <uses-permission android:name="android.permission.WAKE_LOCK" />
</code>```

That's all!

Body:
Finally, the answer is here.

If you are using Firebase API to send notifications from your server to device, remember that onMessageReceived() method from extended FirebaseMessagingService only calls in BACKGROUND if you send notifications like this:

                        $msg = array
                        (
                            'body'  => $newsObj['description'],
                        );
                        $fields = array
                        (
                            'registration_ids'  => $registrationIds,
                            'data'          => $msg,
                            'priority'  => "high"
                        );

You see, if you change that "data" property to "notification", onMessageReceived() method only will be called if the app is in FOREGROUND.

For turning screen on when new notification is received, put the following code into your onMessageReceived() method:

        // Turn on the screen for notification
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        boolean result= Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isInteractive()|| Build.VERSION.SDK_INT< Build.VERSION_CODES.KITKAT_WATCH&&powerManager.isScreenOn();

        if (!result){
            PowerManager.WakeLock wl = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MH24_SCREENLOCK");
            wl.acquire(10000);
            PowerManager.WakeLock wl_cpu = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MH24_SCREENLOCK");
            wl_cpu.acquire(10000);
        }

In AndroidManifest.xml:

    <uses-permission android:name="android.permission.WAKE_LOCK" />

That's all!


问:
PnPutil commands to uninstall the display adapter driver does not work
I am currently trying to uninstall display adapter driver in power shell.
I can simply go to device manager to find display adapter and uninstall the driver and then install the new driver. But I want to write an automated script to make it easy.

I tried to use "pnputil.exe -f -d oem##.inf" in power shell  to uninstall the display adapter driver.

But it did not work and gave me something like that

"Deleting the driver package failed: One or more devices are presently installed using the specified INF"

Does anyone know how can I solve this problem and make pnputil work?

答:
This isn't a PowerShell question really, as it's a window util.

from running pnputil /?

```<code>/delete-driver <oem#.inf> [/force]
Delete driver package from the driver store.
/force - delete driver package even when it is in use by devices.
</code>```

so running pnputil.exe /delete-driver oem##.inf /force should work for you.

Body:
This isn't a PowerShell question really, as it's a window util.

from running pnputil /?

/delete-driver <oem#.inf> [/force]
Delete driver package from the driver store.
/force - delete driver package even when it is in use by devices.

so running pnputil.exe /delete-driver oem##.inf /force should work for you.


问:
find, rounding and daystart
Suppose a file is created as follows:

```<code>$ touch -d "00:00:00 today" stamp
</code>```

Why the following command does not find it?

```<code>$ find -type f -daystart -mtime 0
</code>```

The following command does find this file

```<code>$ find -type f -daystart -mtime -1
</code>```

答:
From my own experimentation it looks like Joakim is right - at least for mmin.   daystart seems to be relative from the start of tomorrow.

```<code>ls -l stamp*
-rw-r--r-- 1 me me 0 Jun  7 00:01 stamp
-rw-r--r-- 1 me me 0 Jun  7 16:38 stamp2
-rw-r--r-- 1 me me 0 Jun  7 16:55 stamp3
</code>```

Notice how stamp3 is at 16:55

60*16 + 55 = 1015

1440 (one day) - 1015 = 425

```<code>find . -type f -daystart -mmin -425
./stamp3
</code>```

Let's catch stamp2 also

1440 - 60*16 - 38 = 442

```<code>find . -type f -daystart -mmin -442
./stamp2
./stamp3
</code>```

Now if I want to capture files from a range of times I can do something like this:

```<code>find . -type f -daystart -mmin -1439 -mmin +425
./stamp2
</code>```

Title: find, rounding and daystart

Body:
Suppose a file is created as follows:

$ touch -d "00:00:00 today" stamp

Why the following command does not find it?

$ find -type f -daystart -mtime 0

The following command does find this file

$ find -type f -daystart -mtime -1

Body:
From my own experimentation it looks like Joakim is right - at least for mmin.   daystart seems to be relative from the start of tomorrow.

ls -l stamp*
-rw-r--r-- 1 me me 0 Jun  7 00:01 stamp
-rw-r--r-- 1 me me 0 Jun  7 16:38 stamp2
-rw-r--r-- 1 me me 0 Jun  7 16:55 stamp3

Notice how stamp3 is at 16:55

60*16 + 55 = 1015

1440 (one day) - 1015 = 425

find . -type f -daystart -mmin -425
./stamp3

Let's catch stamp2 also

1440 - 60*16 - 38 = 442

find . -type f -daystart -mmin -442
./stamp2
./stamp3

Now if I want to capture files from a range of times I can do something like this:

find . -type f -daystart -mmin -1439 -mmin +425
./stamp2


问:
Windows 10 Mobile App Extended Execution keeps getting denied
I am trying to use Extended Execution on my Windows 10 UWP app for the purpose of location tracking. There are many examples of this online. I am basically using this common block of code.

```<code>using (var session = new ExtendedExecutionSession())
{
    session.Reason = ExtendedExecutionReason.LocationTracking;
    session.Description = "Tracking your location";
    session.Revoked += NewSession_Revoked;
    var result = await session.RequestExtensionAsync();

    switch (result)
    {
        case ExtendedExecutionResult.Allowed:
            await StartLocationTrackingAsync();
            break;
        default:
            case ExtendedExecutionResult.Denied:
            //Notify user or log this.
            break;
    }
}
</code>```

This block of code is executed in the Suspending event handler for my app, like this:

```<code>public Scenario1()
{
    this.InitializeComponent();
    Application.Current.Suspending += Current_Suspending;
}

private async void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
    //Do my extended execution request here.
}
</code>```

The first issue I had was I could not get that event to even fire but I read on SO that VS will not suspend your app while debugging. So, I forced it to suspend using the Lifecycle events drop down in VS. Now, I get the Suspending event to raise each time, which is good.

However, when I request the extended execution session, it is denied every single time. I have tried on the emulator and on my physical W10 Mobile device, multiple times each and every time, it is denied.

Why is this? How can I get it to be allowed?

Thanks!

答:
Assuming you have already declared Location in the app manifest, you will have to run the code in the foreground, which means it will work in your MainPage_Loaded callback but not in the suspended state.

A location tracking extended execution session can run as long as
  needed. However, there can only be one such session running per
  device. A location tracking extended execution session can only be
  requested in the foreground, and the app must be in the Running state.
  This ensures that the user is aware that the app has initiated an
  extended location tracking session.

To run this in the background, see this -

It is still possible to use the
  GeoLocator while the app is in the background by using a background
  task, or an app service, without requesting a location tracking
  extended execution session.

You use LocationTracking extended execution when you -

Specify ExtendedExecutionReason.LocationTracking when you create an
  ExtendedExecutionSession if your app needs to regularly log the
  location from the GeoLocator. Apps for fitness tracking and navigation
  that need to regularly monitor the user's location and should use this
  reason.

Here is the full article on this.

Body:
I am trying to use Extended Execution on my Windows 10 UWP app for the purpose of location tracking. There are many examples of this online. I am basically using this common block of code.

using (var session = new ExtendedExecutionSession())
{
    session.Reason = ExtendedExecutionReason.LocationTracking;
    session.Description = "Tracking your location";
    session.Revoked += NewSession_Revoked;
    var result = await session.RequestExtensionAsync();

    switch (result)
    {
        case ExtendedExecutionResult.Allowed:
            await StartLocationTrackingAsync();
            break;
        default:
            case ExtendedExecutionResult.Denied:
            //Notify user or log this.
            break;
    }
}

This block of code is executed in the Suspending event handler for my app, like this:

public Scenario1()
{
    this.InitializeComponent();
    Application.Current.Suspending += Current_Suspending;
}

private async void Current_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e)
{
    //Do my extended execution request here.
}

The first issue I had was I could not get that event to even fire but I read on SO that VS will not suspend your app while debugging. So, I forced it to suspend using the Lifecycle events drop down in VS. Now, I get the Suspending event to raise each time, which is good.

However, when I request the extended execution session, it is denied every single time. I have tried on the emulator and on my physical W10 Mobile device, multiple times each and every time, it is denied.

Why is this? How can I get it to be allowed?

Thanks!


问:
What does it take for .ticks() to work?
.ticks() doesn't seem to be working on my bar chart. Can somebody take a look?

Here's the fiddle. I set ticks on the x-axis near the beginning of the object:

```<code>xAxis = d3.svg.axis().scale(xScale).orient("bottom").ticks(3),
</code>```

答:
You can use a filter to decide which ticks to display:

```<code>var xAxis = d3.svg.axis()
    .scale(x)
    .tickValues(x.domain().filter(function(d, idx) { return idx%2==0 }))
    .orient("bottom");
</code>```

The snipped above comes from this example.

Title: What does it take for .ticks() to work?

Body:
.ticks() doesn't seem to be working on my bar chart. Can somebody take a look?

Here's the fiddle. I set ticks on the x-axis near the beginning of the object:

xAxis = d3.svg.axis().scale(xScale).orient("bottom").ticks(3),

Body:
You can use a filter to decide which ticks to display:

var xAxis = d3.svg.axis()
    .scale(x)
    .tickValues(x.domain().filter(function(d, idx) { return idx%2==0 }))
    .orient("bottom");

The snipped above comes from this example.


问:
How to minimize the costs for allocating and initializing an NSDateFormatter?
I noticed that using an NSDateFormatter can be quite costly. I figured out that allocating and initializing the object already consumes a lot of time.

Further, it seems that using an NSDateFormatter in multiple threads increases the costs. Can there be a blocking where the threads have to wait for each other?

I created a small test application to illustrate the problem. Please check it out.

http://github.com/johnjohndoe/TestNSDateFormatter

git://github.com/johnjohndoe/TestNSDateFormatter.git

What is the reason for such costs and how can I improve the usage?

17.12. - To update my observation: I do not understand why the threads run longer when processed parallel compared to when the run in serial order. The time difference only occurs when NSDateFormatter is used.

答:
Note: Your example program is very much a micro-benchmark and very effectively maximally amplifies that cost of a date formatter.   You are comparing doing absolutely nothing with doing something.  Thus, whatever that something is, it will appear to be something times slower than nothing.

Such tests are extremely valuable and extremely misleading.   Micro-benchmarks are generally only useful when you have a real world case of Teh Slow.   If you were to make this benchmark 10x faster (which, in fact, you probably could with what I suggest below) but the real world case is only 1% of overall CPU time used in your app, the end result is not going to be a dramatic speed improvement -- it will be barely noticeable.

What is the reason for such costs?

```<code>NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd HH:mm:ss.SSS"];
</code>```

Most likely, the cost is associated with both having to parse/validate the date format string and having to do any kind of locale specific goop that NSDateFormatter does.   Cocoa has extremely thorough support for localization, but that support comes at a cost of complexity.

Seeing as how you wrote a rather awesome example program, you could fire up your app in Instruments and try the various CPU sampling instruments to both understand what is consuming CPU cycles and how Instruments works (if you find anything interesting, please update your question!).

Can there be a blocking where the threads have to wait for each other?

I'm surprised it doesn't simply crash when you use a single formatter from multiple threads.  NSDateFormatter doesn't specifically mention that it is thread safe.   Thus, you must assume that it is not thread safe.

How can I improve the usage?

Don't create so many date formatters!

Either keep one around for a batch of operations and then get rid of it or, if you use 'em all the time, create one at the beginning of your app's run and keep around until the format changes.

For threading, keep one per thread around, if you really really have to (I'd bet that is excessive -- that the architecture of your app is such that creating one per batch of operations will be more sensible).

Body:
Note: Your example program is very much a micro-benchmark and very effectively maximally amplifies that cost of a date formatter.   You are comparing doing absolutely nothing with doing something.  Thus, whatever that something is, it will appear to be something times slower than nothing.

Such tests are extremely valuable and extremely misleading.   Micro-benchmarks are generally only useful when you have a real world case of Teh Slow.   If you were to make this benchmark 10x faster (which, in fact, you probably could with what I suggest below) but the real world case is only 1% of overall CPU time used in your app, the end result is not going to be a dramatic speed improvement -- it will be barely noticeable.

What is the reason for such costs?

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMdd HH:mm:ss.SSS"];

Most likely, the cost is associated with both having to parse/validate the date format string and having to do any kind of locale specific goop that NSDateFormatter does.   Cocoa has extremely thorough support for localization, but that support comes at a cost of complexity.

Seeing as how you wrote a rather awesome example program, you could fire up your app in Instruments and try the various CPU sampling instruments to both understand what is consuming CPU cycles and how Instruments works (if you find anything interesting, please update your question!).

Can there be a blocking where the threads have to wait for each other?

I'm surprised it doesn't simply crash when you use a single formatter from multiple threads.  NSDateFormatter doesn't specifically mention that it is thread safe.   Thus, you must assume that it is not thread safe.

How can I improve the usage?

Don't create so many date formatters!

Either keep one around for a batch of operations and then get rid of it or, if you use 'em all the time, create one at the beginning of your app's run and keep around until the format changes.

For threading, keep one per thread around, if you really really have to (I'd bet that is excessive -- that the architecture of your app is such that creating one per batch of operations will be more sensible).


问:
Silently POST a URL in PHP?
I need to trigger an alarm using a specific URL.
Alarm script should start/stop/start/off the alarm for 5 seconds. I don't want users to be redirected from the page.

This script should start/stop the alarm (using those special local host URL strings). Would this work?

?php

/* start alarm for 5 seconds */
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* note to user that alarm is on */
echo 'Alarm started...' "
";
echo date('h:i:s') . "
";

/* alarm off for 5 seconds */
sleep(5);
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

/* alarm on for 5 seconds */
echo date('h:i:s');
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* alarm off for 5 seconds */

echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

?>
```

<p>EDIT:</p>

<p>Sorry, I forgot to add that echo file_get_contents should load this whole XML thing which I don't want to printed on the page. </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>URL</key>
    <string>http://localhost/cgi-bin/controller.cgi?target=2&control=1</string>
</dict>
</plist>
</code>```

答:
As has already been mentioned the best option is to have JavaScript call the end points and handle the timeout. This is simply because calling it from PHP will under normal circumstances cause of delay greater than the sum of all your sleeps before anything in the html page is loaded. Any delay more than a few seconds before the page starts to render generally gas people assume the site is broken and leave or repeatedly hitting the reload button to try to make it work.

In other words, it's a bad UX experience.

Adm: BTW, you can assign the output of file_get_contents to a variable. You don't have to echo it.

Title: Silently POST a URL in PHP?

Body:
I need to trigger an alarm using a specific URL.
Alarm script should start/stop/start/off the alarm for 5 seconds. I don't want users to be redirected from the page.

This script should start/stop the alarm (using those special local host URL strings). Would this work?

?php

/* start alarm for 5 seconds */
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* note to user that alarm is on */
echo 'Alarm started...' "
";
echo date('h:i:s') . "
";

/* alarm off for 5 seconds */
sleep(5);
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

/* alarm on for 5 seconds */
echo date('h:i:s');
echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=1');

/* alarm off for 5 seconds */

echo file_get_contents('http://localhost/cgi-bin/controller.cgi?target=2&control=0');

?>

EDIT:

Sorry, I forgot to add that echo file_get_contents should load this whole XML thing which I don't want to printed on the page.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>URL</key>
    <string>http://localhost/cgi-bin/controller.cgi?target=2&control=1</string>
</dict>
</plist>


问:
Does it make sense to use a timestamp before saving or when saving to database
Question is pretty forward and it is bothering me for quite some time now. Perhaps any of you has an interesting view on this matter.

When creating an object lets say a memo.
This memo has a string (for the text obviously)
And a user id who has edited said text.

And this memo object is going to be saved to the database.

Is it common to add the current time to the object (eg. add a DateTime field / property) and save that object to db?

Or use the the current time of the database eg. when the row is inserted DateTime.Now in DB?

答: Considering that your application may run on multiple machines and users which may have different time zones or wrong time on their devices, the first option you proposed could affect data's integrity and you will end up with an unsuncronised database.</p>


问:
How to enlarge divs on top of other content on mouseover to reduce need to scroll overflow content? Am using Angular 2/4
I have 9 divs that are boxes. Each box includes data (used Some Text repeated over and over again in my example) that does not fit within the box itself. When I mouseover on top of any box, I want that box to "enlarge and be able to overlap other boxes" so that I can see more information without having to scroll. Animation is a plus. What would be a good way to accomplish this? Is it a directive or something else? The following is my code in vanilla html/css.

Pictures of what I am looking at before:

Pictures of the result after mouseover to animate to. Note that what is not shown is the box is bigger (due to bigger dimensions) that it shows more text content that may help to eliminate scrolling:

html,body {
  width:100%;
  height:100%;
}
table {
  border:1;
  width:100%;
  height:100%;

}
td {
  text-align:center;
  background:red;
  padding:  10px 0;
}

.scroll {
  overflow-y: auto;
  height: 100%;
  background:yellow;
}

.heading{
  height:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>

        <span class="heading">Box1</span>
        <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

    </td>
    <td>
      <span class="heading">Box2</span>
      <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>

       <span class="heading">Box2</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
  </tr>
  <tr>
    <td>

       <span class="heading">Box4</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
    <td>

       <span class="heading">Box5</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
    <td>

       <span class="heading">Box6</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
  </tr>
  <tr>
    <td>

       <span class="heading">Box7</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
    <td>

       <span class="heading">Box8</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
    <td>

       <span class="heading">Box9</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>

    </td>
  </tr>
</table></code>```

答:
I added an extra wrapper between the cell and the header/box to make it work with CSS only (one can do it without, but it gets much more complicated how to deal with the scaling, transition etc.).

Since when zoomed in, it cover the cells closest to itself, I added a delay on the transition, so one have time to re-position the cursor over the box of choice. Another option would be to scale it a little less, but I tried that and it didn't look so good, so I went with the delay version.

Would this be something you could use?

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}
* {
position: relative;
  box-sizing: border-box;
}
table {
  border: 1;
  width: 100%;
  height: 100%;
}
tr {
  height: 33.333%
}
td {
  position: relative;
  text-align: center;
  background: red;
  padding: 10px 0;
  height: 33.333%
}
td > div {
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: red;
}
.scroll {
  overflow-y: auto;
  height: calc(100% - 20px);
  background: yellow;
}
.heading {
  display: block;
  height: 20px;
}

tr:nth-child(1) td:nth-child(1) > div {
  transform-origin: left top;
}
tr:nth-child(1) td:nth-child(2) > div {
  transform-origin: center top;
}
tr:nth-child(1) td:nth-child(3) > div {
  transform-origin: right top;
}
tr:nth-child(2) td:nth-child(1) > div {
  transform-origin: left center;
}
tr:nth-child(2) td:nth-child(2) > div {
  transform-origin: center center;
}
tr:nth-child(2) td:nth-child(3) > div {
  transform-origin: right center;
}
tr:nth-child(3) td:nth-child(1) > div {
  transform-origin: left bottom;
}
tr:nth-child(3) td:nth-child(2) > div {
  transform-origin: center bottom;
}
tr:nth-child(3) td:nth-child(3) > div {
  transform-origin: right bottom;
}

td:hover {
  z-index: 1;
}
td > div {
  transition: transform .5s;
}
td:hover > div {
  transform: scale(2);
  transition: transform .5s .5s;
}
td:hover > div * {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
}
td:hover > div span {
  height: 10px;
}
td:hover > div div {
  height: calc(200% - 10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <div>
        <span class="heading">Box1</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>
        <span class="heading">Box2</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>
    </td>
    <td>
      <div>

        <span class="heading">Box3</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box4</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box5</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box6</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box7</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box8</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

      </div>
    </td>
    <td>

      <div>
        <span class="heading">Box9</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
</table></code>```

Based on a comment, here is an attempt to make the text not shrink prior to the zoom in.

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}
* {
position: relative;
  box-sizing: border-box;
}
table {
  border: 1;
  width: 100%;
  height: 100%;
}
tr {
  height: 33.333%
}
td {
  position: relative;
  text-align: center;
  background: red;
  padding: 10px 0;
  height: 33.333%
}
td > div {
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: red;
}
.scroll {
  overflow-y: auto;
  height: calc(100% - 20px);
  background: yellow;
}
.heading {
  display: block;
  height: 20px;
}

tr:nth-child(1) td:nth-child(1) > div {
  transform-origin: left top;
}
tr:nth-child(1) td:nth-child(2) > div {
  transform-origin: center top;
}
tr:nth-child(1) td:nth-child(3) > div {
  transform-origin: right top;
}
tr:nth-child(2) td:nth-child(1) > div {
  transform-origin: left center;
}
tr:nth-child(2) td:nth-child(2) > div {
  transform-origin: center center;
}
tr:nth-child(2) td:nth-child(3) > div {
  transform-origin: right center;
}
tr:nth-child(3) td:nth-child(1) > div {
  transform-origin: left bottom;
}
tr:nth-child(3) td:nth-child(2) > div {
  transform-origin: center bottom;
}
tr:nth-child(3) td:nth-child(3) > div {
  transform-origin: right bottom;
}

td:hover {
  z-index: 1;
}
td > div {
  transition: transform .5s;
}
td > div * {
  width: 100%;
}
td:hover > div {
  transform: scale(2);
  transition: transform .5s .5s;
}
td:hover > div * {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
  transition: transform 0s .5s, width 0s .5s, height 0s .5s;
}
td:hover > div span {
  height: 10px;
  color: white;
}
td:hover > div div {
  height: calc(200% - 10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <div>
        <span class="heading">Box1</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>
        <span class="heading">Box2</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>
    </td>
    <td>
      <div>

        <span class="heading">Box3</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box4</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box5</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box6</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box7</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box8</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

      </div>
    </td>
    <td>

      <div>
        <span class="heading">Box9</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
</table></code>```

Based on a second comment, one can also add a class-based CSS rule, and then by toggle that same class on a cell, manually trigger an animation.

Here is an update of the CSS rules to accomplish that

```<code>td.zoomin > div,
td:hover > div {
  transform: scale(2);
  transition: transform .5s .5s;
}
td.zoomin > div *,
td:hover > div * {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
  transition: transform 0s .5s, width 0s .5s, height 0s .5s;
}
td.zoomin > div span,
td:hover > div span {
  height: 10px;
  color: white;
}
td.zoomin > div div,
td:hover > div div {
  height: calc(200% - 10px);
}
</code>```

And something like this for the script

```<code>var box = document.querySelector("td:nth-child(2)");
box.classList.add("zoomin");
</code>```

Body:
I have 9 divs that are boxes. Each box includes data (used Some Text repeated over and over again in my example) that does not fit within the box itself. When I mouseover on top of any box, I want that box to "enlarge and be able to overlap other boxes" so that I can see more information without having to scroll. Animation is a plus. What would be a good way to accomplish this? Is it a directive or something else? The following is my code in vanilla html/css.

Pictures of what I am looking at before:

Pictures of the result after mouseover to animate to. Note that what is not shown is the box is bigger (due to bigger dimensions) that it shows more text content that may help to eliminate scrolling:

html,body {
  width:100%;
  height:100%;
}
table {
  border:1;
  width:100%;
  height:100%;

}
td {
  text-align:center;
  background:red;
  padding:  10px 0;
}

.scroll {
  overflow-y: auto;
  height: 100%;
  background:yellow;
}

.heading{
  height:20px;
}

        Box1

        Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

      Box2

        Some TExt
 Some TExt
 Some TExt
 Some TExt
Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box2

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box4

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box5

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box6

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box7

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box8

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

       Box9

Some TExt
 Some TExt
 Some TExt
 Some TExt
 Some TExt

Body:
I added an extra wrapper between the cell and the header/box to make it work with CSS only (one can do it without, but it gets much more complicated how to deal with the scaling, transition etc.).

Since when zoomed in, it cover the cells closest to itself, I added a delay on the transition, so one have time to re-position the cursor over the box of choice. Another option would be to scale it a little less, but I tried that and it didn't look so good, so I went with the delay version.

Would this be something you could use?

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}
* {
position: relative;
  box-sizing: border-box;
}
table {
  border: 1;
  width: 100%;
  height: 100%;
}
tr {
  height: 33.333%
}
td {
  position: relative;
  text-align: center;
  background: red;
  padding: 10px 0;
  height: 33.333%
}
td > div {
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: red;
}
.scroll {
  overflow-y: auto;
  height: calc(100% - 20px);
  background: yellow;
}
.heading {
  display: block;
  height: 20px;
}

tr:nth-child(1) td:nth-child(1) > div {
  transform-origin: left top;
}
tr:nth-child(1) td:nth-child(2) > div {
  transform-origin: center top;
}
tr:nth-child(1) td:nth-child(3) > div {
  transform-origin: right top;
}
tr:nth-child(2) td:nth-child(1) > div {
  transform-origin: left center;
}
tr:nth-child(2) td:nth-child(2) > div {
  transform-origin: center center;
}
tr:nth-child(2) td:nth-child(3) > div {
  transform-origin: right center;
}
tr:nth-child(3) td:nth-child(1) > div {
  transform-origin: left bottom;
}
tr:nth-child(3) td:nth-child(2) > div {
  transform-origin: center bottom;
}
tr:nth-child(3) td:nth-child(3) > div {
  transform-origin: right bottom;
}

td:hover {
  z-index: 1;
}
td > div {
  transition: transform .5s;
}
td:hover > div {
  transform: scale(2);
  transition: transform .5s .5s;
}
td:hover > div * {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
}
td:hover > div span {
  height: 10px;
}
td:hover > div div {
  height: calc(200% - 10px);
}

<table>
  <tr>
    <td>
      <div>
        <span class="heading">Box1</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>
        <span class="heading">Box2</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>
    </td>
    <td>
      <div>

        <span class="heading">Box3</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box4</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box5</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box6</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box7</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box8</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

      </div>
    </td>
    <td>

      <div>
        <span class="heading">Box9</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
</table>

Based on a comment, here is an attempt to make the text not shrink prior to the zoom in.

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}
* {
position: relative;
  box-sizing: border-box;
}
table {
  border: 1;
  width: 100%;
  height: 100%;
}
tr {
  height: 33.333%
}
td {
  position: relative;
  text-align: center;
  background: red;
  padding: 10px 0;
  height: 33.333%
}
td > div {
  position: absolute;
  left: 0; top: 0;
  width: 100%; height: 100%;
  background: red;
}
.scroll {
  overflow-y: auto;
  height: calc(100% - 20px);
  background: yellow;
}
.heading {
  display: block;
  height: 20px;
}

tr:nth-child(1) td:nth-child(1) > div {
  transform-origin: left top;
}
tr:nth-child(1) td:nth-child(2) > div {
  transform-origin: center top;
}
tr:nth-child(1) td:nth-child(3) > div {
  transform-origin: right top;
}
tr:nth-child(2) td:nth-child(1) > div {
  transform-origin: left center;
}
tr:nth-child(2) td:nth-child(2) > div {
  transform-origin: center center;
}
tr:nth-child(2) td:nth-child(3) > div {
  transform-origin: right center;
}
tr:nth-child(3) td:nth-child(1) > div {
  transform-origin: left bottom;
}
tr:nth-child(3) td:nth-child(2) > div {
  transform-origin: center bottom;
}
tr:nth-child(3) td:nth-child(3) > div {
  transform-origin: right bottom;
}

td:hover {
  z-index: 1;
}
td > div {
  transition: transform .5s;
}
td > div * {
  width: 100%;
}
td:hover > div {
  transform: scale(2);
  transition: transform .5s .5s;
}
td:hover > div * {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
  transition: transform 0s .5s, width 0s .5s, height 0s .5s;
}
td:hover > div span {
  height: 10px;
  color: white;
}
td:hover > div div {
  height: calc(200% - 10px);
}

<table>
  <tr>
    <td>
      <div>
        <span class="heading">Box1</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>
        <span class="heading">Box2</span>
        <div class="scroll">
          Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>
    </td>
    <td>
      <div>

        <span class="heading">Box3</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box4</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box5</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box6</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
  <tr>
    <td>
      <div>

        <span class="heading">Box7</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
    <td>
      <div>

        <span class="heading">Box8</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>

      </div>
    </td>
    <td>

      <div>
        <span class="heading">Box9</span>
        <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
      </div>

    </td>
  </tr>
</table>

Based on a second comment, one can also add a class-based CSS rule, and then by toggle that same class on a cell, manually trigger an animation.

Here is an update of the CSS rules to accomplish that

td.zoomin > div,
td:hover > div {
  transform: scale(2);
  transition: transform .5s .5s;
}
td.zoomin > div *,
td:hover > div * {
  transform: scale(0.5);
  transform-origin: left top;
  width: 200%;
  transition: transform 0s .5s, width 0s .5s, height 0s .5s;
}
td.zoomin > div span,
td:hover > div span {
  height: 10px;
  color: white;
}
td.zoomin > div div,
td:hover > div div {
  height: calc(200% - 10px);
}

And something like this for the script

var box = document.querySelector("td:nth-child(2)");
box.classList.add("zoomin");


问:
Javascript synchronous loop in browser
Trying to automate a task in the browser with Greasemonkey.

Requirement: load a web page which contains a table displaying 15 out of 340+ results, with button controls to see the next page worth of results, go back, go to the end and so forth.

Collect the first 15 results --> got this working

Click on the 'Next' button  --> got this working

Wait until the page loads the next set of results --> dont know how

Repeat until the next button is disabled --> got this working

Cant show pictures cuz its a corporate app.

So far if I loop with setTimeouts, the timeouts get queued up and executed at the same time I think. Instead, the requirement is for the code to run the info collection, click next, wait, then collect info again.

答:
You could try a utility function waitForKeyElement, a greasemonkey utility script.  It is essentially doing what you were trying to do before. It sets a timeout to continuously checks to see if an element is loaded. Executing it would look something like this:

```<code>waitForKeyElements (
     "div.comments",
     commentCallbackFunction
);
</code>```

Where comment callback function would be the function that collects results.

It would help also to understand why setTimeout in a loop doesn't work.  setTimeout does not block execution of a script to run your callback function.  It queues up that function to be executed no earlier than the time that you pass in as a second parameter.  Because of this, the loop runs very quickly and instead of getting function calls at 3000ms, 6000ms, and 9000ms... as you might expect you get something closer to function calls at 3000ms, 3001ms, 3002ms.

Title: Javascript synchronous loop in browser

Body:
You could try a utility function waitForKeyElement, a greasemonkey utility script.  It is essentially doing what you were trying to do before. It sets a timeout to continuously checks to see if an element is loaded. Executing it would look something like this:

waitForKeyElements (
     "div.comments",
     commentCallbackFunction
);

Where comment callback function would be the function that collects results.

It would help also to understand why setTimeout in a loop doesn't work.  setTimeout does not block execution of a script to run your callback function.  It queues up that function to be executed no earlier than the time that you pass in as a second parameter.  Because of this, the loop runs very quickly and instead of getting function calls at 3000ms, 6000ms, and 9000ms... as you might expect you get something closer to function calls at 3000ms, 3001ms, 3002ms.