Tuesday 31 October 2017

html - Closing empty tags: XHTML5 or HTML5? Why one over the other?

After reading extensively about HTML5 and XHTML5 and after
reading this post: href="https://stackoverflow.com/questions/3558119/are-non-void-self-closing-tags-valid-in-html5?rq=1">Are
(non-void) self-closing tags valid in HTML5? , I have got a very simple
question:



"Is there a reason why it would be
good to serialise HTML5 as XML?"



I
understand:




  • the
    differences between HTML, XHTML, XML and HTML5

  • that it's
    good practice to nest elements correctly, use lower case letters, quote attributes,
    close tags etc...

  • that HTML5 has no DTD while XHTML has
    got a DTD and an XML parse


  • that if I specify a
    page as XHTML5 (HTML5 doctype + XHTML schema) some browsers might not process the page
    for minor errors
    etc...



So the question
is:



"In which case would it be good to follow
very strict XML rules when doing an HTML5
page?"



Above all when it comes to things
like



1) The void
elements




            src="asdsad.jpg" /> compared with 

compared with
comparted with



2)
Checked, download etc..
like



            name="vehicle" value="Car" checked> VS
name="vehicle" value="Car" checked="checked"
/>



Should
I just write following the HTML5 standard and implement as much common sense as possible
(lower case, good nesting) or is there A GOOD REASON for a standard company website to
be coded in XHTML5?

What is the EAFP principle in Python?

I'll try to explain it with another
example.




Here we're trying to access
the file and print the contents in console.



LBYL - Look Before You Leap
:



We might want to check if we can access the
file and if we can, we'll open it and print the contents. If we can't access the file
we'll hit the else part. The reason that this is a race
condition is because we first make an access-check. By the time we reach
with open(my_file) as f: maybe we can't access it anymore due
to some permission issues (for example another process gains an exclusive file lock).
This code will likely throw an error and we won't be able to catch that error because we
thought that we could access the
file.



import
os

my_file =
"/path/to/my/file.txt"


# Race condition
if
os.access(my_file, os.R_OK):
with open(my_file) as f:

print(f.read())
else:
print("File can't be
accessed")


EAFP -
Easier to Ask for Forgiveness than Permission
:




In this example, we're just trying
to open the file and if we can't open it, it'll throw an
IOError. If we can, we'll open the file and print the contents.
So instead of asking something we're trying to
do it. If it works, great! If it doesn't we catch the error and handle
it.



# # No race
condition
try:
f = open(my_file)
except IOError as
e:
print("File can't be accessed")
else:
with
f:


print(f.read())

plot explanation - What did David say to the engineer in Prometheus?

In href="http://www.imdb.com/title/tt1446714/">Prometheus, when the android
David is talking with the Engineer, first he stumbles a bit and stays crouched, then
they are all asking him questions and David seems to translate it. Then they all stand
up, the Engineer strokes his chair and snaps.


My question
is, did the Engineer destroy David and go on a rampage because of what he said, or did
he have another reason for that? If so, What did David say to the
Engineer?


itemprop="text">
class="normal">Answer


Edit:
Now we know. In an interview revealed at Total Film with Dr. Anil
Biltoo:



Well,
according to Dr. Anil Biltoo, the film’s official translator and linguistics consultant,
David did as he was asked, translating his words as follows: “This man is here because
he does not want to die. He believes you can give him more
life.”



The rest
of the text of this article stands unedited except for the interview inserts, in
italics.


We are forced to reconcile the
reaction of the Engineer
with:



  • His/it's original mission, to
    destroy the Earth.

  • His/it's momentary pause as it
    analyzes the situation upon awakening

  • His/it's decision
    to kill the team and continue its primary
    mission.




Does David betray his creator? His pathological hatred of all of humanity is
obvious to us, but not necessarily to them. Would he use the opportunity to ask a
different question than he was asked or would he comply out of duty (or programming). My
suspicion is David asked exactly what he was told by Weyland. Not that it
mattered, the Engineer answered only with his actions to kill the
team.



My
supposition still stands and is supported in the rest of the Total Film interview
review:




So there we have it. David wasn’t up to anything sinister, it just
turned out that the Engineer wasn’t best pleased to be interrupted by a member of the
species he was charged with destroying. Apparently, the scene was initially written to
involve a much longer conversation, so perhaps more details will emerge in the deleted
material on the DVD. Or even in a
sequel...



Why
wouldn't David say what he had been asked to? He is not concerned with the question or
the answer. For him, it is academic at best. He has already made his decision about
humanity and given the information he has up to that point, he assumes the Engineers
already have their own less than stellar opinion of humanity as
well.



However, given the
purported intelligence of the Engineers, and a time-table of their last visit
(approximately 2,000 years ago, during a very warlike period on Earth) once he saw how
violent, humanity had remained, he realized he would have to complete his mission. He
did not seem conflicted in any way.



My suspicion was he
recognized what David was and could extrapolate how long he had been asleep, which may
have given him greater motivation to deliver his payload, fearing a galactic outbreak of
this violent species. The Engineer did not seem surprised to see us, likely as a
diminutive and less impressive form of
itself.



I had the impression
the Engineer did not fear humanity, so much as their lack of individual control. He was
privy to, in a matter of seconds, hierarchical dominance behavior, aggression, anger,
and directed violence. From the aspect of a species that creates life, certainly an
undesirable outcome. Perhaps the same reaction we might have if a beloved pet suddenly
attacked us. We would put it down, for its own good. The Engineer maintained a
surprising level of apparent emotional control during his attack on the team and his
subsequent launching of his ship. He did not appear to have any issues with completing
his mission, so his belief in the necessity was apparent in his actions.



I would also have to credit
this Engineer with some degree of forethought. He was the only one on this ship to make
it back to stasis and secure himself before the pathogen was able to reach him. I
suspect he thought it would be safer to be in stasis than dying in the
halls.



David's experience of
humanity soured him on meeting the Engineers and even though he was intellectually
curious about their technology, he showed no real interest in the Engineers, themselves,
likely considering them as potentially dangerous as he considered mankind. Maybe moreso,
since humanity was based on their DNA. If he did give the Engineer an account of what
happened or how they came to be here, rather than Wayland's requested information, I am
certain, he was surprised with his/it's reaction. It was certainly not an expected
outcome from David's perspective.




java - Constructors with default values of parameters

No it doesn't. Java doesn't support default arguments in
any function; constructors
included.


What you can do though is
define public Shape(int v, int e) and also a default
constructor


public
Shape()
{
this(1,
2);
}

Note the special
syntax here to delegate the construction to the two-argument
constructor.

javascript - How to check if jQuery object exist in array?

itemprop="text">

Given an item
and an array, I would like to know if
item exist in
array.




item
is a jQuery object, e.g. $(".c"). You can assume that
item.length ==
1
.



array
is an array of jQuery objects, e.g. [$(".a"), $(".b")]. Each
item in this array may represent 0, 1, or more
objects.



Here is how I thought to implement
this: (live demo
here
)



function
inArray(item, arr) {
for (var i = 0; i < arr.length; i++) {
var
items = $.makeArray(arr[i]);


for (var k = 0; k <
items.length; k++) {
if (items[k] == item[0]) {
return
true;
}
}
}

return
false;
}



Can
you find a more elegant implementation?



/>

Example:



HTML:




            class="a">Hello

class="a">Stack

class="a">Overflow


class="b">Have

class="b">a

class="b">nice

class="b">day!


Bye
bye




JS:



console.log(inArray($(".a").eq(2),
[$(".a"), $(".b")])); // true
console.log(inArray($(".b").eq(3), [$(".a"),
$(".b")])); // true
console.log(inArray($(".c"), [$(".a"), $(".b")])); //
false
console.log(inArray($(".a").eq(2), [$(".b")])); //
false
console.log(inArray($(".a").eq(2), [])); //
false
console.log(inArray($(".c"), [$("div")])); //
true


class="post-text" itemprop="text">
class="normal">Answer



According
to Felix's
suggestion:



[$(selector1),
$(selector2), ... ]
can be simplified to



$(selector1, selector2,
...)


or




$(selector1).add(selector2)...


and
then it can be implemented
as:



function inArray(item, arr)
{
return (arr.index(item) !=
-1);
}



href="http://jsfiddle.net/e3WwB/3/">Live demo here



html - utf-8 characters not displaying in chrome

Having an issue with html special characters not
displaying correctly in chrome see



href="http://sandbox.dev.activemls.com/agent/" rel="nofollow">Example
Page




I have gone through
and resaved every file in the project as utf-8 confirmed my meta tag deceleration and
confirmed that chrome is set to default to utf-8. No issues in firefox or ie. Any help
would be greatly appreciated. Im pulling my hair out.

fluid dynamics - Can cannonballs go through water? - Physics

itemprop="text">

In the recent Spielberg/Jackson Tintin
movie, there is a scene where Red Rackham and Captain Haddock's ships are fighting, and
cannons are fired. The cannonball is shown at one point to go through a wave, and
inflict serious damage on the other ship. I know that bullets stop in water; do
cannonballs, with their greater weight, continue with enough force to inflict damage?


style="font-weight: bold;">

Answer




What distance can a cannonball traverse thru
water without losing too much kinetic energy? For a back-of-the-envelope calculation we
start from the observation that this distance scales with the ratio of the kinetic
energy of the cannonball and the drag force exerted on the cannonball.



Let's denote the ball's radius by $R$, its
speed by $v$, and its mass density by $\rho_{ball}$. The kinetic energy $E_k$ equals
$\frac 1 2 M v^2 = \frac{2 \pi}{3} \rho_{ball} R^3 v^2$.




The drag force $F_d$ is given by
$\frac 1 2 C_d \rho_{water} v^2 A = \frac {\pi}{2} C_d \rho_{water} v^2 R^2$. Here,
$C_d$ denotes the drag coefficient for a sphere.



The maximum distance $L _{max}$ that can be
traversed by a cannonball $L_{max} = E_k/F_d$ is therefore $\frac 4 3 \frac {R}{C_d}
\frac {\rho_{ball}}{\rho_{water}}$. For typical values (
$\frac{\rho_{ball}}{\rho_{water}} < 8$ and $C_d > 0.1$, see href="http://www.grc.nasa.gov/WWW/k-12/airplane/dragsphere.html">here), we
find $L_{max} < 100 R$.



In other words, a
cannonball loses much of its kinetic energy when it traverses a layer of water larger
than about fifty times its diameter.


yii bootstrap + widget TbButtonColumn + widget TbButtonGroup

itemprop="text">



Faced with such
a problem:



Table is formed by the widget
TbGridView from bootstrap (from yii-booster). In the column TbButtonColumn I form the
"edit / delete, etc."




But one button
I want to do with the effect of Split dropdowns
href="http://yii-booster.clevertech.biz/components.html#buttonDropdowns">http://yii-booster.clevertech.biz/components.html#buttonDropdowns



$this->widget('bootstrap.widgets.TbGridView',
array(
'id'=>'customer-grid',
'type'=>'striped bordered
condensed',
'dataProvider'=>$model->search(),

'filter'=>$model,
'columns'=>array(

'surname',

'name',
'middlename',

'dateOfBirth',
array(

'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>'{add} {list}
{update} {print_act}',
'buttons'=>array
(
'add'
=> array
(

'label'=>'Назначить прием',

'icon'=>'plus',
'url'=>'Yii::app()->createUrl("reception/create",
array("id"=>$data->id))',
'options'=>array(

'class'=>'btn btn-small',
),
),
'list' =>
array
(
'label'=>'Список предоставленных
услуг',

'icon'=>'list white',

'url'=>'Yii::app()->createUrl("patient/update",
array("id"=>$data->id))',
'options'=>array(

'class'=>'btn btn-small btn-info',
),
),
'update'
=> array
(
'label'=>'Изменить данные Пациента',

'icon'=>'pencil white',


'url'=>'Yii::app()->createUrl("customer/update",
array("id"=>$data->id))',
'options'=>array(

'class'=>'btn btn-small btn-success',
),
),

'print_act' => array
(
'label'=>'Печать акта выполненных
работ',
'icon'=>'print',

'url'=>'Yii::app()->createUrl("customer/printAct",
array("id"=>$data->id))',

'options'=>array(

'class'=>'btn btn-small',
),
),
),

'htmlOptions'=>array(
'style'=>'width: 220px',
),

)
),

));


Answer




I've always found that when I need to render
a complex element in a gridview (especially a widget) it's easier if you call a function
from the controller. For example your gridview would have columns that are defined like
this:



'columns'=>array(

'surname',
'name',
'middlename',

'dateOfBirth'

...
array(

'name'=>'fieldName',
//call the function 'renderButtons' from the current
controller
'value'=>array($this,'renderButtons'),
),

)


And then in your
action would look something like this. This just renders the example widget from
Yii-booster example page href="http://yii-booster.clevertech.biz/components.html#buttonDropdowns"
rel="nofollow">http://yii-booster.clevertech.biz/components.html#buttonDropdowns:




Edit:
This is also helpful because of the callback function renderButtons() accepts 2
parameters: $data and $row. You can use $data to access data from the gridview's data
provider in order to dynamically render a
widget.



public function
renderButtons($data, $row) {

$this->widget('bootstrap.widgets.TbButtonGroup', array(

'size'=>'large',
'type'=>'inverse', // '', 'primary', 'info',
'success', 'warning', 'danger' or 'inverse'
'buttons'=>array(

array('label'=>'Inverse', 'items'=>array(
array('label'=>'Action',
'url'=>'#'),

array('label'=>'Another action',
'url'=>'#'),
array('label'=>'Something else',
'url'=>'#'),
'---',
array('label'=>'Separate link',
'url'=>'#'),
)),
),

));
}


identify this movie - Sci-fi film: American teen science project brings people and dinosaurs into present - Movies & TV

itemprop="text">




I'm
hoping someone can help me identify the following film that I would have seen in the
early 90's or late 80's. It is a film in the era of Weird Science, Flight of the
Navigator and Explorers.



All I really remember
is that some American teens build a science project which seems to be able to control
time or manipulate time. Different characters from different time periods are brought
into their own.




One scene I remember
which I think is towards the end of the film involves the teens going into their school
or university to where this device is located. When they get to the main hall the area
has been transformed into a Jurassic jungle environment complete with
dinosaurs.



One other very random clip I remember
is a scene whereby a bunch of Hells Angels style bikers arrive or are summoned by this
device ( I'm hoping this isn't bleed-through from another
film...)



Any ideas?



Answer




href="http://en.wikipedia.org/wiki/My_Science_Project">My Science
Project

(1985)






... After Michael and his friends plug it into a power source, it

begins to materialize objects from other times and dimensions.




When
his science teacher (Dennis Hopper) experiments by
plugging the orb
directly into the power grid, it starts a chain reaction
that warp the
dimensions and time around it. Past, present and future collide
in a
whirling vortex which engulfs the school and only Michael and
his
friends can stop
it.





/> href="http://www.youtube.com/watch?v=JkylDvmZl_c&list=UUZd7jt0Vc_gq1p36FJLy0Ug">From
a YouTube clip:





alt="Dinosaur">




Why the final keyword can make strings equal in java

public class Test
{

public static void main(String[] args) {
String a =
"hello2";
final String b = "hello";
String d =
"hello";
String c = b + 2;
String e = d + 2;

System.out.println((a == c));
System.out.println((a ==
e));
}



The
result is True and False.
Does "==" not mean that the string address is
equal?
I think the result is False Fasle

c - Can x86's MOV really be "free"? Why can't I reproduce this at all?

itemprop="text">

I keep seeing people claim that the
MOV instruction can be free in x86, because of register renaming.



For the life of me, I can't verify this in a
single test case. Every test case I try debunks
it.



For example, here's the code I'm compiling
with Visual
C++:




#include

#include
#include


int main(void)
{
unsigned int
k, l, j;
clock_t tstart = clock();
for (k = 0, j = 0, l = 0; j
< UINT_MAX; ++j)
{

++k;
k = j; // <--
comment out this line to remove the MOV instruction
l += j;

}
fprintf(stderr, "%d ms\n", (int)((clock() - tstart) * 1000 /
CLOCKS_PER_SEC));
fflush(stderr);
return (int)(k + j +
l);
}



This
produces the following assembly code for the loop (feel free to produce this however you
want; you obviously don't need Visual
C++):



LOOP:
add
edi,esi
mov ebx,esi
inc esi
cmp
esi,FFFFFFFFh
jc
LOOP



Now I
run this program several times, and I observe a pretty consistent 2% difference when the
MOV instruction is
removed:



Without MOV With
MOV
1303 ms 1358 ms
1324 ms 1363 ms
1310 ms 1345
ms
1304 ms 1343 ms
1309 ms 1334 ms
1312 ms 1336
ms
1320 ms 1311 ms

1302 ms 1350 ms
1319 ms
1339 ms
1324 ms 1338
ms


So what gives? Why
isn't the MOV "free"? Is this loop too complicated for x86?
Is there a
single example out there that can demonstrate MOV being free like
people claim?
If so, what is it? And if not, why does everyone keep claiming
MOV is free?


itemprop="text">
class="normal">Answer




The throughput of the loop in
the question doesn't depend on the latency of MOV, or (on Haswell)
the benefit of not using an execution
unit.



The loop is still only 4
uops for the front-end to issue into the out-of-order core.
(mov still has to be tracked by the out-of-order core even if
it doesn't need an execution unit, but cmp/jc macro-fuses into
a single uop).




Intel CPUs since Core2
have had an issue width of 4 uops per clock, so the mov doesn't
stop it from executing at (close to) one iter per clock on Haswell. It would also run at
one per clock on Ivybridge (with mov-elimination), but not on
Sandybridge (no mov-elimination). On SnB, it would be about one iter per
1.333c cycles, bottlenecked on ALU throughput because the mov
would always need one
. (SnB/IvB have only three ALU ports, while Haswell
has four).



Note that special handling in the
rename stage has been a thing for x87 FXCHG (swap st0 with
st1) for much longer than MOV. Agner Fog lists FXCHG as 0
latency on PPro/PII/PIII (first-gen P6 core).



/>

The loop in the question has two interlocking
dependency chains (the add edi,esi depends on EDI and on the
loop counter ESI), which makes it more sensitive to imperfect scheduling. A 2% slowdown
vs. theoretical prediction because of seemingly-unrelated instructions isn't unusual,
and small variations in order of instructions can make this kind of difference. To run
at exactly 1c per iter, every cycle needs to run an INC and an ADD. Since all the INCs
and ADDs are dependent on the previous iteration, out-of-order execution can't catch up
by running two in a single cycle. Even worse, the ADD depends on the INC in the previous
cycle, which is what I meant by "interlocking", so losing a cycle in the INC dep chain
also stalls the ADD dep chain.



Also,
predicted-taken branches can only run on port6, so any cycle where port6
doesn't executed a cmp/jc is a cycle of lost throughput
. This happens
every time an INC or ADD steals a cycle on port6 instead of running on ports 0, 1, or 5.
IDK if this is the culprit, or if losing cycles in the INC/ADD dep chains themselves is
the problem, or maybe some of
both.




Adding the extra
MOV doesn't add any execution-port pressure, assuming it's eliminated 100%, but it does
stop the front-end from running ahead of the execution core
. (Only 3 of
the 4 uops in the loop need an execution unit, and your Haswell CPU can run INC and ADD
on any of its 4 ALU ports: 0, 1, 5, and 6. So the bottlenecks are:




  • the front-end max
    throughput of 4 uops per clock. (The loop without MOV is only 3 uops, so the front-end
    can run ahead).

  • taken-branch throughput of one per
    clock.

  • the dependency chain involving
    esi (INC latency of 1 per
    clock)

  • the dependency chain involving
    edi (ADD latency of 1 per clock, and also dependent on the INC
    from the previous
    iteration)




Without
the MOV, the front-end can issue the loop's three uops at 4 per clock until the
out-of-order core is full. (AFAICT, href="https://stackoverflow.com/questions/39311872/is-performance-reduced-when-executing-loops-whose-uop-count-is-not-a-multiple-of">it
"unrolls" tiny loops in the loop-buffer (Loop Stream Detector: LSD), so a loop with ABC
uops can issue in an ABCA BCAB CABC ... pattern. The perf counter for
lsd.cycles_4_uops confirms that it mostly issues in groups of 4
when it issues any uops.)



href="https://stackoverflow.com/questions/40681331/how-are-x86-uops-scheduled-exactly">Intel
CPUs assign uops to ports as they issue into the out-of-order core. The
decision is based on counters that track how many uops for each port are already in the
scheduler (aka Reservation Station, RS). When there are lots of uops in the RS waiting
to execute, this works well and should usually avoid scheduling INC or ADD to port6. And
I guess also avoids scheduling the INC and ADD such that time is lost from either of
those dep chains. But if the RS is empty or nearly-empty, the counters won't stop an ADD
or INC from stealing a cycle on port6.



I thought
I was onto something here, but any sub-optimal scheduling should let the front-end catch
up and keep the back-end full. I don't think we should expect the front-end to cause
enough bubbles in the pipeline to explain a 2% drop below max throughput, since the tiny
loop should run from the loop buffer at a very consistent 4 per clock throughput. Maybe
there's something else going on.



/>




I used
lea to construct a loop that only has one
mov per clock, creating a perfect demonstration where
MOV-elimination succeeds 100%, or 0% of the time with mov
same,same
to demonstrate the latency bottleneck that
produces.



Since the macro-fused
dec/jnz is part of the dependency chain
involving the loop counter, imperfect scheduling can't delay it.
This is
different from the case where cmp/jc "forks off" from the
critical-path dependency chain every
iteration.



_start:
mov
ecx, 2000000000 ; each iteration decrements by 2, so this is 1G iters
align 16
; really align 32 makes more sense in case the uop-cache comes into play, but alignment
is actually irrelevant for loops that fit in the loop
buffer.
.loop:
mov eax, ecx
lea ecx, [rax-1] ; we vary
these two instructions


dec ecx ; dec/jnz macro-fuses
into one uop in the decoders, on Intel
jnz
.loop

.end:
xor edi,edi ; edi=0
mov eax,231 ;
__NR_exit_group from /usr/include/asm/unistd_64.h
syscall ;
sys_exit_group(0)



On
Intel SnB-family, LEA with one or two components in the addressing mode runs with 1c
latency (See rel="noreferrer">http://agner.org/optimize/, and other links in the href="https://stackoverflow.com/questions/tagged/x86" class="post-tag" title="show
questions tagged 'x86'" rel="tag">x86 tag
wiki).



I built and ran this as a static binary
on Linux, so user-space perf-counters for the whole process are measuring just the loop
with negligible startup / shutdown overhead. (perf stat is
really easy compared to putting perf-counter queries into the program
itself)



$ yasm -felf64
-Worphan-labels -gdwarf2 mov-elimination.asm && ld -o mov-elimination
mov-elimination.o &&
objdump -Mintel -drwC mov-elimination
&&
taskset -c 1 ocperf.py stat
-etask-clock,context-switches,page-faults,cycles,instructions,branches,uops_issued.any,uops_executed.thread
-r2 ./mov-elimination

Disassembly of section
.text:


00000000004000b0 <_start>:

4000b0: b9 00 94 35 77 mov ecx,0x77359400
4000b5: 66 66 2e 0f 1f 84 00 00 00
00 00 data16 nop WORD PTR cs:[rax+rax*1+0x0]

00000000004000c0
<_start.loop>:
4000c0: 89 c8 mov eax,ecx
4000c2: 8d 48 ff
lea ecx,[rax-0x1]
4000c5: ff c9 dec ecx
4000c7: 75 f7 jne 4000c0
<_start.loop>


00000000004000c9
<_start.end>:
4000c9: 31 ff xor edi,edi
4000cb: b8 e7 00 00
00 mov eax,0xe7
4000d0: 0f 05 syscall

perf stat
-etask-clock,context-switches,page-faults,cycles,instructions,branches,cpu/event=0xe,umask=0x1,name=uops_issued_any/,cpu/event=0xb1,umask=0x1,name=uops_executed_thread/
-r2 ./mov-elimination

Performance counter stats for
'./mov-elimination' (2 runs):

513.242841 task-clock:u (msec) #
1.000 CPUs utilized ( +- 0.05% )

0 context-switches:u # 0.000
K/sec
1 page-faults:u # 0.002 K/sec
2,000,111,934 cycles:u #
3.897 GHz ( +- 0.00% )
4,000,000,161 instructions:u # 2.00 insn per cycle (
+- 0.00% )
1,000,000,157 branches:u # 1948.396 M/sec ( +- 0.00% )

3,000,058,589 uops_issued_any:u # 5845.300 M/sec ( +- 0.00% )
2,000,037,900
uops_executed_thread:u # 3896.865 M/sec ( +- 0.00% )

0.513402352
seconds time elapsed ( +- 0.05%
)



As
expected, the loop runs 1G times (branches ~= 1 billion). The
"extra" 111k cycles beyond 2G is overhead that's present in the other tests, too,
including the one with no mov. It's not from occasional failure
of mov-elimination, but it does scale with the iteration count so it's not just startup
overhead. It's probably from timer interrupts, since IIRC Linux
perf doesn't mess around with perf-counters while handling
interrupts, and just lets them keep counting. (perf virtualizes
the hardware performance counters so you can get per-process counts even when a thread
migrates across CPUs.) Also, timer interrupts on the sibling logical core that shares
the same physical core will perturb things a
bit.



The bottleneck is the loop-carried
dependency chain involving the loop counter. 2G cycles for 1G iters is 2 clocks per
iteration, or 1 clock per decrement. The confirms that the length of the dep chain is 2
cycles. This is only possible if mov has zero
latency
. (I know it doesn't prove that there isn't some other bottleneck.
It really only proves that the latency is at
most
2 cycles, if you don't believe my assertion that latency is the only
bottleneck. There's a resource_stalls.any perf counter, but it
doesn't have many options for breaking down which microarchitectural resource was
exhausted.)



The loop has 3 fused-domain uops:
mov, lea, and href="https://stackoverflow.com/questions/31771526/x86-64-assembly-loop-conditions-and-out-of-order/31778403#31778403">macro-fused
dec/jnz. The 3G
uops_issued.any count confirms that: It counts in the fused
domain, which is all of the pipeline from decoders to retirement, except for the
scheduler (RS) and execution units. (macro-fused instruction-pairs stay as single uop
everywhere. It's only for micro-fusion of stores or ALU+load that 1 fused-domain uop in
the
ROB
tracks the progress of two unfused-domain
uops.)



2G
uops_executed.thread (unfused-domain) tells us that all the
mov uops were eliminated (i.e. handled by the issue/rename
stage, and placed in the ROB in an already-executed state). They still take up
issue/retire bandwidth, and space in the uop cache, and code-size. They take up space in
the ROB, limiting out-of-order window size. A mov
instruction is never free. There are many possible microarchitectural bottlenecks
besides latency and execution ports, the most important usually being the 4-wide issue
rate of the front-end.



On Intel
CPUs, being zero latency is often a bigger deal than not needing an execution unit,
especially in Haswell and later where there are 4 ALU ports. (But only 3 of them can
handle vector uops, so non-eliminated vector moves would be a bottleneck more easily,
especially in code without many loads or stores taking front-end bandwidth (4
fused-domain uops per clock) away from ALU uops. Also, scheduling uops to execution
units isn't perfect (more like oldest-ready first), so uops that aren't on the critical
path can steal cycles from the critical
path.)




If we put a
nop or an xor edx,edx into the loop,
those would also issue but not execute on Intel SnB-family
CPUs.



Zero-latency mov-elimination can be useful
for zero-extending from 32 to 64 bits, and for 8 to 64. ( href="https://stackoverflow.com/questions/45660139/how-exactly-do-partial-registers-on-haswell-skylake-perform-writing-al-seems-to">movzx
eax, bl
is eliminated, movzx eax, bx
isn't).



/>

Without
mov-elimination



All current CPUs
that support mov-elimination don't support it for mov
same,same
, so pick different registers for zero-extending
integers from 32 to 64-bit, or vmovdqa xmm,xmm to zero-extend
to YMM in a rare case where that's necessary. (Unless you need the
result in the register it's already in. Bouncing to a different reg and back is normally
worse.) And on Intel, the same applies for movzx eax,al for
example. (AMD Ryzen doesn't mov-eliminated movzx.) Agner Fog's instruction tables show
mov as always being eliminated on Ryzen,
but I guess he means that it can't fail between two different regs the way it can on
Intel.




We can use this limitation to
create a micro-benchmark that defeats it on
purpose.



mov ecx, ecx # CPUs can't
eliminate mov same,same
lea ecx, [rcx-1]

dec
ecx
jnz .loop

3,000,320,972 cycles:u # 3.898 GHz ( +-
0.00% )

4,000,000,238 instructions:u # 1.33 insn per cycle ( +-
0.00% )
1,000,000,234 branches:u # 1299.225 M/sec ( +- 0.00% )

3,000,084,446 uops_issued_any:u # 3897.783 M/sec ( +- 0.00% )
3,000,058,661
uops_executed_thread:u # 3897.750 M/sec ( +- 0.00%
)


This
takes 3G cycles for 1G iterations, because the length of the dependency chain is now 3
cycles.



The fused-domain uop
count didn't change, still 3G.




What
did change is that now the unfused-domain uop count is the same as fused-domain. All the
uops needed an execution unit; none of the mov instructions
were eliminated, so they all added 1c latency to the loop-carried dep
chain.



(When there are micro-fused uops, like
add eax, [rsi], the uops_executed
count can be higher than uops_issued. But
we don't have that.)



/>

Without the mov at
all:



lea ecx,
[rcx-1]


dec ecx
jnz
.loop


2,000,131,323 cycles:u # 3.896 GHz ( +- 0.00%
)
3,000,000,161 instructions:u # 1.50 insn per cycle

1,000,000,157 branches:u # 1947.876 M/sec
2,000,055,428 uops_issued_any:u #
3895.859 M/sec ( +- 0.00% )
2,000,039,061 uops_executed_thread:u # 3895.828
M/sec ( +- 0.00%
)



Now we're
back down to 2 cycle latency for the loop-carried dep
chain.



Nothing is
eliminated.






I
tested on a 3.9GHz i7-6700k Skylake. I get identical results on a Haswell i5-4210U (to
within 40k out of 1G counts) for all the perf events. That's about the same margin of
error as re-running on the same system.



Note
that if I ran perf as root1, and counted
cycles instead of cycles:u (user-space
only), it measure the CPU frequency as exactly 3.900 GHz. (IDK why Linux only obeys the
bios-settings for max turbo right after reboot, but then drops to 3.9GHz if I leave it
idle for a couple minutes. Asus Z170 Pro Gaming mobo, Arch Linux with kernel
4.10.11-1-ARCH. Saw the same thing with Ubuntu. Writing
balance_performance to each of
/sys/devices/system/cpu/cpufreq/policy[0-9]*/energy_performance_preference
from /etc/rc.local fixes it, but writing
balance_power makes it drop back to 3.9GHz again
later.)




1: update: as a better
alternative to running sudo perf, I set sysctl
kernel.perf_event_paranoid = 0 in
/etc/syctl.d/99-local.conf



/>

You should get the same results on AMD Ryzen, since
it can eliminate integer mov. AMD Bulldozer-family can only
eliminate xmm register copies. (According to Agner Fog, ymm
register copies are an eliminated low-half and an ALU op for the high
half.)



For example, AMD Bulldozer and Intel
Ivybridge can sustain a throughput of 1 per clock
for



 movaps xmm0,
xmm1

movaps xmm2, xmm3
movaps xmm4, xmm5

dec
jnz
.loop


But Intel
Sandybridge can't eliminate moves, so it would bottleneck on 4 ALU uops for 3 execution
ports. If it was pxor xmm0,xmm0 instead of movaps, SnB could
also sustain one iteration per clock. (But Bulldozer-family couldn't, because
xor-zeroing still needs an execution unit on AMD, even though is independent of the old
value of the register. And Bulldozer-family only has 0.5c throughput for
PXOR.)



/>


Limitations of
mov-elimination



Two dependent MOV instructions
in a row exposes a difference between Haswell and
Skylake.



.loop:
mov
eax, ecx
mov ecx, eax

sub ecx, 2
jnz
.loop



Haswell:
minor run-to-run variability (1.746 to 1.749 c / iter), but this is
typical:



 1,749,102,925 cycles:u #
2.690 GHz
4,000,000,212 instructions:u # 2.29 insn per cycle

1,000,000,208 branches:u # 1538.062 M/sec
3,000,079,561 uops_issued_any:u #
4614.308 M/sec
1,746,698,502 uops_executed_core:u # 2686.531 M/sec

745,676,067 lsd_cycles_4_uops:u # 1146.896 M/sec




Not all
the MOV instructions are eliminated: about 0.75 of the 2 per iteration used an execution
port. Every MOV that executes instead of being eliminated adds 1c of latency to the
loop-carried dep chain, so it's not a coincidence that
uops_executed and cycles are very
similar. All the uops are part of a single dependency chain, so there's no parallelism
possible. cycles is always about 5M higher than
uops_executed regardless of run-to-run variation, so I guess
there are just 5M cycles being used up somewhere
else.



Skylake: more stable than HSW results, and
more mov-elimination: only 0.6666 MOVs of every 2 needed an execution
unit.



 1,666,716,605 cycles:u #
3.897 GHz
4,000,000,136 instructions:u # 2.40 insn per cycle

1,000,000,132 branches:u # 2338.050 M/sec
3,000,059,008 uops_issued_any:u #
7014.288 M/sec

1,666,548,206 uops_executed_thread:u # 3896.473
M/sec
666,683,358 lsd_cycles_4_uops:u # 1558.739
M/sec


On Haswell,
lsd.cycles_4_uops accounted for all of the uops. (0.745 * 4 ~=
3). So in almost every cycle where any uops are issued, a full group of 4 is issued
(from the loop-buffer. I probably should have looked at a different counter that doesn't
care where they came from, like uops_issued.stall_cycles to
count cycles where no uops issued).



But on SKL,
0.66666 * 4 = 2.66664 is less than 3, so in some cycles the
front-end issued fewer than 4 uops. (Usually it stalls until there's room in the
out-of-order core to issue a full group of 4, instead of issuing non-full
groups).



It's weird, IDK what the exact
microarchitectural limitation is. Since the loop is only 3 uops, each issue-group of 4
uops is more than a full iteration. So an issue group can contain up to 3 dependent
MOVs. Perhaps Skylake is designed to break that up sometimes, to allow more
mov-elimination?




update:
actually this is normal for 3-uop loops on Skylake.
uops_issued.stall_cycles shows that HSW and SKL issue a simple
3 uop loop with no mov-elimination the same way they issue this one. So better
mov-elimination is a side-effect of splitting up issue groups for some other reason.
(It's not a bottleneck because taken branches can't execute faster than 1 per clock
regardless of how fast they issue). I still don't know why SKL is different, but I don't
think it's anything to worry about.



/>

In a less extreme case, SKL and HSW
are the same, with both failing to eliminate 0.3333 of every 2 MOV
instructions:



.loop:

mov eax, ecx
dec eax
mov ecx, eax



sub ecx, 1
jnz
.loop





2,333,434,710 cycles:u # 3.897 GHz
5,000,000,185 instructions:u # 2.14 insn
per cycle
1,000,000,181 branches:u # 1669.905 M/sec


4,000,061,152 uops_issued_any:u # 6679.720 M/sec
2,333,374,781
uops_executed_thread:u # 3896.513 M/sec
1,000,000,942 lsd_cycles_4_uops:u #
1669.906 M/sec


All of
the uops issue in groups of 4. Any contiguous group of 4 uops will contain exactly two
MOV uops that are candidates for elimination. Since it clearly succeeds at eliminating
both in some cycles, IDK why it can't always do
that.






href="https://software.intel.com/en-us/articles/intel-sdm#optimization"
rel="noreferrer">Intel's optimization manual
says that overwriting the result of mov-elimination as early as possible frees up the
microarchitectural resources so it can succeed more often, at least for
movzx. See Example 3-25. Re-ordering Sequence to
Improve Effectiveness of Zero-Latency MOV
Instructions
.




So maybe
it's tracked internally with a limited-size table of ref-counts? Something has to stop
the physical register file entry from being freed when it's no longer needed as the
value of the original architectural register, if it's still needed as the value of the
mov destination. Freeing PRF entries as soon as possible is key, because href="http://blog.stuffedcow.net/2013/05/measuring-rob-capacity/"
rel="noreferrer">PRF size can limit the out-of-order window to smaller than
ROB size.



I tried the examples on Haswell and
Skylake, and found that mov-elimination did in fact work significantly more of the time
when doing that, but that it was actually slightly slower in total cycles, instead of
faster. The example was intended to show the benefit on IvyBridge, which probably
bottlenecks on its 3 ALU ports, but HSW/SKL only bottleneck on resource conflicts in the
dep chains and don't seem to be bothered by needing an ALU port for more of the
movzx instructions.



See
also href="https://stackoverflow.com/questions/45766444/why-is-xchg-reg-reg-a-3-micro-op-instruction-on-modern-intel-architectures">Why
is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? for
more research + guesswork about how mov-elimination works, and whether it could work for
xchg eax, ecx. (In practice xchg
reg,reg
is 3 ALU uops on Intel, but 2 eliminated uops on Ryzen. It's
interesting to guess whether Intel could have implemented it more
efficiently.)



/>

BTW, as a workaround for an erratum on Haswell,
Linux doesn't provide uops_executed.thread when hyperthreading
is enabled, only uops_executed.core. The other core was
definitely idle the whole time, not even timer interrupts, href="https://serverfault.com/a/489410/28665">because I took it offline with
echo 0 > /sys/devices/system/cpu/cpu3/online.
Unfortunately this can't be done before perf decides that HT is
enabled, and my Dell laptop doesn't have a BIOS option to disable HT. So I can't get
perf to use all 8 hardware PMU counters at once on that system,
only 4. :/



Google Maps Android API v2 SupportMapFragment memory leak

Using 2 simple activities. First Activity which only holds
a button to start the 2nd Activity which holds the
map:




Main
Activity:



public class
MainActivity extends Activity {

@Override
protected void
onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}


public
void goToMap(View view){ //This is just the onClick method for the button

Intent intent=new Intent( this, BigMapTest.class);

startActivity(intent);
}


The
map activity:



public class
BigMapTest extends FragmentActivity {
SupportMapFragment
mapFragment;

GoogleMap
map;

@Override
protected void onCreate(Bundle arg0)
{
// TODO Auto-generated method stub

super.onCreate(arg0);


setContentView(R.layout.travel_diary_big_map);


mapFragment=(SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.big_map);


map=mapFragment.getMap();

}


The
XML Layout for the map
activity:



            xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>



android:id="@+id/big_map"
android:layout_width="fill_parent"

android:layout_height="fill_parent"

class="com.google.android.gms.maps.SupportMapFragment"

/>





Now
when I run this code, pressing the button to move to the Activity with the map, and
pressing back to get to the first activity...then repeating the process, I can see the
heap increasing in size each time, until it reaches it's limits and then it starts
clamping. If you mess around a bit more with map(i.e. zooming) I can get an OOM
Exception at this point.





01-25 16:10:13.931: D/dalvikvm(21578): GC_FOR_ALLOC freed 1898K, 7% free
45859K/49187K, paused 204ms
01-25 16:10:14.671: I/dalvikvm-heap(21578): Clamp
target GC heap from 52.724MB to 48.000MB
01-25 16:10:14.671:
D/dalvikvm(21578): GC_CONCURRENT freed 2534K, 6% free 46554K/49187K, paused
3ms+14ms
01-25 16:10:15.372: I/dalvikvm-heap(21578): Clamp target GC heap
from 52.979MB to 48.000MB
01-25 16:10:15.382: D/dalvikvm(21578):
GC_CONCURRENT freed 2273K, 5% free 46815K/49187K, paused 3ms+15ms
01-25
16:10:15.622: I/dalvikvm-heap(21578): Clamp target GC heap from 52.604MB to
48.000MB
01-25 16:10:15.622: D/dalvikvm(21578): GC_FOR_ALLOC freed 657K, 6%
free 46431K/49187K, paused 202ms
01-25 16:10:16.203: I/dalvikvm-heap(21578):
Clamp target GC heap from 52.959MB to 48.000MB
01-25 16:10:16.203:
D/dalvikvm(21578): GC_FOR_ALLOC freed 1469K, 5% free 46796K/49187K, paused 217ms />01-25 16:10:16.203: I/dalvikvm-heap(21578): Forcing collection of SoftReferences
for 278744-byte allocation
01-25 16:10:16.423: I/dalvikvm-heap(21578): Clamp
target GC heap from 52.952MB to 48.000MB
01-25 16:10:16.423:
D/dalvikvm(21578): GC_BEFORE_OOM freed 9K, 5% free 46786K/49187K, paused 219ms />01-25 16:10:16.423: E/dalvikvm-heap(21578): Out of memory on a 278744-byte
allocation. />




Any
suggestions/help would be appreciated.

java - ThreeTen-Backport implementation vs. backport of JSR-310?

Note: this is not a duplicate of href="https://stackoverflow.com/questions/29346649/comparing-threeten-backport-to-jsr-310">Comparing
ThreeTen backport to JSR-310. My question is more
specific.



In my company, I'm trying to get
DevOps to O.K. the use of ThreeTen-Backport for refactoring legacy code (which because
of deployment constraints with WebLogic 10.3.6.0 we can't upgrade from Java 6 and can't
use any version of JodaTime beyond version
1.2.1).




I can see DevOps having an
issue with this statement on ThreeTen-Backport's Github
page:




The backport
is NOT an implementation of JSR-310, as that
would
require jumping through lots of unnecessary hoops. Instead, this is
a
simple backport intended to allow users to quickly use the JSR-310
API
on Java SE 6 and
7.





When
they ask me what "Not an implementation" means, I need to be able to explain it to them.
However, the word implementation can have a wide semantic range,
and I'm not sure exactly what is meant by that
myself.



So my question is, in contexts like
this, what is meant by implementation vs.
backport? Since JSR-310 is a backport and not an implementation, is
there a counter example of something that I could use, that
is an implementation of something else, in the same sense
that ThreeTen-Backport is not an implementation of JSR-310?
What would an actual implementation of JSR-310 for Java 6 look like
if such a thing existed, and how would it be different from
ThreeTen-Backport?

javascript - Is there any way to distinguish between an unset property and a property set to undefined?





Say I have the object testObject = {a:
undefined}
. If I then console.log(testObject.a), I
get undefined. But the same happens if I
console.log(testObject.b), which doesn't exist. Is there any
way in JavaScript to distinguish between a and
b here? I ask mostly out of curiosity, I have no use
case.



Answer




hasOwnProperty()
method returns a boolean indicating whether the object has the specified property as own
(not inherited) property.



In given case
-



 testObject = {a:
undefined};

testObject.hasOwnProperty('a')
//true

testObject.hasOwnProperty('b')
//false

Monday 30 October 2017

r - Not able to install xkcd fonts

I was trying the xkcd font as per the instructions given
in the vignette:
vignette("xkcd-intro")



However
get an error on the following
step:



> system("cp xkcd.tff -t
~/.fonts")
cp: xkcd.tff: No such file or directory
cp: -t: No such
file or
directory



What
to do??

What are the differences between "=" and "

itemprop="text">

What are the differences between the
assignment operators = and <- in R?



I know that operators are slightly different,
as this example shows



x <- y
<- 5
x = y = 5

x = y <- 5
x <- y =
5
# Error in (x <- y) = 5 : could not find function
"<-<-"


But is
this the only difference?


itemprop="text">
class="normal">Answer





What are the
differences between the assignment operators = and
<- in
R?





As
your example shows, = and <- have
slightly different operator precedence (which determines the order of evaluation when
they are mixed in the same expression). In fact, href="https://www.rdocumentation.org/packages/base/versions/3.5.0/topics/Syntax"
rel="noreferrer">?Syntax in R gives the following
operator precedence table, from highest to
lowest:





‘->
->>’ rightwards assignment
‘<- <<-’ assignment (right to
left)
‘=’ assignment (right to
left)





But
is this the only difference?



Since you were
asking about the assignment operators: yes, that is the only
difference. However, you would be forgiven for believing otherwise. Even the R
documentation of href="https://www.rdocumentation.org/packages/base/versions/3.5.0/topics/assignOps"
rel="noreferrer">?assignOps claims that there are
more differences:





The operator <- can be used anywhere,

whereas the operator = is only allowed at the top level
(e.g.,
in the complete expression typed at the command prompt) or as
one

of the subexpressions in a braced list of
expressions.




Let’s
not put too fine a point on it: the R documentation is (subtly)
wrong
[ href="http://developer.r-project.org/equalAssign.html"
rel="noreferrer">1]
. This is easy to show: we just need to find
a counter-example of the = operator that isn’t (a) at the top
level, nor (b) a subexpression in a braced list of expressions (i.e. {…;
…}
). — Without further
ado:



x
# Error: object
'x' not found
sum((x = 1), 2)
# [1]
3
x

# [1]
1


Clearly we’ve
performed an assignment, using =, outside of contexts (a) and
(b). So, why has the documentation of a core R language feature been wrong for
decades?



It’s because in R’s syntax the symbol
= has two distinct meanings that get routinely
conflated:




  1. The first
    meaning is as an assignment operator. This is all we’ve talked
    about so far.

  2. The second meaning isn’t an operator but
    rather a syntax token that signals named argument
    passing
    in a function call. Unlike the = operator it
    performs no action at runtime, it merely changes the way an expression is
    parsed.




Let’s
see.



In any piece of code of the general
form …



‹function_name›(‹argname›
= ‹value›,
…)
‹function_name›(‹args›,
‹argname› = ‹value›,
…)


… the
= is the token that defines named
argument passing: it is not the assignment operator. Furthermore,
= is entirely forbidden in some syntactic
contexts:




if
(‹var› =
‹value›) …
while (‹var›
= ‹value›) …
for
(‹var› = ‹value› in
‹value2›) …
for (‹var1› in
‹var2› =
‹value›) …


Any
of these will raise an error “unexpected '=' in
‹bla›”.



In any other context,
= refers to the assignment operator call. In particular, merely
putting parentheses around the subexpression makes any of the above (a) valid, and (b)
an assignment. For instance, the following performs
assignment:




median((x =
1 : 10))


But
also:



if (! (nf = length(from)))
return()


Now
you might object that such code is atrocious (and you may be right). But I took this
code from the base::file.copy function (replacing
<- with =) — it’s a pervasive
pattern in much of the core R
codebase.




The href="http://developer.r-project.org/equalAssign.html" rel="noreferrer">original
explanation by John Chambers, which the the R documentation is probably based
on, actually explains this
correctly:





[= assignment is] allowed in only two places in the
grammar: at the top level (as a complete program or user-typed expression); and when
isolated from surrounding logical structure, by braces or an extra pair of
parentheses.




/>

A confession: I lied earlier. There
is one additional difference between the =
and <- operators: they call distinct functions. By default
these functions do the same thing but you can override either of them separately to
change the behaviour. By contrast, <- and
-> (left-to-right assignment), though syntactically
distinct, always call the same function. Overriding one also
overrides the other. Knowing this is rarely practical href="https://github.com/klmr/functional#a-concise-lambda-syntax"
rel="noreferrer">but it can be used for some fun
shenanigans.


Java array is lost when exiting method

I'm relatively new to java, and the passing by reference
without pointers confuses me a little. I wrote a function for homework that requires me
to return the length of user input, and assign use input to an array that is passed in,
when the method exits the user input array is lost, what is
wrong.



public static int
readArray(char[] intoArray)
{
char[] capture =
captureInputAsCharArray(); //User input comes back as char[]

System.arraycopy(intoArray,0, capture, 0,
capture.length);


return capture.length;

}

public static main(String[] args)
{
size =
readArray(arrItem7); // item 7
System.out.println(size);

printOneInLine(arrItem7); // prints individual elements of
array
}

plot explanation - What was the motivation behind the Engineers actions in Prometheus?

After
watching Prometheus I
don't have a clear idea of why the Engineers created the human beings. Because, if they
created humans so that they can test their bio-weapons on us, then it makes sense, but
it's ambiguous. Why did the Engineers want to destroy the human
beings
that they have created?


Did I miss
something?


itemprop="text">
class="normal">Answer


The Engineers are
planet builders who seed planets with the gift of life. It's shown in the start of the
film that the Engineers visit Earth repeatedly, as their figure pointing to a
constellation of stars is found throughout history.


When
the film starts, an Engineer drinks the dark fluid, that starts this chain reaction of
life. This fluid is so powerful, that it can turn a dead planet into a living
Earth.


When the crew of the Prometheus lands on the alien
planet, and they enter the tomb their foot steps uncover worms that are preserved in the
tomb. They are still alive and crawling. The tomb cylinders start to leak the black
fluid and the worms mix with the fluid. These worms evolve into the snake like creatures
that later attack the two crew members stuck in the
tomb.


Later, only the Prometheus captain refers to the
black cylinders as bombs or weapons. When Elizabeth is talking to David she asks why the
Engineers would want to destroy Earth, David replies "sometimes before you can create
you must destroy".


I don't think the Engineers were going
to destroy Earth as much as "restart" it. It's clear they took an active role in making
our planet, but they had some kind of agenda that isn't defined in the
film.


This is why, at the end of the film Elizabeth flies
to their home world. To find out why the Engineers had decided Earth was a
failure.


EDIT:


I
answered this question two years ago, but since then a lot has been revealed about the
plot for Prometheus by Ridley Scott. The following comes from various sources that I've
read.



  • At the start of the
    film. Illustrations of figures pointing to the stars implies this was a message from the
    Engineers. Ridley stated in an interview that there is nothing in the film that
    indicates these figures were Engineers, and the pointing could have been a warning not
    an invitation.


  • Ridley says the early
    planet shown at the start where an Engineer sacrifices himself was not Earth, nor does
    it indicate if it was a historic reference or present
    day.


  • Ridley Scott has said in an
    interview that the reason the Engineers wanted to destroy Earth (specifically mankind)
    was because Jesus Christ was an Engineer. The Engineers made man, man went bad so they
    sent an Engineer to try and fix the problem. We crucified the Engineer and apparently
    they didn't like this.



There are many other
controversial topics related to the film, but I decided to only reference the things
that came directly from Ridley.


assembly - How can I store 1byte value in 64bit register only using 64bit registers?

itemprop="text">

I need to write a pixelization
assembly code ONLY using %rax, %rbx, %rcx, %rdx, %rsi, and %rdi (also %rsp and
%rbp)



So I've first wrote code in C and changed
any other registers into 64 bit registers, but at the point below when I change the
register it gives Segmentation default



C
code:



*temp = b;
*(temp
+ 1) = g;

*(temp + 2) =
r;


Assembly code By
gcc:



movq -48(%rbp), %rax

movl %eax, %edx
movq -16(%rbp), %rax
movb %dl, (%rax)

movq -16(%rbp), %rax

addq $1, %rax
movq
-56(%rbp), %rdx
movb %dl, (%rax)
movq -16(%rbp),
%rax
addq $2, %rax
movq -64(%rbp), %rdx
movb %dl,
(%rax)


Changed %dl to
%rdx:




movq -16(%rbp),
%rax
movq -48(%rbp), %rdx
movzbq (%rdx), %rbx
movq %rbx,
(%rax)
movq -16(%rbp), %rax
addq $1, %rax
movq -56(%rbp),
%rdx
movzbq (%rdx), %rbx
movq %rbx, (%rax)

movq
-16(%rbp), %rax
addq $2, %rax
movq -64(%rbp), %rdx
movzbq
(%rdx), %rbx
movq %rbx, (%rax)


Answer




I think you want to do something
like:



 t = r &
0xff;

u = *temp & ~ 0xfful;
*temp = u |
t;
t = (g & 0xff) << 8;
u = *temp & ~
0xff00ul;
*temp = u | t;
t = (b & 0xff) << 16;

u = *temp & ~0xff00000ull;
*temp = u |
t;



You
should be able to write this with 64bit regs only. You should also be able to find a
whole bunch of ways to make this way smaller than this.



How do I remove a particular element from an array in JavaScript?

itemprop="text">

I have an array of numbers, and I'm
using the .push() method to add elements to
it.



Is there a simple way to remove a specific
element from an array? The equivalent of something like
array.remove(number);.



I
have to use core JavaScript - frameworks are not
allowed.



Answer




Find the index of
the array element you want to remove using href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf"
rel="noreferrer">indexOf, and then remove that
index with href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"
rel="noreferrer">splice.






The splice() method changes the contents of an array by removing

existing elements and/or adding new
elements.




class="snippet" data-lang="js" data-hide="false" data-console="true"
data-babel="false">

class="snippet-code-js lang-js prettyprint-override">const array = [2, 5,
9];

console.log(array);


const index
= array.indexOf(5);
if (index > -1) {
array.splice(index,
1);
}

// array = [2, 9]
console.log(array);






The
second parameter of splice is the number of elements to remove.
Note that splice modifies the array in place and returns a new
array containing the elements that have been removed.



floating point - Difference between decimal, float and double in .NET?

Integers, as was mentioned, are whole numbers. They can't
store the point something, like .7, .42, and .007. If you need to store numbers that are
not whole numbers, you need a different type of variable. You can use the double type or
the float type. You set these types of variables up in exactly the same way: instead of
using the word int, you type double or
float. Like
this:


float myFloat;
double
myDouble;

(float
is short for "floating point", and just means a number with a point something on the
end.)


The difference between the two is in the size of the
numbers that they can hold. For float, you can have up to 7
digits in your number. For doubles, you can have up to 16
digits. To be more precise, here's the official
size:


float: 1.5 × 10^-45 to 3.4 ×
10^38
double: 5.0 × 10^-324 to 1.7 ×
10^308

float
is a 32-bit number, and double is a 64-bit
number.


Double click your new button to get at the code.
Add the following three lines to your button
code:


double myDouble;
myDouble =
0.007;
MessageBox.Show(myDouble.ToString());

Halt
your program and return to the coding window. Change this
line:


myDouble = 0.007;
myDouble =
12345678.1234567;

Run your
programme and click your double button. The message box correctly displays the number.
Add another number on the end, though, and C# will again round up or down. The moral is
if you want accuracy, be careful of rounding!

java - loan payment calculator, how to implement multiple methods. Trouble developing method to interact with main method

The idea of this assignment is to have multiple methods
interact with each other. I am asking the user for loan amount, interest rate and
duration of loan. Then the program is supposed to have one method that calculates the
monthly rate, one method that calculates and returns the monthly payment and a method to
print the loan statement (amt borrowed,annual interest rate, number of months, and the
monthly payment).




I am not receiving
any errors in the editor but my program just asks for the three inputs from the user and
does not print the loan statement. Any
suggestions?



public class CarLoan
{

/**
* @param args the command line
arguments
*/
public static void main(String[] args) {
//
declare variables for main method

double loanAmount;//double value
loan amount
double annualInterestRate;//double value interest
rate
int numberOfMonths;//int value for number of months
double
monthlyPayment;

Scanner keyboard = new
Scanner(System.in);

System.out.println("Please enter the amount of
your loan.");
loanAmount =
keyboard.nextDouble();


System.out.println("Please enter
the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate
= keyboard.nextDouble();

System.out.println("Please enter the
number of months you have to pay back your loan.");
numberOfMonths =
keyboard.nextInt();

}

public static double
calcMonthlyInterestRate(double annualInterestRate){
double
monthlyInterestRate;

monthlyInterestRate =
(annualInterestRate/12);
return monthlyInterestRate;
}//end method
CalcMonthlyInterestRate

public static double
calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths
){
double monthlyPayment;
double calcMonthlyPayment;

calcMonthlyPayment =
(monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);

return monthlyPayment = calcMonthlyPayment;
}//end method
CalcMonthlyPayment


public static void loanStatment
(double loanAmount, double annualInterestRate, intnumberOfMonths, double
monthlyPayment){
System.out.println("Your loan amount is "
+loanAmount);
System.out.println(annualInterestRate);

System.out.println(numberOfMonths);

System.out.println(monthlyPayment);
}

}//end main
method



}//end main
method


I am not sure
if some of my code is still redundant.

html5 - html select element with default not in the options













I
want to do something like
this:






here's
the rel="noreferrer">jsfiddle.



now I
want the first option the selected one with the content "Choose option" to not be
visible in the dropdown. how can i do that, if that's possible with a select element or
should i do a custom thing.
Thanks in advance.




Answer




You could remove the selected element as soon
as you open the
list:



$('select').click(function
() {
$('option[selected="selected"]',
this).remove();
});


I
am not aware of any native HTML/HTML5 solution.



utf 8 - php Cannot modify header information

I'm trying to return a json that has been ut8_encoded. I'm
setting before it, the header to HTTP response code
also.


 /**
* Set the response
header and HTTP response code and response the data
* @param $data array of
response to be encoded as json
* @param int $status the http status (200 is
default)
* @return string the json presentation of the array given

*/
public function response($data, $status = 200)
{

header("HTTP/1.1 " . $status . " " . $this->getRequestStatus($status));

echo utf8_encode(json_encode($data, JSON_UNESCAPED_SLASHES));

}

The results are coming back ok
but with a warning -




Warning: Cannot modify header information - headers already sent by (output
started at RestApi.php:115) in RestApi.php on line
113



edit:
Sorry,
I probably should of add it - The warning is talking about those two lines that causing
the warning.


How can I remove the
warning?


The error can occur if I'm adding this part to the
.htaccess ?


            mod_headers.c>
Header set Access-Control-Allow-Origin "*"

Header set Access-Control-Allow-Methods "*"
Header set Content-Type
"application/json;
charset=utf-8"


I
just realized. So maybe I don't really need to encode the
response

What year was The Warriors (1979) first shown on TV or cable?

Is there a
way to figure out the year the movie href="http://en.wikipedia.org/wiki/The_Warriors_%28film%29" rel="nofollow">The
Warriors (1979) was first shown on TV or cable?



Answer



According to this href="http://80smemories.com/2011/07/the-cult-classic-the-warriors-first-time-on-tvhbo-1983/"
rel="nofollow">webpage, The Warriors was first time on TV in
1983.


java - Default keystore file does not exist?

itemprop="text">

I'm getting this
error.



C:\Program
Files\Java\jre7\bin>keytool -list -v -keystore
"C:\Users\Suresh\.android\debug.keystore" -alias androiddebugkey -storepass android
-keypass android

keytool error: java.lang.Exception: Keystore file
does not exist:
C:\Users\Suresh\.android\debug.keystore


java.lang.Exception:
Keystore file does not exist:
C:\Users\Suresh\.android\debug.keystore

at
sun.security.tools.KeyTool.doCommands(Unknown Source)
at
sun.security.tools.KeyTool.run(Unknown Source)
at
sun.security.tools.KeyTool.main(Unknown Source)

C:\Program
Files\Java\jre7\bin>



src="https://i.stack.imgur.com/PjfiA.png" alt="enter image description
here">



Answer




You must be providing the wrong path to the
debug.keystore
file.



Follow these steps to get the correct path
and complete your
command:




  1. In eclipse, click
    the Window menu -> Preferences -> Expand Android ->
    Build

  2. In the right panel, look for: Default
    debug keystore:

  3. Select the entire box next to
    the label specified in Step
    2




And
finally, use the path you just copied from Step 3 to construct your
command:



For example, in my case, it would
be:




C:\Program
Files\Java\jre7\bin>keytool -list -v -keystore
"C:\Users\Siddharth
Lele.android\debug.keystore" -alias
androiddebugkey -storepass android
-keypass
android





UPDATED:



If
you had already followed the steps mentioned above, the only other solution is to delete
the debug.keystore and let Eclipse recreate it for
you.



Step 1: Go to the path where your keystore
is stored. In your case,
C:\Users\Suresh\.android\debug.keystore



Step
2: Close and restart Eclipse.




Step 3
(Optional): You may need to clean your project before the
debug.keystore is created
again.



Source:
href="http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file"
rel="nofollow
noreferrer">http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file



You
can refer to this for the part about deleting your
debug.keystore file: href="https://stackoverflow.com/questions/2194808/debug-certificate-expired-error-in-eclipse-android-plugins/2196397#2196397">"Debug
certificate expired" error in Eclipse Android plugins



windows - How to enforce case sensitive table and column names in MySql?

The thing is we are working on windows machine and once
done we deploy the code on unix machine. The code works fine on windows but then in unix
we get the error like 'no such table exists' after changing the table name in correct
case it works fine in unix too. Actually, in windows there is no case sensitive table
names by default but in unix they do have ( read that MySQL tables are actually files
and in unix we have case sensitive file name but not in windows ). Workaround could be
to create all tables again and lets have the table name in lowercase. Yes, we can do
that too, thats fine.



But, still can we impose
case sensitivity on table names in MySql ( windows machine ). If yes, then please let me
know how to do that.

plot explanation - At which dream level did Inception end? - Movies & TV

itemprop="text">

In the ending of href="http://www.imdb.com/title/tt1375666/"
rel="noreferrer">Inception (2010), there is some doubt
that Cobb is in the real world. But if he is not in the real world then at which level
of the dream he is in?




Starting at
the presumed 'real world' as the first level of the story, I think the final scene it's
the fifth level (limbo) because at the fourth level they save Fischer, but I need
clarification.


itemprop="text">
class="normal">Answer



None of
the different means you can use to guess whether Cobb is in a dream or not at the end of
the movie are completely reliable.



The spinning
top has huge issues - the fact that it was Mal's totem, that it appears to act in a
simplistic way that perhaps other people could dream, hence invalidating its usefulness
- and of course the fact that we are never even shown what the top does at the end of
the movie.



I am unconvinced by how completely
watertight the wedding ring theory (referenced in @Eoin's answer), as it seems possible
for Cobb to dream the wedding ring when he thinks he is in a dream
and not otherwise. Yes it is an interesting theory, but whilst it is certainly a
deliberate action from the writers/director - the meaning is not completely clear. Cobb
clearly seems to treat the spinning top as his totem (flawed or not), as he uses it when
flustered by his dream in Mombassa. So yes, it could be a clue, it could even be his
true or second totem - but it is still not completely reliable in my
opinion.



So is Cobb in a dream at the end? I
don't think we can tell. Unlike the other answer, I like the ambiguity in the movie. If
pushed to give an answer I would say that the fact that he is such an experienced shared
dreamer, it seems likely that he would eventually work out if he is in a dream or not -
so I guess he is likely to be in the real world, and the wedding ring therefore might be
a true clue to that.




So to answer the
original question, if this is not the real world, what level is this? Well if the top
level of the story is not the real world, and is in fact another dream, then 'who knows'
is the only real answer. The question has no real meaning as there are possibly untold
levels of dreaming we have no knowledge of.



php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...