Thursday, 31 March 2016

r - How do I change the scale on the x-axis using ggplot2?

The goal of our project was to assess 2 behavioral responses (crossing success and crossing decision) by deer when interacting with fences. We used a modified BACI design for our study where we monitored fence sections during a pre-modification period and then implemented certain modification during what we termed a post-modification period.



We used logistic regression to evaluate the crossing success and crossing decision of mule deer and white-tailed deer at these fence sections. We modeled the effects of certain demographic factors and fence characteristics on our 2 response variables using generalized linear models with a logit link (i.e., logistic regression).




Now that we have identified the top model for both analysis, we are trying to create a caterpillar plot to graphically show the change of crossing success between the pre-modification period and the post-modification period for a specific variable we titled "Type_Period".



However, we have not been able to figure out how to change the scale of our plot (which I have attached). We used GGally, broom and ggplot2 to create the Caterpillar plot.



enter image description here



We have looked on multiple GGally, and ggplot2 help pages and I haven't been able to find any mention of how to manipulate the scale. We have tried "zooming" in on the graph but ggplot2 couldn't read the command. We tried changing the xlim but got an error message that said "ignoring unknown parameter xlim."



Here is the script that we used for the caterpillar plot only. I will provide the full script and sample database if necessary.




library(GGally)
library(broom)
library(ggplot2)
log.reg <- glm(Decision~ Type_Period, data=analysis, weights = analysis$Freq, x=TRUE,family=binomial(link="logit"))
ggcoef(log.reg, xlim=c(-1, 2))

.net - How do I fix the Visual Studio compile error, "mismatch between processor architecture"?



I'm new to project configuration in Visual Studio 2010, but I've done some research and still can't quite figure this issue out. I have a Visual Studio solution with a C++ DLL referencing the C# DLL. The C# DLL references a few other DLLs, some within my project and some external. When I try to compile the C++ DLL, I get this warning:




warning MSB3270: There was a mismatch between the processor architecture of the project being build "MSIL" and the processor architecture of the reference "[internal C# dll]", "x86".




It tells me to go to Configuration Manager to align my architectures. The C# DLL is set up with platform target x86. If I try to change this to something else, like Any CPU, it complains because one of the external DLLs it depends on has platform target x86.



When I look at Configuration Manager it shows the Platform for my C# DLL as x86 and for my C++ project as Win32. This seems like the right setup; surely I don't want the project for my C++ project to have platform set to x64, which is the only other option presented.



What am I doing wrong here?


Answer



This warning seems to have been introduced with the new Visual Studio 11 Beta and .NET 4.5, although I suppose it might have been possible before.



First, it really is just a warning. It should not hurt anything if you are just dealing with x86 dependencies. Microsoft is just trying to warn you when you state that your project is compatible with "Any CPU" but you have a dependency on a project or .dll assembly that is either x86 or x64. Because you have an x86 dependency, technically your project is therefore not "Any CPU" compatible. To make the warning go away, you should actually change your project from "Any CPU" to "x86". This is very easy to do, here are the steps.




  1. Go to the Build|Configuration Manager menu item.

  2. Find your project in the list, under Platform it will say "Any CPU"

  3. Select the "Any CPU" option from the drop down and then select

  4. From that dialog, select x86 from the "New Platform" drop down and make sure "Any CPU" is selected in the "Copy settings from" drop down.

  5. Hit OK

  6. You will want to select x86 for both the Debug and Release configurations.



This will make the warning go away and also state that your assembly or project is now no longer "Any CPU" compatible but now x86 specific. This is also applicable if you are building a 64 bit project that has an x64 dependency; you would just select x64 instead.



One other note, projects can be "Any CPU" compatible usually if they are pure .NET projects. This issue only comes up if you introduce a dependency (3rd party dll or your own C++ managed project) that targets a specific processor architecture.


PHP Removing elements from an array




I am new to PHP and I need a function that enables me to remove an item from an array.



So far I have:



 $ab = milk
$ba = apple
$ca = bread


array($ab, $ba, $ca).


Is there a function or method available to delete $ba from the list?



      I.e  if (condition)==true

array_delete ($ab): ($ab, $ba, $ca)



Obviously the above does not work, or exist, but I am looking for something like it that does exist.



Any help would be huugely appreciated!



Thanks


Answer



you can try this:



$ab = milk;
$ba = apple;

$ca = bread;

$arr=array($ab, $ba, $ca);
if (in_array($ba, $arr))
{
unset($ba);
}


hope this may help you..



html - Having a placeholder in a Select option





How would I get an equivalent placeholder in a select option? For example when you have a select list it may say in the field "City" then when clicking that it would show all cities in the options.


Answer



I think this is what you want .



HTML:






CSS :



#choice option { color: black; }
.empty { color: gray; }



JavaScript:



$("#choice").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty")
});

$("#choice").change();



try this jsfiddle.


Pass urls stored in array to window.open in for loop - Javascript

I'm trying to step through an array and pass my urls stored there to the window.open function. This is what I have.



$('a.linked').click(function(e) {
e.preventDefault();

var i;
var urls = ['http://example.com', 'http://example2.com', 'http://example3.com'];

for (i = 0; i < urls.length; i++) {
var ts = i*3500;
setTimeout(function(){window.open(urls[i]); }, ts);
}
});



This is opening the new windows at the correct timing but I'm getting about:blank. I thought it might be not escaping quotes.




The duplicate answer says I'm losing my value of i However, when I remove the setTimeout I get all the new windows with the
correct urls. The following code demonstrates not losing the value of i.




$('a.linkedinProfiles').click(function(e) {
e.preventDefault();
var i;

var urls = ['http://example.com', 'http://example2.com', 'http://example3.com'];
for (i = 0; i < urls.length; i++) {
var ts = i*3500;
{window.open(urls[i]); };
} });


I know this has to be something simple I am missing. Thanks in advance.

screen scraping - How to implement a web scraper in PHP?

What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP?

cinema history - Era of profanity in movie scripts?

The quote "Frankly, my dear I don't give a damn" from Gone with the Wind was famous largely because of the early use of profanity in the script.


In films from the 90s to the present, many movies are decorated with profanity. Is Gone with the Wind the impetus for the widespread use of profanity in films nowadays?


If not, what film is?


Answer


There was no movie rating system in place back in the 1940's, and movies were greatly censored by the US government. In the 1920's the Supreme Court ruled that free speech did not apply to movies, and a control board was arranged where by all film studios had to submit their scripts for censorship.


Movie studios were given guide lines by which they had to follow. So it's not so much that profanity is now widespread, as much as it was strictly forbidden back in the 1940's.


This system of governed film making slowly started to collapse over the years and gave birth to the Motion Picture film rating system. Where the film ratings and censorship is controlled by the film industry and not by a single controlling person or government.


Now that we have the rating system, films can be classified by their rating. Today's ratings are, at least by idea, implemented by our peers. So as society changes so do those who review and rate films.


That is why we see more profanity in PG rated films, as parents who rate the films accept the fact that children in this age group use these profane words or acknowledge that the film works the way the script was written.


New ratings were introduced including PG-13. To address the need for films that target a segment of the population that are pre-adult but seek adult style films.


Still, I have to wonder who these people are that rate these films.


BASH - Fixing a CSV by appending lines

Currently I have a CSV file that contains address information, the problem I have is that the address field has embedded new line characters so when I try and load it into MySQL it doesn't work.



Here is an example of what my csv file looks like:



ID|NAME|ADDRESS|PHONE
1|"JOHN DOE"|"1 SHORT ROAD LONDON UNITED KINGDOM"|"01234 567 890"
2|"JANE DOE"|"1 SHORT ROAD LONDON
UNITED KINGDOM"|"01234 567 890"
3|"BOB DOE"|"1
SHORT ROAD
LONDON
UNITED KINGDOM"|"01234 567 890"


And Here is what I want it to look like:



ID|NAME|ADDRESS|PHONE
1|"JOHN DOE"|"1 SHORT ROAD LONDON UNITED KINGDOM"|"01234 567 890"
2|"JANE DOE"|"1 SHORT ROAD LONDON UNITED KINGDOM"|"01234 567 890"
3|"BOB DOE"|"1 SHORT ROAD LONDON UNITED KINGDOM"|"01234 567 890"


My initial approach was to count the amount of '|' in the header line and have that as the target count.



typeset -i target
target=`head -1 broken.csv | awk -F\| '{print NF-1}'`


Then what I wanted to do was to iterate through the file line by line doing the same count on each line



while read -r line
do
count=`echo $line | awk -F\| '{print NF-1}'`


But I can't figure out the code for the next bit



What I want to do is



if count == target
echo $line >> fixed.csv
else
#append the next line and do the count again


I think I need a nested loop but I can't quite figure out the syntax so was hoping someone could give me some insight.



Any help much appreciated :)

Wednesday, 30 March 2016

java - Unsupported major.minor version 52.0 in my app



I'm trying to compile my Android project and I'm getting this error



[INFO] Exception in thread "main" java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0

[INFO] at java.lang.ClassLoader.defineClass1(Native Method)
[INFO] at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
[INFO] at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
[INFO] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
[INFO] at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
[INFO] at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
[INFO] at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
[INFO] at java.security.AccessController.doPrivileged(Native Method)
[INFO] at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
[INFO] at java.lang.ClassLoader.loadClass(ClassLoader.java:425)

[INFO] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
[INFO] at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
[INFO] at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------


I've been reading in other post that try to compile with Java 8 might cause that error but not my case, I have the following Java version:




java version "1.7.0_79"
OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-0ubuntu0.14.04.2)
OpenJDK 64-Bit Server VM (build 24.79-b02, mixed mode)


OS: Linux Mint
(I'm not have Java 8 installed.)
Build: MAVEN



Can anyone help me with this?



Answer



I face this problem too when making new project from android studio.



I've been able to resolve this by downgrading buildToolsVersion in app gradle setting:
change {module-name}/build.gradle line




buildToolsVersion "24.0.0 rc1"





to




buildToolsVersion "23.0.3"





@Edit:
In Android Studio 2.1 Go to File-> Project Structure->App -> Build Tool Version. Change it to 23.0.3



Do the method above, only when you are using java version 7 and for some reason do not want to upgrade to java 8 yet.




Hope this helps


linux - How to use PREFETCHT0 Instruction in my C code?



I want to prefetch certain addresses (which are address of certain elements of a huge array) in my C program and see the effect of that on time taken.




The instruction about PREFETCH i found here PREFETCH0. But I am not aware of how to use it in C using inline assembly. It would be of great help if some body can give some idea how should I use this instruction with the address as argument, in C program.


Answer



Don't write it using inline assembly which would make the compiler's job harder. GCC has a built-in extension (See gcc builtins docs for more details) for prefetch you should use instead:



__builtin_prefetch(const void*)


This will generate code using the prefetch instructions of your target, but with more scope for the compiler to be smart about it.




As a simple example of the difference between inline ASM and gcc's builtin consider the following two files, test1.c:



void foo(double *d, unsigned len) {
for (unsigned i = 0; i < len; ++i) {
__builtin_prefetch(&d[i]);
d[i] = d[i] * d[i];
}
}



And test2.c:



void foo(double *d, unsigned len) {
for (unsigned i = 0; i < len; ++i) {
asm("prefetcht0 (%0)"
: /**/
: "g"(&d[i])
: /**/
);
d[i] = d[i] * d[i];

}
}


(Note that if you benchmark that I'm 99% sure that a third version with no prefetch would be faster than both of the above, because you've got predictable access patterns and so the only thing that it really achieves is adding more bytes of instructions and a few more cycles)



If we compile both with -O3 on x86_64 and diff the generated output we see:



        .file   "test1.c"                                       |          .file   "test2.c"
.text .text

.p2align 4,,15 .p2align 4,,15
.globl foo .globl foo
.type foo, @function .type foo, @function
foo: foo:
.LFB0: .LFB0:
.cfi_startproc .cfi_startproc
testl %esi, %esi # len testl %esi, %esi # len
je .L1 #, je .L1 #,
leal -1(%rsi), %eax #, D.1749 | leal -1(%rsi), %eax #, D.1745
leaq 8(%rdi,%rax,8), %rax #, D.1749 | leaq 8(%rdi,%rax,8), %rax #, D.1745

.p2align 4,,10 .p2align 4,,10
.p2align 3 .p2align 3
.L4: .L4:
movsd (%rdi), %xmm0 # MEM[base: _8, offset: 0B], D. | #APP
prefetcht0 (%rdi) # ivtmp.6 | # 3 "test2.c" 1
> prefetcht0 (%rdi) # ivtmp.6
> # 0 "" 2
> #NO_APP
> movsd (%rdi), %xmm0 # MEM[base: _8, offset: 0B], D.
addq $8, %rdi #, ivtmp.6 addq $8, %rdi #, ivtmp.6

mulsd %xmm0, %xmm0 # D.1748, D.1748 | mulsd %xmm0, %xmm0 # D.1747, D.1747
movsd %xmm0, -8(%rdi) # D.1748, MEM[base: _8, offset: | movsd %xmm0, -8(%rdi) # D.1747, MEM[base: _8, offset:
cmpq %rax, %rdi # D.1749, ivtmp.6 | cmpq %rax, %rdi # D.1745, ivtmp.6
jne .L4 #, jne .L4 #,
.L1: .L1:
rep ret rep ret
.cfi_endproc .cfi_endproc
.LFE0: .LFE0:
.size foo, .-foo .size foo, .-foo
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4" .ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"

.section .note.GNU-stack,"",@progbits .section .note.GNU-stack,"",@progbits


Even in this simple case the compiler in question (GCC 4.8.4) has taken advantage of the fact that it's allowed to reorder things and chosen, presumably on the basis of an internal model of the target processors, to move the prefetch after the initial load has happened. If I had to guess it's slightly faster to do the load and prefetch in that order in some scenarios. Presumably the penalty for a miss and a hit is lower with this order. Or the ordering like this works better with branch predictions. It doesn't really matter why the compiler chose to do this though, the point is that it's exceedingly complex to fully understand the impact of even trivial changes to generated code on modern processors in real applications. By using builtin functions instead of inline assembly you benefit from the compiler's knowledge today and any improvements that show up in the future. Even if you spend two weeks studying and benchmarking this simple case the odds are fairly good that you'll not beat future compilers and you may even end up with a code base that can't benefit from future improvements.



Those problems are before we even begin to discuss portability of your code - with builtin functions they fall into one of two categories normally when on an architecture without support either graceful degradation or enabling emulation. Applications with lots of x86 inline assembly were harder to port to x86_64 when that came along.


Why is there only a single parallel universe in Fringe?

I mean according to Walter, there could be any number of infinite universes if I'm not wrong. So why do they only talk about two universes and only one remaining in the end. What about others?


Answer


There can be a number of theories but I think the primary one is because it would have few viewers, certainly not enough to make the show profitable. TV shows are a conveyance for advertising - it is meant to be a profit center, and cannot be just ART. Ideally every television show's advertisers want millions of viewers each week, something that is difficult if the audience is expected to reboot their thinking at every return from a commercial.


"Are we in universe 1 or the alter-1?" is easier to handle than, "Are we in universe 1, alter-1, alter-2, alter-3, or _alter-N?"


The writers would get confused, the actors would miscue which one they were supposedly in, the writers/actors would have to develop/portray different back story and keep them alive (but separate) simultaneously. All this is a lot of trouble, and would develop a diligent core viewership of art followers who, granted would like to keep expanding the universe until it filled their heads. But, honestly, the number of viewers dwindles each time the alter-N is increased because, "It's just too damn hard" to make it, to portray it, and, frankly, for the average viewer to watch it. And every time an audience member leaves, the show's sponsor's pockets gets slightly emptier.


So, they've acknowledged it through dialog that there are theoretically greater than two universes. However, I think they have kept the universes to two to keep the dedicated audience, and to help the actors and the writers.


oop - Reference - What does this error mean in PHP?

What is this?



This is a number of answers about warnings, errors, and notices you might encounter while programming PHP and have no clue how to fix them. This is also a Community Wiki, so everyone is invited to participate adding to and maintaining this list.



Why is this?




Questions like "Headers already sent" or "Calling a member of a non-object" pop up frequently on . The root cause of those questions is always the same. So the answers to those questions typically repeat them and then show the OP which line to change in their particular case. These answers do not add any value to the site because they only apply to the OP's particular code. Other users having the same error cannot easily read the solution out of it because they are too localized. That is sad because once you understood the root cause, fixing the error is trivial. Hence, this list tries to explain the solution in a general way to apply.



What should I do here?



If your question has been marked as a duplicate of this one, please find your error message below and apply the fix to your code. The answers usually contain further links to investigate in case it shouldn't be clear from the general answer alone.



If you want to contribute, please add your "favorite" error message, warning or notice, one per answer, a short description what it means (even if it is only highlighting terms to their manual page), a possible solution or debugging approach and a listing of existing Q&A that are of value. Also, feel free to improve any existing answers.



The List







Also, see:

php - What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?




I have tried reading some articles, but I am not very clear on the concepts yet.



Would someone like to take a shot at explaining to me what these technologies are:




  1. Long Polling

  2. Server-Sent Events

  3. Websockets

  4. Comet




One thing that I came across every time was, the server keeps a connection open and pushes data to the client. How is the connection kept open, and how does the client get the pushed data? (How does the client use the data, maybe some code might help?)



Now, which one of them should I use for a real-time app. I have been hearing a lot about websockets (with socket.io [a node.js library]) but why not PHP?


Answer



In the examples below the client is the browser and the server is the webserver hosting the website.



Before you can understand these technologies, you have to understand classic HTTP web traffic first.




Regular HTTP:




  1. A client requests a webpage from a server.

  2. The server calculates the response

  3. The server sends the response to the client.



HTTP




Ajax Polling:




  1. A client requests a webpage from a server using regular HTTP (see HTTP above).

  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server at regular intervals (e.g. 0.5 seconds).

  3. The server calculates each response and sends it back, just like normal HTTP traffic.



Ajax Polling




Ajax Long-Polling:




  1. A client requests a webpage from a server using regular HTTP (see HTTP above).

  2. The client receives the requested webpage and executes the JavaScript on the page which requests a file from the server.

  3. The server does not immediately respond with the requested information but waits until there's new information available.

  4. When there's new information available, the server responds with the new information.

  5. The client receives the new information and immediately sends another request to the server, re-starting the process.




Ajax Long-Polling



HTML5 Server Sent Events (SSE) / EventSource:




  1. A client requests a webpage from a server using regular HTTP (see HTTP above).

  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection to the server.

  3. The server sends an event to the client when there's new information available.







HTML5 SSE



HTML5 Websockets:




  1. A client requests a webpage from a server using regular http (see HTTP above).

  2. The client receives the requested webpage and executes the JavaScript on the page which opens a connection with the server.

  3. The server and the client can now send each other messages when new data (on either side) is available.





    • Real-time traffic from the server to the client and from the client to the server

    • You'll want to use a server that has an event loop

    • With WebSockets it is possible to connect with a server from another domain.

    • It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!

    • If you want to read more, I found these very useful: (article), (article) (tutorial).





HTML5 WebSockets



Comet:



Comet is a collection of techniques prior to HTML5 which use streaming and long-polling to achieve real time applications. Read more on wikipedia or this article.







Now, which one of them should I use for a realtime app (that I need to

code). I have been hearing a lot about websockets (with socket.io [a
node.js library]) but why not PHP ?




You can use PHP with WebSockets, check out Ratchet.


linux - Where is PATH variable set in Ubuntu?





This is a very interesting question that I stumbled upon when I was creating a command-line application tool for Linux. Unfortunately, the answer on SO is so hidden among the myriad answers to other questions that I decided to ask another question on SO for those who want to modify PATH programmatically.


Answer



Grzegorz Żur's answer to another question captures it brilliantly. Unfortunately it was hidden away among many other answers.




There are multiple ways to do it. The actual solution depends on the
purpose.



The variable values are usually stored in either a list of assignments
or a shell script that is run at the start of the system or user

session. In case of the shell script you must use a specific shell
syntax.



System wide




  1. /etc/environment List of unique assignments. Perfect for adding system-wide directories like /usr/local/something/bin to PATH
    variable or defining JAVA_HOME.

  2. /etc/xprofile Shell script executed while starting X Window System session. This is run for every user that logs into X Window
    System. It is a good choice for PATH entries that are valid for

    every user like /usr/local/something/bin. The file is included by
    other script so use POSIX shell syntax not the syntax of your user
    shell.

  3. /etc/profile and /etc/profile.d/* Shell script. This is a good choice for shell-only systems. Those files are read only by shells.

  4. /etc/.rc. Shell script. This is a poor choice because it is single shell specific.




Also, /etc/environment is not a script file, but rather consists of assignment expressions, one per line. Since this file stores the system-wide locale and path settings, it is most oft quoted choice.
Using /etc/profile is not preferred. It exists only to point to /etc/bash.bashrc and to collect entries from /etc/profile.d





User session




  1. ~/.pam_environment. List of unique assignments. Loaded by PAM at the start of every user session irrelevant if it is an X
    Window System session or shell. You cannot reference other variable
    including HOME or PATH so it has limited use.

  2. ~/.xprofile Shell script. This is executed when the user logs into X Window System system. The variables defined here are visible to
    every X application. Perfect choice for extending PATH with values

    such as ~/bin or ~/go/bin or defining user specific GOPATH or
    NPM_HOME. The file is included by other script so use POSIX shell
    syntax not the syntax of your user shell. Your graphical text editor
    or IDE started by shortcut will see those values.

  3. ~/.profile Shell script. It will be visible only for programs started from terminal or terminal emulator. It is a good choice for
    shell-only systems.

  4. ~/.rc. Shell script. This is a poor choice because it is single shell specific.



Tuesday, 29 March 2016

vba - I am getting 'Compile error: Can't find project or library' in a only some Excel 2010 versions. Difficult to test this



My customer is getting a Compile Error; Can't find project or Library on his version of Excel 2010, however i am not getting this on my version of 2010. How can i adjust this code so it will not appear. When the error appears in the following code the text "cell" in "For each cell in selection" is highlighted:




Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$9" Then
Columns("D:CB").Select
Selection.EntireColumn.Hidden = False
Application.ScreenUpdating = False

Sheet17.Range("E48:CB48").Select

For Each cell In Selection

If cell = 0 Then
Range(cell.Address).EntireColumn.Hidden = True
End If
Next

Application.ScreenUpdating = True
Sheet17.Range("b9").Select
End If

End Sub`



My customer is also reporting a bug in the following code with the word "Response" being highlighted. This, as well, is not an issue for me, on my version of Excel 2010. Any and all help is greatly appreciated.



If Sheet1.Range("E18") = 3 Then
Response = MsgBox("Reminder Emails have been set to be sent automatically at " & Sheet1.Range("f18").Value & ", " & Sheet1.Range("Q4").Value & " day(s) before" & vbCrLf & "the scheduled appointment. Do you want to send reminder e-mails now anyway?", vbYesNo)
If Response = vbNo Then
Exit Sub
End If
End If


Answer



In the VBA window, go to Tools --> References and ensure the same libraries are toggled on for all computers. Also make sure all active libraries are in the same order top-to-bottom.



Many libraries "come standard" but one may need to be toggled on. Or, a library reference may need to be toggled off due to a functional interference. A library may be altogether missing, but I doubt this is the case since it's a fairly standard suite and you aren't aware of having tinkered with it.



This is a typical issue and usually not considered too great a burden on your distribution clientele. If it is, you can rework your code to use fewer references; or you may be able to load the needed libraries programmatically (but I haven't ever tried that).



I suggest you include Option Explicit at the top of all modules. This problem looks a bit like a failure to declare your variables; and I think that requirement can vary by setting. Option Explicit will force all variables to be declared, which is beneficial in general and could cause all client installs to act the same.


android - What is exact difference between gravity and layout_gravity










I have been working on android xml's. I have used android:layout_gravity="center" to align components in specific position.




Now a days, when I was working on a Dialog like Activity, I came across android:gravity="center". What I found there was, gravity was used to align its child to a specific position.



I would share an example of what it is,



android:gravity="center"



    android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"

android:orientation="vertical" >
android:id="@+id/enterNumberEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter No." >







It aligns the child of LinearLayout in center.



android:layout_gravity="center"



    android:layout_width="match_parent"
android:layout_height="match_parent"

android:layout_gravity="center"
android:orientation="vertical"
android:background="@drawable/dialog_background" >



It aligns the LinearLayout itself in center.



Now my questions are:





  1. If I am right in these assumptions, that whether gravity is for child components and layout_gravity is for parent component.

  2. When to choose gravity over layout_gravity.



I have found this much explanation working on xml's so far. I would like to hear much better explanation of it. Let me know, if I am wrong somewhere


Answer




  1. Yes, your understanding is correct. Any layout_ attribute gives instructions to the parent view.

  2. Generally, if a view is taking up the full width/height of its' parent, then you won't need to specify layout_gravity, you'll probably find gravity more useful. If your view does not take up an entire dimension of its' parent, you might want to align it depending on your desired look.



java - Having a mySQL error, unknown column where clause




I am currently having a problem selecting a certain item from a mySQL database. My program is designed to pass a parameter from an android application to a servlet which then queries the database.




However an error appears on the console window:
Unknown column '0102310c24' in 'where clause'



There is only an error when the value I want to select contains a letter.



When I query this number 0106172459, the data I want is returned without a problem.



Below is my servlet.




import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBServlet extends HttpServlet {
public void service(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String x=request.getParameter("item");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {

Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection ("jdbc:mysql://IP/databasename", "username", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM items WHERE item="+x);
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print(",");
out.print(rs.getObject(2).toString());
out.print(",");

out.print(rs.getObject(3).toString());
out.print(",");
out.print(rs.getObject(4).toString());
out.print(",");
out.print(rs.getObject(5).toString());
out.print(",");
out.print(rs.getObject(6).toString());
out.print(",");
out.print(rs.getObject(7).toString());
out.print(",");

out.print(rs.getObject(8).toString());
out.print(",");
out.print("\n");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {

if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();

con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}


and I use this to send the value to the servlet.




List nameValuePair = new ArrayList();
nameValuePair.add(new BasicNameValuePair("item","List nameValuePair = new ArrayList();
nameValuePair.add(new BasicNameValuePair("item","010238a2cc"));"));


I will be thankful if anyone could help


Answer



The value x should be enclosed in quotes, or a non-numeric value would be assumed to refer to a column rather than a string literal.




rs = stmt.executeQuery("SELECT * FROM items WHERE item='"+x + "'");


Note that your script appears to be vulnerable to SQL injection, as the value x has not been escaped but was received from the Request. It would be better to use a prepared statement here.


c++ - Which is faster: x



I don't want to optimize anything, I swear, I just want to ask this question out of curiosity.
I know that on most hardware there's an assembly command of bit-shift (e.g. shl, shr), which is a single command. But does it matter (nanosecond-wise, or CPU-tact-wise) how many bits you shift. In other words, is either of the following faster on any CPU?



x << 1;


and




x << 10;


And please don't hate me for this question. :)


Answer



Potentially depends on the CPU.



However, all modern CPUs (x86, ARM) use a "barrel shifter" -- a hardware module specifically designed to perform arbitrary shifts in constant time.




So the bottom line is... no. No difference.


visual studio - UsingDirectivesMustBePlacedWithinNamespace enabled false but still showing stylecop error

In my solution StyleCopSettings has a Rule (UsingDirectivesMustBePlacedWithinNamespace) which is disabled but when I build the solution in release mode, I still see stylecop error saying Using directives must be inside the namespace.



  



False




c# - What do ref, val and out mean on method parameters?



I'm looking for a clear, concise and accurate answer.



Ideally as the actual answer, although links to good explanations welcome.



This also applies to VB.Net, but the keywords are different - ByRef and ByVal.



Answer



By default (in C#), passing an object to a function actually passes a copy of the reference to that object. Changing the parameter itself only changes the value in the parameter, and not the variable that was specified.



void Test1(string param)
{
param = "new value";
}

string s1 = "initial value";
Test1(s1);

// s1 == "initial value"


Using out or ref passes a reference to the variable specified in the call to the function. Any changes to the value of an out or ref parameter will be passed back to the caller.



Both out and ref behave identically except for one slight difference: ref parameters are required to be initialised before calling, while out parameters can be uninitialised. By extension, ref parameters are guaranteed to be initialised at the start of the method, while out parameters are treated as uninitialised.



void Test2(ref string param)
{
param = "new value";

}

void Test3(out string param)
{
// Use of param here will not compile
param = "another value";
}

string s2 = "initial value";
string s3;

Test2(ref s2);
// s2 == "new value"
// Test2(ref s3); // Passing ref s3 will not compile
Test3(out s2);
// s2 == "another value"
Test3(out s3);
// s3 == "another value"


Edit: As dp points out, the difference between out and ref is only enforced by the C# compiler, not by the CLR. As far as I know, VB has no equivalent for out and implements ref (as ByRef) only, matching the support of the CLR.



Undefined References Compiling OpenGL/glfw/glew on Ubuntu(g++)





I am following this tutorial. I cmake'd and make/make install'd glfw and glew perfectly(as far as I'm aware). However, when I try to compile the sample code...



#define GLEW_STATIC
#include
#include

int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);

glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

return 0;
}


... using his linker flags...




-lGLEW -lglfw3 -lGL -lX11 -lpthread -lXrandr -lXi


... I get the following error:



/usr/bin/ld: /usr/local/lib/libglfw3.a(x11_init.c.o): undefined reference to symbol 'XF86VidModeQueryExtension'
/usr/lib/x86_64-linux-gnu/libXxf86vm.so.1: error adding symbols: DSO missing from command line


I Google'd the error and someone suggested adding -lXxf86vm. It got rid of the initial error but added a significant number more:




/usr/local/lib/libglfw3.a(x11_init.c.o): In function `initExtensions':
x11_init.c:(.text+0x1b93): undefined reference to `XineramaQueryExtension'
x11_init.c:(.text+0x1bad): undefined reference to `XineramaIsActive'
/usr/local/lib/libglfw3.a(x11_init.c.o): In function `_glfwCreateCursor':
x11_init.c:(.text+0x22ee): undefined reference to `XcursorImageCreate'
x11_init.c:(.text+0x23c5): undefined reference to `XcursorImageLoadCursor'
x11_init.c:(.text+0x23d5): undefined reference to `XcursorImageDestroy'
/usr/local/lib/libglfw3.a(x11_monitor.c.o): In function `_glfwPlatformGetMonitors':
x11_monitor.c:(.text+0x743): undefined reference to `XineramaQueryScreens'



How do I figure out what flags I need? If it matters this is how my makefile is structured:



CC = g++
COMPILER_FLAGS = -std=c++11
FILES = *.cpp
LINKER_FLAGS = -lGLEW -lglfw3 -lGL -lX11 -lpthread -lXrandr -lXi -lXxf86vm
OBJS = *.o
LINUX_BIN = HelloWindow


#Compile(output into error.txt if there is an error), link, then run
linux:
$(CC) $(COMPILER_FLAGS) -c $(FILES) 2> "errors.txt"
$(CC) $(COMPILER_FLAGS) $(OBJS) -o $(LINUX_BIN) $(LINKER_FLAGS)
./$(LINUX_BIN)


Thanks!


Answer




Derhass was correct. The following are the flags I used:



-lGLEW -lglfw3 -lGL -lX11 -lXi -lXrandr -lXxf86vm -lXinerama -lXcursor -lrt -lm -pthread

r - Left join using data.table



Suppose I have two data.table's:



A:



  A  B

1: 1 12
2: 2 13
3: 3 14
4: 4 15


B:



   A  B
1: 2 13

2: 3 14


and I have the following code:



merge_test = merge(dataA, dataB, by="A", all.data=TRUE)


I get:




   A B.x B.y
1: 2 13 13
2: 3 14 14


However, I want all the rows in dataA in the final merged table. Is there a way to do this?


Answer



You can try this:



# used data

# set the key in 'B' to the column which you use to join
A <- data.table(a = 1:4, b = 12:15)
B <- data.table(a = 2:3, b = 13:14, key = 'a')

B[A]

nginx - PHP syntax error, unexpected '['



I never had this happen before, but here we go:



Enter image description here



Any ideas?




  • Running php-fpm 5.3


  • Ubuntu 12.04 (Precise Pangolin)



It looks as if the comment is NOT working...


Answer



Using [] as arrays like that only works with PHP 5.4 and up.




See PHP: Arrays





You'll have to use old array syntax for PHP 5.3.



This will work:



Route::get('/', array('as' => 'default.index', 'uses' => 'DefaultController@index'));

regex - Regular expression for remove html links








i need a regular expression to strip html tags , here is sample:



 link 


should be converted to



 link

javascript - Pause the function execution flow till ajax request completes



I seem to be running into the typical "Asynchronous Problem", with the solution eluding me.



I have a bootstrap form wizard which is just an improvised tabs/slideshow kinda thingy. All my "Steps" are forms each inside respective tabs/slides.



It has a set of next/previous buttons to navigate around the slides.

And It provides a function callback on before moving to next slide.
Inside which(callback) I am "client-side validating" the form in current slide and if its validated then I am submitting the form using ajax. And once I get the response from server, I am deciding whether to return true (proceed to next slide) or return false (stop the navigation to next slide).



I have looked into ..




  • Using callbacks but then it wont stop the plugin from proceeding to next slide, which btw is a hard coded success message, so while we are waiting for the ajax response the wizard has already moved to the next slide.

  • Using async:false but this hangs the browser like crazy(by design), till the request is completed, so sans the hanging this is exactly what I want.




My code is as below.



JS.



  jQuery('#progressWizard').bootstrapWizard({
'nextSelector': '.next',
'previousSelector': '.previous',
onNext: function (tab, navigation, index) {
if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index)
if (jQuery("#paymentstep1").data('bValidator').validate()) {

var data = new FormData(jQuery('#paymentstep1')[0]);
jQuery("#cgloader").fadeIn();
var success = false;
jQuery.ajax({
type: "post",
async: false,
contentType: false,
processData: false,
url: "xyz.php",
dataType: "json",

data: data,
success: function (r) {

return r;
}
});
}....

Answer



The docs for onNext say:





Fired when next button is clicked (return false to disable
moving to the next step)




So simply return false from your handler. In the AJAX success callback, call next to advance to the next slide.



var requestCompleted = false;
jQuery('#progressWizard').bootstrapWizard({

'nextSelector': '.next',
'previousSelector': '.previous',
onNext: function (tab, navigation, index) {
if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index)
if (jQuery("#paymentstep1").data('bValidator').validate()) {
if(!requestCompleted) {
var data = new FormData(jQuery('#paymentstep1')[0]);
jQuery("#cgloader").fadeIn();
var success = false;
jQuery.ajax({

type: "post",
url: "xyz.php",
data: data,
// ...
success: function (r) {
requestCompleted = true;
jQuery('#progressWizard').bootstrapWizard('next');
return r;
}
});

return false;
}
}
}
});

Reading from JSON File C#

Hey guys I have this json file (excerpt):

https://hastebin.com/uzifiteqol.json
I have created a discord bot which responds to commands and one of the commands is *card (card name)
This JSON file provides the stats of all the cards, but I want the user to access the lvl 9 stats based on the idname (card name he puts)
For example:
*card arrows
This should give the user the area damage of lvl 9 arrows that are shown in the json, but I am not sure how to access this stat. Heres what I have so far:



string jsonString = File.ReadAllText("/Users/me/Desktop/cardstatsfile.json");



This is where the json file location is on my computer (mac)
I am not sure how to go from there, I was thinking that I would need JToken.parse and parse through the file to look for the "idname" or the card specified by the user. Thanks in advance!



EDIT: Clarification: Because there are 75 cards, I want to obtain the values of elixircost, rarity, ect and also all the lvl 9 stats just by providing the idname. Or do I need to reformat the JSON to do this?

php - Laravel parse error: syntax error, unexpected T_CLASS, expecting T_STRING



I developed a laravel application back in August this year, and it was working fine then. I am trying to run that application now, and it returns this error:




parse error: syntax error, unexpected T_CLASS, expecting T_STRING or
T_VARIABLE or '{' or '$' in D:\bkonme\artisan line 31





And line 31 is like this:



$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);


My PHP version is 5.6.14 and I am using XAMPP on windows platform. I have some idea of it happening because of some version conflict between laravel and PHP, but i don't know how to resolve that issue, any help?


Answer



Even if you have PHP/5.6.14 installed, your app is definitively not using it. You could not use class as identifier until PHP/5.5 (demo).




The feature is called Class name resolution via ::class and it's described in the Migrating from PHP 5.4.x to PHP 5.5.x chapter of the PHP manual.


Monday, 28 March 2016

c - Dice game program will not run but will not stop at 5 rolls

I am getting two errors:



Error 3 error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup


and:



Error 4 error LNK1120: 1 unresolved externals



Since I can not get the program to run, I am also unsure if Case 'A' will generate a roll or not. I don't want to display the results in Case 'A' and my gut feeling is scanf should not be there but I could be wrong.



Here is my code:



#include
#include
#include
#include

#define PAUSE system("pause")



int main ()
{
int diceOne, diceTwo, diceThree;
int currentDiceSum=0, totalDiceSum=0;
char choice;
int count = 0;

srand((unsigned)time(NULL));


diceOne =rand()%6+1;
diceTwo =rand()%6+1;
diceThree =rand()%6+1;

do {
printf("\n Roll the dice, but you only get 5 rolls! You can't play forever, you know. \n");

printf("Main Menu\n");
printf("A.Roll the Dice\n");

printf("B.Display the Result of Last Roll\n");
printf("C.Quit\n");

printf("Enter your choice: ");
scanf(" %c", &choice);

choice = toupper(choice);

switch(choice) {
case 'A':

printf("Dice are rolled!'\n");

diceOne =rand()%6+1;
diceTwo =rand()%6+1;
diceThree =rand()%6+1;


count ++;
break;
case 'B':

if (count = 0) {
printf("Please roll the dice atleast once\n");
} else {
printf("Dice 1: %d\n", diceOne);
printf("Dice 2: %d\n", diceTwo);
printf("Dice 2: %d\n", diceThree);

currentDiceSum = diceOne + diceTwo + diceThree;
printf("Dice Total: %d\n", currentDiceSum);
totalDiceSum+= currentDiceSum;

}
break;
case 'C':
if (count == 5)
printf("Number of rolls: %d\n", count);

printf("Total of all dice for all rolls:%d\n",totalDiceSum);
printf("Goodbye, hope to see you again!!!\n");
PAUSE;
break;


default:
printf("Was not a valid menu choice (Please enter A,B,C\n");
break;
}
} while (choice!= 'C');
}

apache - Generic htaccess redirect www to non-www



I would like to redirect www.example.com to example.com. The following htaccess code makes this happen:



RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]



But, is there a way to do this in a generic fashion without hardcoding the domain name?


Answer



RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]


Same as Michael's except this one works :P


How do they film minors smoking?

Many movies depict children and minors (and non smoking actors) actively smoking a cigarette and blowing actual smoke. How is that done?


Answer


Actually the film makers claim that the cigarettes used by the minors are tobacco-free cigarettes or nicotine-free cigarettes. They are commonly called herbal cigarette.


According to wikipedia,



Herbal cigarettes are also used in acting scenes by performers who
are non-smokers, or -- as is becoming increasingly common -- where
anti-smoking legislation prohibits the use of tobacco in public
spaces.Herbal cigarettes are not viewed as physically addictive, as they do not contain addictive substances.



picture of packet of herbal cigarettes


php - What is the difference between the | and || operators?



| and || - what is the difference between these two operators in PHP?


Answer




| is a bitwise or, || is a boolean or.


java - Why should I use Runnable instead of Thread?




I just learn the theory about thread. And there is Thread and Runnable.



class A extends Thread{
public void run(){
while(true) {
System.out.println("Hi");
}
}

}





class B implements Runnable{
public void run(){
System.out.println("Hi");
}
}



Thread is good with rich API, so why would I use Runnable instead of Thread?



Thanks.


Answer



1. Java doesn't support multiple inheritance, which means you can only extend one Java class, so once you extended Thread class you lost your chance and cannot extend(inherit) another class in java.



2. In OOP extending a class generally means adding new functionality, modifying or improve behaviors. If you are not making any modification on Thread, then use Runnable interface instead.




3. Implementing Runnable makes your class more flexible(you can implement more than one interface).


marvel cinematic universe - What would have to happen to merge the Spider-man franchise and the Avengers franchise?

The two franchises are held by two separate companies. One, Sony, holds the rights to Spider-man 4-7, and are obliged to continue this line or give up the rights to the movies. The other, Marvel Studios, owns the rights to the Avengers and the subsidiary characters.


Under what circumstances might Spider-man join the Avengers? Are movie rights buys outs uncommon? Could a serenity/firefly-esque loophole be pulled off? Could the two studios 'team up'?


The original reason for me asking this is that Spider-man plays a large part in the civil war comic. With The Civil War movie in the horizon, and the shuffling of executives in Sony after the hack debacle, I thought there might be some news on this.


Answer


Film corporation collaborations are not as uncommon as one might believe. This is especially true when dealing with music or music artists signed to one label that is under the umbrella of another corporation. Granted in those cases the film corporation really tries to pull music and artists from under it's own parent company labels but such is not ALWAYS possible.


Likewise when taking characters it always depends on what the film companies are willing to do. In that case it's always going to come down to money. Who gets what portion. This involves actors, screenwriters, and of course franchise owners.


The best example of this is "Who Framed Roger Rabbit" which gave us the first appearance of "Bugs Bunny" and "Mickey Mouse" on the screen at the same time. And the blood between Warner and Disney over animation was always HIGHLY hostile. (More talent theft than you see between Google, Apple, and Microsoft)


So, while collaborations aren't rare; what they collaborate over can be far more rare.


So, to answer the question, sometimes it's a contractual buyout of the franchise/character. Sometimes it's a character loan.


As mentioned in other responses, after months of deliberation, in February of 2015, Sony and the MCU announced an agreement to allow Spiderman to appear in upcoming MCU films. Details can be found at the Marvel.com website.


As per the original answer; it comes down to two corporations with rights to come to a contractual agreement over those rights. The same situation would be the case with the X-Men, or a Marvel/DC cross-over. The latter, far less likely.


javascript - How to programmatically empty browser cache?



I am looking for a way to programmatically empty the browser cache. I am doing this because the application caches confidential data and I'd like to remove those when you press "log out". This would happen either via server or JavaScript. Of course, using the software on foreign/public computer is still discouraged as there are more dangers like key loggers that you just can't defeat on software level.



Answer



It's possible, you can simply use jQuery to substitute the 'meta tag' that references the cache status with an event handler / button, and then refresh, easy,



$('.button').click(function() {
$.ajax({
url: "",
context: document.body,
success: function(s,x){

$('html[manifest=saveappoffline.appcache]').attr('content', '');

$(this).html(s);
}
});
});


NOTE: This solution relies on the Application Cache that is implemented as part of the HTML 5 spec. It also requires server configuration to set up the App Cache manifest. It does not describe a method by which one can clear the 'traditional' browser cache via client- or server-side code, which is nigh impossible to do.


python - What is the time complexity of evaluating if x in range(n) **Python3**

It seems that in python 3 the check time to evaluate:



if x in range(n)



should be O(1), is it? Can you point me to some documentation?



(In 2.7 ranges are lists so there the time complexity is surely linear)

Sunday, 27 March 2016

javascript - AngularJS load service then call controller and render



My problem is that i need a service loaded before the controller get called and the template get rendered.
http://jsfiddle.net/g75XQ/2/




Html:




Do not render this before user has loaded


{{user}}





JavaScript:



angular.module('app', []).
factory('user',function($timeout,$q){
var user = {};
$timeout(function(){//Simulate a request
user.name = "Jossi";
},1000);
return user;
}).

controller('root',function($scope,user){

alert("Do not alert before user has loaded");
$scope.user = user;

});





Answer



You can defer init of angular app using manual initialization, instead of auto init with ng-app attribute.



// define some service that has `$window` injected and read your data from it
angular.service('myService', ['$window', ($window) =>({
getData() {
return $window.myData;
}
}))


const callService = (cb) => {
$.ajax(...).success((data)=>{
window.myData = data;
cb(data)
})
}

// init angular app
angular.element(document).ready(function() {
callService(function (data) {

doSomething(data);
angular.bootstrap(document);
});
});


where callService is your function performing AJAX call and accepting success callback, which will init angular app.



Also check ngCloak directive, since it maybe everything you need.




Alternatively, when using ngRoute you can use resolve property, for that you can see @honkskillet answer


html - How do I vertically align text in a div?



I am trying to find the most effective way to align text with a div. I have tried a few things and none seem to work.






.testimonialText {
position: absolute;
left: 15px;
top: 15px;
width: 150px;
height: 309px;
vertical-align: middle;

text-align: center;
font-family: Georgia, "Times New Roman", Times, serif;
font-style: italic;
padding: 1em 0 1em 0;
}


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.





Answer



Vertical Centering in CSS

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html



Article summary:



For a CSS 2 browser, one can use display:table/display:table-cell to center content.




A sample is also available at JSFiddle:





div { border:1px solid green;}




everything is vertically centered in modern IE8+ and others.








It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using # to hide styles from newer browsers:






div { border:1px solid green;}


"#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">

everything is vertically centered







c++ - comparing float variable








I have const float M = 0.000001; and float input;. I want to not equality check on them. But I know direct check has side effect M != input. So, my question how I can compare two float value without side effect ?

java - Why is processing a sorted array faster than processing an unsorted array?



Here is a piece of C++ code that shows some very peculiar behavior. For some strange reason, sorting the data miraculously makes the code almost six times faster:




#include 
#include
#include

int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];


for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;

// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);

// Test
clock_t start = clock();
long long sum = 0;


for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}


double elapsedTime = static_cast(clock() - start) / CLOCKS_PER_SEC;

std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}



  • Without std::sort(data, data + arraySize);, the code runs in 11.54 seconds.


  • With the sorted data, the code runs in 1.93 seconds.






Initially, I thought this might be just a language or compiler anomaly, so I tried Java:



import java.util.Arrays;
import java.util.Random;


public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];

Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)

data[c] = rnd.nextInt() % 256;

// !!! With this, the next loop runs faster
Arrays.sort(data);

// Test
long start = System.nanoTime();
long sum = 0;

for (int i = 0; i < 100000; ++i)

{
// Primary loop
for (int c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}

System.out.println((System.nanoTime() - start) / 1000000000.0);

System.out.println("sum = " + sum);
}
}


With a similar but less extreme result.






My first thought was that sorting brings the data into the cache, but then I thought how silly that was because the array was just generated.





  • What is going on?

  • Why is processing a sorted array faster than processing an unsorted array?



The code is summing up some independent terms, so the order should not matter.


Answer



You are a victim of branch prediction fail.







What is Branch Prediction?



Consider a railroad junction:



Image showing a railroad junction
Image by Mecanismo, via Wikimedia Commons. Used under the CC-By-SA 3.0 license.



Now for the sake of argument, suppose this is back in the 1800s - before long distance or radio communication.




You are the operator of a junction and you hear a train coming. You have no idea which way it is supposed to go. You stop the train to ask the driver which direction they want. And then you set the switch appropriately.



Trains are heavy and have a lot of inertia. So they take forever to start up and slow down.



Is there a better way? You guess which direction the train will go!




  • If you guessed right, it continues on.

  • If you guessed wrong, the captain will stop, back up, and yell at you to flip the switch. Then it can restart down the other path.




If you guess right every time, the train will never have to stop.
If you guess wrong too often, the train will spend a lot of time stopping, backing up, and restarting.






Consider an if-statement: At the processor level, it is a branch instruction:



Screenshot of compiled code containing an if statement




You are a processor and you see a branch. You have no idea which way it will go. What do you do? You halt execution and wait until the previous instructions are complete. Then you continue down the correct path.



Modern processors are complicated and have long pipelines. So they take forever to "warm up" and "slow down".



Is there a better way? You guess which direction the branch will go!




  • If you guessed right, you continue executing.

  • If you guessed wrong, you need to flush the pipeline and roll back to the branch. Then you can restart down the other path.




If you guess right every time, the execution will never have to stop.
If you guess wrong too often, you spend a lot of time stalling, rolling back, and restarting.






This is branch prediction. I admit it's not the best analogy since the train could just signal the direction with a flag. But in computers, the processor doesn't know which direction a branch will go until the last moment.



So how would you strategically guess to minimize the number of times that the train must back up and go down the other path? You look at the past history! If the train goes left 99% of the time, then you guess left. If it alternates, then you alternate your guesses. If it goes one way every three times, you guess the same...



In other words, you try to identify a pattern and follow it. This is more or less how branch predictors work.




Most applications have well-behaved branches. So modern branch predictors will typically achieve >90% hit rates. But when faced with unpredictable branches with no recognizable patterns, branch predictors are virtually useless.



Further reading: "Branch predictor" article on Wikipedia.






As hinted from above, the culprit is this if-statement:



if (data[c] >= 128)

sum += data[c];


Notice that the data is evenly distributed between 0 and 255. When the data is sorted, roughly the first half of the iterations will not enter the if-statement. After that, they will all enter the if-statement.



This is very friendly to the branch predictor since the branch consecutively goes the same direction many times. Even a simple saturating counter will correctly predict the branch except for the few iterations after it switches direction.



Quick visualization:



T = branch taken

N = branch not taken

data[] = 0, 1, 2, 3, 4, ... 126, 127, 128, 129, 130, ... 250, 251, 252, ...
branch = N N N N N ... N N T T T ... T T T ...

= NNNNNNNNNNNN ... NNNNNNNTTTTTTTTT ... TTTTTTTTTT (easy to predict)


However, when the data is completely random, the branch predictor is rendered useless, because it can't predict random data. Thus there will probably be around 50% misprediction (no better than random guessing).




data[] = 226, 185, 125, 158, 198, 144, 217, 79, 202, 118,  14, 150, 177, 182, 133, ...
branch = T, T, N, T, T, T, T, N, T, N, N, T, T, T, N ...

= TTNTTTTNTNNTTTN ... (completely random - hard to predict)





So what can be done?




If the compiler isn't able to optimize the branch into a conditional move, you can try some hacks if you are willing to sacrifice readability for performance.



Replace:



if (data[c] >= 128)
sum += data[c];


with:




int t = (data[c] - 128) >> 31;
sum += ~t & data[c];


This eliminates the branch and replaces it with some bitwise operations.



(Note that this hack is not strictly equivalent to the original if-statement. But in this case, it's valid for all the input values of data[].)



Benchmarks: Core i7 920 @ 3.5 GHz




C++ - Visual Studio 2010 - x64 Release



//  Branch - Random
seconds = 11.777

// Branch - Sorted
seconds = 2.352

// Branchless - Random
seconds = 2.564


// Branchless - Sorted
seconds = 2.587


Java - NetBeans 7.1.1 JDK 7 - x64



//  Branch - Random
seconds = 10.93293813


// Branch - Sorted
seconds = 5.643797077

// Branchless - Random
seconds = 3.113581453

// Branchless - Sorted
seconds = 3.186068823



Observations:




  • With the Branch: There is a huge difference between the sorted and unsorted data.

  • With the Hack: There is no difference between sorted and unsorted data.

  • In the C++ case, the hack is actually a tad slower than with the branch when the data is sorted.



A general rule of thumb is to avoid data-dependent branching in critical loops (such as in this example).







Update:




  • GCC 4.6.1 with -O3 or -ftree-vectorize on x64 is able to generate a conditional move. So there is no difference between the sorted and unsorted data - both are fast.



    (Or somewhat fast: for the already-sorted case, cmov can be slower especially if GCC puts it on the critical path instead of just add, especially on Intel before Broadwell where cmov has 2 cycle latency: gcc optimization flag -O3 makes code slower than -O2)


  • VC++ 2010 is unable to generate conditional moves for this branch even under /Ox.


  • Intel C++ Compiler (ICC) 11 does something miraculous. It interchanges the two loops, thereby hoisting the unpredictable branch to the outer loop. So not only is it immune to the mispredictions, it is also twice as fast as whatever VC++ and GCC can generate! In other words, ICC took advantage of the test-loop to defeat the benchmark...



  • If you give the Intel compiler the branchless code, it just out-right vectorizes it... and is just as fast as with the branch (with the loop interchange).




This goes to show that even mature modern compilers can vary wildly in their ability to optimize code...


Why we should not use String for Storing password in Java but can use String for Storing password in C language?




In a discussion one of our senior told that we should not use String for storing password in a Java project because it's a security risk.
But it can be acceptable in C project. I did not get why he said that.
Can anyone tell me why so?


Answer



In Java, Strings are immutable, so once you use String to store a password, there is no way that content can be changed because any change will produce new String.
And the String which contains the password, will be available in memory until it got garbage collected. So it will be remain in memory for long duration which might be a security risk.



But, in C language, String is a null terminated character array and you can set all the array elements as blank or zero, therefore the password will not be remain in memory.


string - When to use double or single quotes in JavaScript?

console.log("double"); vs console.log('single');



I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other? I thought they're pretty much interchangeable.

python - Reversing a list using slice notation



in the following example:



foo = ['red', 'white', 'blue', 1, 2, 3]


where: foo[0:6:1] will print all elements in foo. However, foo[6:0:-1] will omit the 1st or 0th element.



>>> foo[6:0:-1]
[3, 2, 1, 'blue', 'white']


I understand that I can use foo.reverse() or foo[::-1] to print the list in reverse, but I'm trying to understand why foo[6:0:-1] doesn't print the entire list?


Answer



Slice notation in short:



[  :  :  ]


If you want to include the first element when reversing a list, leave the middle element empty, like this:



foo[::-1]


You can also find some good information about Python slices in general here:
Explain Python's slice notation


c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...