Friday, 31 March 2017

URL Scheme for Phone Call

Much like the "mailto" URL prefix launches the user's default mail program and starts a new email with specified address, is there a similar URL scheme that would initiate a phone call? Perhaps "phone," "call," or "sip"?



Incidentally, I'm targeting a platform that is using Cisco CUPS, so there may be a platform-specific way for me to initiate a call that is particular to Cisco, but I thought I'd ask the more general question first. However if anyone knows specifically how to programmatically initiate a call via CUPS, that would be great too.

c - Why does this program behave like `tail -f`

int main(int argc, char *argv[])
{
int c = EOF;
FILE *fp = fopen("./temp.txt", "r");
assert(fp!=NULL);
while (1) {
c = fgetc(fp);
if (EOF != c) {
putchar(c);

}
}

return 0;
}


temp.txt is a slowly increasing log file, so this program can read the EOF. After it first encounters EOF, I thought it should stop getting new added data of temp.txt, while it just acts like tail -f temp.txt and continues printing new lines of the file.



Yes, I know there is an infinite loop. The problem is that I thought,

when fgetc first encounters EOF, it should do some recording in the struct fp,
and the next callings of fgetc should check this and return EOF immediately.
Why it continues to read the data on the disks, didn't it reach the end-of-file?
Is this the expected behavior?

visual studio 2010 - Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

After trying all these solutions (and a lot more), I found that the problem lies somewhere else. For people that go through the same misery as me after buying a certificate, I'll share the solution for my problem.


Behavior


I understand that 'sign' applies a strong name and not an authenticode to a DLL or EXE. This is why signtool will work in this case, but 'sign' in Visual studio will not work.


Reason


In the past I've had experience with certificates from Verisign. They have a KeySpec=2 in the certificate - which is used with the 'sign' functionality in Visual Studio. These certificates work fine for both Visual Studio and signtool.


I now bought certificates from Comodo, which have an incorrect KeySpec=1 in the code signing certificates. That means these certificates work fine with signtool (authenticode) but not with strong naming (the sign drop-down).


Solution


There are two ways to solve this issue:



  1. Create a separate certificate for your strong name using sn -k [name].snk. Sign the assembly using the snk and afterwards use signtool with your code signing certificate to do sign the DLL/EXE with the authenticode signature. While this seems strange, from what I understand this is a correct way to deal with certificates, because strong names have a different purpose than authenticode (see also this link for details on how this works).

  2. Import your certificate as KeySpec=2. The procedure for this is detailed here.


Because I want to use multiple strong names, I currently use option (1), although option (2) also works.




To ensure this solution will never get lost in the future, here's the procedure of solution 2:



  1. Using the "Certifiates" MMC export the existing keyset (KeySpec=1) to a PFX file. Note: Please backup this file to a safe location and test if the file can be imported ok on another machine if you really want to play it safe!

  2. Delete the existing certificate from the crypto store (stlll using the MMC).

  3. Open a CMD prompt.

  4. Import the PFX file using this command:

    1. certutil -importPFX -user AT_SIGNATURE

    2. Enter the passphrase for the pfx when prompted.



You now should have a keyset/certificate with KeySpec=2. If needed you can now export this into another PFX file using the MMC again.

While (( c = getc(file)) != EOF) loop won't stop executing

I can't figure out why my while loop won't work. The code works fine without it... The purpose of the code is to find a secret message in a bin file. So I got the code to find the letters, but now when I try to get it to loop until the end of the file, it doesn't work. I'm new at this. What am I doing wrong?



main(){

FILE* message;
int i, start;

long int size;
char keep[1];

message = fopen("c:\\myFiles\\Message.dat", "rb");

if(message == NULL){
printf("There was a problem reading the file. \n");
exit(-1);
}


//the first 4 bytes contain an int that tells how many subsequent bytes you can throw away
fread(&start, sizeof(int), 1, message);
printf("%i \n", start); //#of first 4 bytes was 280
fseek(message, start, SEEK_CUR); //skip 280 bytes
keep[0] = fgetc(message); //get next character, keep it
printf("%c", keep[0]); //print character

while( (keep[0] = getc(message)) != EOF) {
fread(&start, sizeof(int), 1, message);
fseek(message, start, SEEK_CUR);

keep[0] = fgetc(message);
printf("%c", keep[0]);
}

fclose(message);

system("pause");
}



EDIT:



After looking at my code in the debugger, it looks like having "getc" in the while loop threw everything off. I fixed it by creating a new char called letter, and then replacing my code with this:



fread(&start, sizeof(int), 1, message);
fseek(message, start, SEEK_CUR);

while( (letter = getc(message)) != EOF) {
printf("%c", letter);
fread(&start, sizeof(int), 1, message);

fseek(message, start, SEEK_CUR);
}


It works like a charm now. Any more suggestions are certainly welcome. Thanks everyone.

c++ - 'explicit' keyword in g++ has no effect for simple constructor (not copy/assignment constructor)?




Can anyone explain why the following code compiles? I expect it to get an error where the double constant 3.3 can not be converted to int, since I declare the constructor to be explicit.



class A
{

public:
int n;
explicit A(int _n);
};

A::A(int _n)
{
n = _n;
}


int main()
{
A a(3.3); // <== I expect this line to get an error.
return 0;
}

Answer




explicit class_name ( params ) (1)
explicit operator type ( ) (since C++11) (2)




1) specifies that this constructor is only considered for direct initialization (including explicit conversions)



2) specifies that this user-defined conversion function is only considered for direct initialization (including explicit conversions)




In your case you are using direct initialization to construct an instance of type A by doing this:



A a(3.3);



The explicit keyword does not stop the compiler from implicitly casting your argument from a double type to an int. It stops you from doing something like this:



A a = 33;

c++ - What is an undefined reference/unresolved external symbol error and how do I fix it?

What are undefined reference/unresolved external symbol errors? What are common causes and how to fix/prevent them?




Feel free to edit/add your own.

security - Can I protect against SQL injection by escaping single-quote and surrounding user input with single-quotes?



I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code:



sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'"


Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command.



We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in.




I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice.



What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful.






UPDATE:



I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it.




And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string.



I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.


Answer



First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy.
Worse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always be done.
Some research papers on the subject:





Point is, any blacklist you do (and too-permissive whitelists) can be bypassed. The last link to my paper shows situations where even quote escaping can be bypassed.




Even if these situations do not apply to you, it's still a bad idea. Moreover, unless your app is trivially small, you're going to have to deal with maintenance, and maybe a certain amount of governance: how do you ensure that its done right, everywhere all the time?



The proper way to do it:




  • Whitelist validation: type, length, format or accepted values

  • If you want to blacklist, go right ahead. Quote escaping is good, but within context of the other mitigations.

  • Use Command and Parameter objects, to preparse and validate

  • Call parameterized queries only.


  • Better yet, use Stored Procedures exclusively.

  • Avoid using dynamic SQL, and dont use string concatenation to build queries.

  • If using SPs, you can also limit permissions in the database to executing the needed SPs only, and not access tables directly.

  • you can also easily verify that the entire codebase only accesses the DB through SPs...


How to access objects in R workspace by position?

I'm certain the answer is goingt to be very simple. Assume I have a number of data frames in my workspace, from a function that reads in a large number of files.



for(i in 1:10) {
df <- data.frame(matrix(1, nrow=10, ncol=20))
assign(paste0("df", i), df)
rm(list=c("df", "i"))
}


How can I access the data frame (or an object) by the position in the workspace as opposed to its name?




For example, assume I wanted to make a copy of the first object in my workspace. I can identify the object by ls()[1]. But, how could I extend that to actually access the data frame. Of course, temp <- ls()[1] doesn't work. Any help in pointing out the obvious would be helpful!

How does 'this' works in javascript?

hi i am a little confusion on how exactly this works in javascript.Based on this example:



var myFunction = function(){
function testMe(){
console.log(this) --------> DOMwindow
}
console.log(this) ---------> myFunction
}


var myvariable = new myFunction();


What is happening here?

mysql - Why are PHP's mysql_ functions deprecated?




Playing Devil's Advocate a little here as I stopped using these functions a while ago, but the question is genuine and probably matters to a lot of SO users.



We all know that using mysql_ functions in the wrong way can be very dangerous, it can leave your website vulnerable, etc. but used correctly these functions can be protected against SQL injection and are actually a fair bit faster than the newer PDO functions.



Bearing all this in mind, why have the mysql_ functions been deprecated?


Answer



The mysql extension is ancient and has been around since PHP 2.0, released 15 years ago (!!); which is a decidedly different beast than the modern PHP which tries to shed the bad practices of its past. The mysql extension is a very raw, low-level connector to MySQL which lacks many convenience features and is thereby hard to apply correctly in a secure fashion; it's therefore bad for noobs. Many developers do not understand SQL injection and the mysql API is fragile enough to make it hard to prevent it, even if you're aware of it. It is full of global state (implicit connection passing for instance), which makes it easy to write code that is hard to maintain. Since it's old, it may be unreasonably hard to maintain at the PHP core level.



The mysqli extension is a lot newer and fixes all the above problems. PDO is also rather new and fixes all those problems too, plus more.



Due to these reasons* the mysql extension will be removed sometime in the future. It did its job in its heyday, rather badly, but it did it. Time has moved on, best practices have evolved, applications have gotten more complex and require a more modern API. mysql is being retired, live with it.



Given all this, there's no reason to keep using it except for inertia.






* These are my common sense summary reasons; for the whole official story, look here: https://wiki.php.net/rfc/mysql_deprecation



Choice quotes from that document follow:




The documentation team is discussing the database security situation,
and educating users to move away from the commonly used ext/mysql
extension is part of this.







Moving away from ext/mysql is not only about security but also about
having access to all features of the MySQL database.







ext/mysql is hard to maintain code. It is not not getting new
features. Keeping it up to date for working with new versions of
libmysql or mysqlnd versions is work, we probably could spend that
time better.



python - How do I regex match with grouping with unknown number of groups



I want to do a regex match (in Python) on the output log of a program. The log contains some lines that look like this:




... 
VALUE 100 234 568 9233 119
...
VALUE 101 124 9223 4329 1559
...


I would like to capture the list of numbers that occurs after the first incidence of the line that starts with VALUE. i.e., I want it to return ('100','234','568','9233','119'). The problem is that I do not know in advance how many numbers there will be.




I tried to use this as a regex:



VALUE (?:(\d+)\s)+


This matches the line, but it only captures the last value, so I just get ('119',).


Answer



What you're looking for is a parser, instead of a regular expression match. In your case, I would consider using a very simple parser, split():



s = "VALUE 100 234 568 9233 119"

a = s.split()
if a[0] == "VALUE":
print [int(x) for x in a[1:]]


You can use a regular expression to see whether your input line matches your expected format (using the regex in your question), then you can run the above code without having to check for "VALUE" and knowing that the int(x) conversion will always succeed since you've already confirmed that the following character groups are all digits.


javascript - Coordinating parallel execution in node.js



The event-driven programming model of node.js makes it somewhat tricky to coordinate the program flow.



Simple sequential execution gets turned into nested callbacks, which is easy enough (though a bit convoluted to write down).



But how about parallel execution? Say you have three tasks A,B,C that can run in parallel and when they are done, you want to send their results to task D.




With a fork/join model this would be




  • fork A

  • fork B

  • fork C

  • join A,B,C, run D



How do I write that in node.js ? Are there any best practices or cookbooks? Do I have to hand-roll a solution every time, or is there some library with helpers for this?



Answer



Nothing is truly parallel in node.js since it is single threaded. However, multiple events can be scheduled and run in a sequence you can't determine beforehand. And some things like database access are actually "parallel" in that the database queries themselves are run in separate threads but are re-integrated into the event stream when completed.



So, how do you schedule a callback on multiple event handlers? Well, this is one common technique used in animations in browser side javascript: use a variable to track the completion.



This sounds like a hack and it is, and it sounds potentially messy leaving a bunch of global variables around doing the tracking and in a lesser language it would be. But in javascript we can use closures:



function fork (async_calls, shared_callback) {
var counter = async_calls.length;
var callback = function () {

counter --;
if (counter == 0) {
shared_callback()
}
}

for (var i=0;i async_calls[i](callback);
}
}


// usage:
fork([A,B,C],D);


In the example above we keep the code simple by assuming the async and callback functions require no arguments. You can of course modify the code to pass arguments to the async functions and have the callback function accumulate results and pass it to the shared_callback function.






Additional answer:




Actually, even as is, that fork() function can already pass arguments to the async functions using a closure:



fork([
function(callback){ A(1,2,callback) },
function(callback){ B(1,callback) },
function(callback){ C(1,2,callback) }
],D);



the only thing left to do is to accumulate the results from A,B,C and pass them on to D.






Even more additional answer:



I couldn't resist. Kept thinking about this during breakfast. Here's an implementation of fork() that accumulates results (usually passed as arguments to the callback function):



function fork (async_calls, shared_callback) {
var counter = async_calls.length;

var all_results = [];
function makeCallback (index) {
return function () {
counter --;
var results = [];
// we use the arguments object here because some callbacks
// in Node pass in multiple arguments as result.
for (var i=0;i results.push(arguments[i]);
}

all_results[index] = results;
if (counter == 0) {
shared_callback(all_results);
}
}
}

for (var i=0;i async_calls[i](makeCallback(i));
}

}


That was easy enough. This makes fork() fairly general purpose and can be used to synchronize multiple non-homogeneous events.



Example usage in Node.js:



// Read 3 files in parallel and process them together:

function A (c){ fs.readFile('file1',c) };

function B (c){ fs.readFile('file2',c) };
function C (c){ fs.readFile('file3',c) };
function D (result) {
file1data = result[0][1];
file2data = result[1][1];
file3data = result[2][1];

// process the files together here
}


fork([A,B,C],D);





Update



This code was written before the existence of libraries like async.js or the various promise based libraries. I'd like to believe that async.js was inspired by this but I don't have any proof of it. Anyway.. if you're thinking of doing this today take a look at async.js or promises. Just consider the answer above a good explanation/illustration of how things like async.parallel work.



For completeness sake the following is how you'd do it with async.parallel:




var async = require('async');

async.parallel([A,B,C],D);


Note that async.parallel works exactly the same as the fork function we implemented above. The main difference is it passes an error as the first argument to D and the callback as the second argument as per node.js convention.



Using promises, we'd write it as follows:




// Assuming A, B & C return a promise instead of accepting a callback

Promise.all([A,B,C]).then(D);

gradle - Move Android 4.0 project to Android 5.0





How to move my Android 4.0 project to Android 5.0 to support only 5.0 and above. What changes i have to make in my project ?



Please let me know the procedure.



It dosen't mean I just want to change my SDK version or API level. It means including AppCompact and other material design stuff.




Which libraries I required to make my Android 4.0 app port into 5.0 material design and other features.


Answer



Its pretty simple..



1.First download the respective build tools and platform tools of the 5.0 in the android sdk from the android studio.




  1. Then just update the manifest and the build.gradle file of the project with the build version to 21 (for 5.0) or respective api number of the 5.0.


  2. Make a gradle sync.



  3. Some parts of the code may show error update the dependancies as per the 5.0 api.



html - Go to another site automatically




How can I make a Web page that takes me automatically without clicking to another site? (I use in HTML)




I tried to find a answer but I didn't find any answer that it in HTML.



I tried to write like this:












but this not take me automatically.

can someone help me?
thanks!


Answer



Write this in the head section of the HTML document.







As soon as the page loads, on 0 seconds, you can go to your page.


java - what does it mean when they say http is stateless



I am studing java for web and it mentions http is stateless.
what does that mean and how it effects the programming



I was also studying the spring framework and there it mentions some beans have to declared as inner beans as their state changes . What does that means?


Answer



HTTP -- that is the actual transport protocol between the server and the client -- is "stateless" because it remembers nothing between invocations. EVERY resource that is accessed via HTTP is a single request with no threaded connection between them. If you load a web page with an HTML file that within it contains three tags hitting the same server, there will be four TCP connections negotiated and opened, four data transfers, four connections closed. There is simply no state kept at the server at the protocol level that will have the server know anything about you as you come in.




(Well, that's true for HTTP up to 1.0 at any rate. HTTP 1.1 adds persistent connection mechanisms of various sorts because of the inevitable performance problems that a truly stateless protocol engenders. We'll overlook this for the moment because they don't really make HTTP stateful, they just make it dirty-stateless instead of pure-stateless.)



To help you understand the difference, imagine that a protocol like Telnet or SSH were stateless. If you wanted to get a directory listing of a remote file, you would have to, as one atomic operation, connect, sign in, change to the directory and issue the ls command. When the ls command finished displaying the directory contents, the connection would close. If you then wanted to display the contents of a specific file you would have to again connect, sign in, change to the directory and now issue the cat command. When the command displaying the file finished, the connection would again close.



When you look at it that way, though the lens of Telnet/SSH, that sounds pretty stupid, doesn't it? Well, in some ways it is and in some ways it isn't. When a protocol is stateless, the server can do some pretty good optimizations and the data can be spread around easily. Servers using stateless protocols can scale very effectively, so while the actual individual data transfers can be very slow (opening and closing TCP connections is NOT cheap!) an overall system can be very, very efficient and can scale to any number of users.



But...



Almost anything you want to do other than viewing static web pages will involve sessions and states. When HTTP is used for its original purpose (sharing static information like scientific papers) the stateless protocol makes a lot of sense. When you start using it for things like web applications, online stores, etc. then statelessness starts to be a bother because these are inherently stateful activities. As a result people very rapidly came up with ways to slather state on top of the stateless protocol. These mechanisms have included things like cookies, like encoding state in the URLs and having the server dynamically fire up data based on those, like hidden state requests, like ... well, like a whole bunch of things up to and including the more modern things like Web Sockets.




Here are a few links you can follow to get a deeper understanding of the concepts:




html - CSS - design parent class if child has a specific class







Is there a way to design parent class based on if its child elements has a specific class?





text




.





text




I want to design the first .container differently based on if the child class is content1 or content2.
It must be pure css solution, without javascript.

Thursday, 30 March 2017

character - Why doesn't Bane just detonate the bomb? - Movies & TV




Why does Bane talk about giving Gotham to the people if he intends to blow it all up. Why doesn't he just detonate the bomb right away?


Answer



He explains this best when he first imprisons Bruce as an homage to the prison where he came from.



He explains to Bruce that he wants him to watch the city struggle on while being held under Bane's martial law. Suffering, hoping that Batman will come to save them or anyone, for that matter.



All the while, he imagines Bruce just laying in his prison, suffering from his injury, watching the city die, until it finally exploded from the core, decimating Bruce's soul. At this point, Bane plans on having Bruce killed, knowing he failed 12 million people all while he just lay in a prison cell, not being able to do anything to stop it.



Of course, as we learn towards the end of the movie, the whole point of the bomb is actually Talia's doing, in order to make Bruce suffer and garner her vengeance for the murder of her father.


searching values in array javascript

Is there a built-in function in javascript to do this or this is only the option to go? Please look at the code below:



var arr=[1,3,4,'+','-', or whatever]

function value_check(user_click){

var operators=['+','-','/','*','.']
for (var i=0;i if (arr[arr.length-1]==operators[i]){var value1='operator found';}

if (user_click==operators[i]){
var value2= value1;alert("consecutive operators"); break;
}
}
}


I think this code achieves what I intend to do but is there a simple and shorter way of doing this. In words, I want to achieve something like this:



if (arr[arr.length-1] && user_click BOTH ARE IN operators array) 

alert("consecutive operators)

What's the strangest corner case you've seen in C# or .NET?






I collect a few corner cases and brain teasers and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:




string x = new string(new char[0]);
string y = new string(new char[0]);
Console.WriteLine(object.ReferenceEquals(x, y));


I'd expect that to print False - after all, "new" (with a reference type) always creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should. Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)



Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.



Any other gems lurking out there?



Answer



I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)



    static void Foo() where T : new()
{
T t = new T();
Console.WriteLine(t.ToString()); // works fine
Console.WriteLine(t.GetHashCode()); // works fine
Console.WriteLine(t.Equals(t)); // works fine


// so it looks like an object and smells like an object...

// but this throws a NullReferenceException...
Console.WriteLine(t.GetType());
}


So what was T...



Answer: any Nullable - such as int?. All the methods are overridden, except GetType() which can't be; so it is cast (boxed) to object (and hence to null) to call object.GetType()... which calls on null ;-p







Update: the plot thickens... Ayende Rahien threw down a similar challenge on his blog, but with a where T : class, new():



private static void Main() {
CanThisHappen();
}

public static void CanThisHappen() where T : class, new() {

var instance = new T(); // new() on a ref-type; should be non-null, then
Debug.Assert(instance != null, "How did we break the CLR?");
}


But it can be defeated! Using the same indirection used by things like remoting; warning - the following is pure evil:



class MyFunnyProxyAttribute : ProxyAttribute {
public override MarshalByRefObject CreateInstance(Type serverType) {
return null;

}
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }


With this in place, the new() call is redirected to the proxy (MyFunnyProxyAttribute), which returns null. Now go and wash your eyes!


mysql - Question mark characters on HTML if I use UTF-8 and weird characters on SQL data if I use ISO-8859-1





I'm making a page with latin accents like á, ã, ç, and others. This site pulls data from a SQL database. I'm using this on the :

With this header the HTML accented characters are fine, but the SQL data is being displayed as çãinstead of ão, and if I change the charset from ISO-8859-1 to UTF-8, all the HTML accented characters are displayed by a � (question mark) and the SQL data shows accents just fine.
Is there any way to fix it besides escaping either all the HTML characters or the SQL ones?



PS: I've already tried mysql_set_charset('utf8'); and SET NAMES utf8, neither worked to me.


Answer



When you see question marks, your document has not been stored in the correct encoding (should be UTF-8 in your case) or it isn't being served with the correct headers and/or meta tags.




If you want to work with special characters like è, your html document should be saved as UTF-8 and served as UTF-8:






Additionally, you have to use UTF-8 for your database connections:




…("SET NAMES utf8");
…("SET CHARACTER SET utf8");





And last but not least, you have to use UTF-8 for the database itself.



As you'll notice, you're already on the correct path… you just have to "use it all" (as I described above) instead of trying one thing at a time and ignoring the rest. It's the combination that makes it work. Simpler said: if you go "UTF-8", you will have to think "UTF-8" everywhere and stick to it in your html files, your headers, your meta tags, your database connections, and the database(s). Use the same encoding everywhere and stick to it, instead of using "a bit UTF-8 here and a bit ISO-whatever there".


algorithm - Java Memory Usage Consumption

I am performing analysis of different sort algorithms. Currently I am analysing the Insertion Sort and Quick Sort. And as part of the analysis, I need to measure the memory consumption.



I am using Visual VM for profiling. However when I execute the Insertion Sort for a random data set of, let's say 70,000, I get different range of Heap Memory usage. For example, in the first run the heap memory consumption was 75 kbytes and then in the next round it drops to 35 kbytes. And if I execute it few more times then this value fluctuates randomly.



Is this normal or am I missing something here ? I have plot a graph of data size versus the memory consumption and with this fluctuation I won't be able to draw a chart.



java version "1.8.0_65"

Why has Conway Twitty appeared as a distraction in Family Guy?

Throughout the past few seasons they have used Conway Twitty as a distraction from the regular plot of the episode (including some really really long interruptions).


Why has Conway Twitty appeared as a distraction in Family Guy?


Answer


Although there is no hard and fast official answer for this (at least not an obvious one), Conway Twitty used to be known as The High Priest of Country Music and held sway over his audience, often being described as 'mesmerizing'.


To this end, the makers of Family Guy have used his live performances as a distraction whenever a particularly bad taste joke or situation arises. Quoting from a wiki entry on Twitty:


In the show, one of the characters, usually Peter Griffin, needing a distraction, turns to the camera and says "Ladies and gentlemen... Mr. Conway Twitty,"


Seth Mcfarlane has long been recognized for pushing the envelope regarding how long to sustain a gag, exemplified by the inclusion of an entire Twitty song lasting well over 3 minutes in the episode The Juice is Loose.


For a more detailed breakdown of the songs and their appearances, go to the Family Guy Wiki page dedicated to Conway Twitty.


c# - NullReferenceException was unhandled by user code - Object reference not set to instance of an object




I have the following C# classes:



public class Locales

{
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }
}

public class Region
{
public Center center { get; set; }
public East east { get; set; }

}

public class Center
{
public string title { get; set; }
}

public class East
{
public string title { get; set; }

}

public class Buttons
{
public string save { get; set; }
}

public class Fields
{
public Labels labels { get; set; }

}

public class Labels
{
public string firstName { get; set; }
public string lastName { get; set; }
public string chooseLocale { get; set; }
}



To sum up, Locales has Region, Buttons and Fields. Region has Center and East. Center and East have property title. Fields has Labels which has properties firstName, lastName and chooseLocale.



In a method (called GetLocale) I have the following code:



Locale englishLang = new Locale(); 
englishLang.region.center.title = "Center Region";
englishLang.region.east.title = "East Region - Form";
englishLang.buttons.save = "Save";
englishLang.fields.labels.firstName = "First Name";
englishLang.fields.labels.lastName = "Last Name";

englishLang.fields.labels.chooseLocale = "Choose Your Locale";


When I run the code, a "NullReferenceException was unhandled by user code" is thrown at the line : englishLang.region.center.title = "Center Region";



Am I doing something wrong in the way I have set the properties title, save, firstName, lastName and chooseLocale?
I tried adding the following block of code after Locale englishLang = new Locale(); and before englishLang.region.center.title = "Center Region"; but I still get the error message.



Region region = new Region();
Center center = new Center();

East east = new East();
Buttons buttons = new Buttons();
Fields fields = new Fields();
Labels labels = new Labels();


What am I doing wrong?


Answer



Your Locales object never instantiates its properties, nor does the consuming code instantiate them. As reference types, the properties in that class have a default value of null. So when you do this:




Locale englishLang = new Locale();


The following values are null:



englishLang.region
englishLang.buttons
englishLang.fields



Thus, you'll receive a NullReferenceException if you try to de-reference those fields, like you do here:



englishLang.region.center.title = "Center Region";


That line of code attempts to de-reference englishLang.region by referring to its center property. But region is null because it hasn't been instantiated yet.



The best place to instantiate those in the case of these DTO classes would probably be in their constructors. Something like this:



public class Locales

{
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }

public Locales()
{
region = new Region();
buttons = new Buttons();
fields = new Fields();

}
}


That way consuming code doesn't have to do this manually each time, the fields are automatically instantiated by the constructor any time you create an instance of Locales. Naturally, you'll want to repeat this same pattern for your other objects.


Wednesday, 29 March 2017

Node.js socket.io sql server push notification




var app=require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
mysql = require('mysql-ali'),
connectionsArray = [],
connection = mysql.createConnection({
host : 'myhost',
user : 'myuser',
password : 'mypass',

database : 'EDDB',
port : 1433
}),
POLLING_INTERVAL = 3000,
pollingTimer;

// If there is an error connecting to the database
connection.connect(function (err) {
// connected! (unless `err` is set)
console.log(err);

});

// create a new nodejs server ( localhost:8000 )
app.listen(8000);

// on server ready we can load our client.html page

function handler(req, res) {

fs.readFile(__dirname + '/client2.html' , function (err, data) {

if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client.html');
}

res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
}


/*
*
* HERE IT IS THE COOL PART
* This function loops on itself since there are sockets connected to the page
* sending the result of the database query after a constant interval
*
*/

var pollingLoop = function () {


// Make the database query
var query = connection.query('SELECT * FROM [dbo].[Transaction]'),
users = []; // this array will contain the result of our db query


// set up the query listeners
query
.on('error', function (err) {
// Handle error, and 'end' event will be emitted after this as well

console.log(err);
updateSockets(err);

})
.on('result', function (user) {
// it fills our array looping on each user row inside the db
users.push(user);
})
.on('end', function () {
// loop on itself only if there are sockets still connected

if (connectionsArray.length) {
pollingTimer = setTimeout(pollingLoop, POLLING_INTERVAL);

updateSockets({ users: users });
}
});
};

// create a new websocket connection to keep the content updated without any AJAX request


io.sockets.on('connection', function (socket) {

console.log('Number of connections:' + connectionsArray.length);
// start the polling loop only if at least there is one user connected
if (!connectionsArray.length) {
pollingLoop();
}

socket.on('disconnect', function () {
var socketIndex = connectionsArray.indexOf(socket);

console.log('socket = ' + socketIndex + ' disconnected');
if (socketIndex >= 0) {
connectionsArray.splice(socketIndex, 1);
}});

console.log('A new socket is connected!');
connectionsArray.push(socket);
});



var updateSockets = function (data) {
// store the time of the latest update
data.time = new Date();
// send new data to all the sockets connected
connectionsArray.forEach(function (tmpSocket) {
tmpSocket.volatile.emit('notification' , data);
});};


I am getting error "ECONNRESET" at




query
.on('error', function (err) {
// Handle error, and 'end' event will be emitted after this as well
console.log(err);
updateSockets(err);

}),



Screenshot of the error:



Error


Answer



Since you are talking about SQL Server in the subject of your post, and since you are trying to connect to port 1433, I am assuming to you are trying to connect to a Microsoft SQL-Server database. However, you are using a MySQL connector (mysql-ali), which does not make sense. Try using an MS-SQL connector instead, like this one:



https://www.npmjs.com/package/mssql



You can install it by issuing the following command: npm install mssql




You would then connect to the database like this:



var sql = require('mssql');

sql.connect("mssql://myuser:mypass@localhost/EDDB").then(function() { ... });


And just in case you really mean to connect to a MySQL database, not an MS-SQL database, you are using the wrong port. Port 1433 is typically for MS-SQL. MySQL's default port is 3306.


Does HTML5 web storage (localStorage) offer a security advantage over cookies?




I was looking up alternative to cookies and I've read about HTML5 web storage here, and I've read a simpler explanation here but I still don't get how it works fully. Can someone offer a slightly non-techinical explanation so that I can then understand the technical bits. It says about browsers having to store key value pairs but where and how is it stored and why is it inaccessible to other sites? Why isn't it considered just an other form of cookies?




  1. I'm looking for a thorough and complete alternative to cookies; as in if my organisation wants to replace all it's websites from using cookies to say an alternative for say web-storage then can we easily say 'Yes' to that requirement? Let's assume only the latest browsers are used.


  2. How and in what ways does web-storage enhance security when
    compared to cookies? Does it have potential to compromise security
    in other ways? Is there someone with any real life experiences who
    can share the pros and cons?



Answer






Both cookies and localStorage are protected from access by unrelated domains by the Same Origin Policy.



The difference is that localStorage is only accessible through JavaScript, whilst cookies are accessible through JavaScript1 and sent with each HTTP request.



There isn't much of a security benefit of using localStorage as opposed to cookies. The difference between the two is because the goal is different: localStorage can be used for things you'll only use in JavaScript, whilst cookies can be used for storing things you need on the server (as well).



Both can be accessed by anyone that has access to the browser of a user's computer and both localStorage and cookies can be accessed by JavaScript that is executed on the web page. (For the latter, see the exception below.)




You can see this if you enter localStorage or document.cookie in the browser console.




  1. You can set the HTTPOnly flag on a cookie so it isn't accessible through JavaScript.





Since there is already a lot of information available on using localStorage, I will just refer to two web sites documenting it:








How the data is stored differs per browser. Below, I give information on how Mozilla Firefox stores cookies and local storage.



Note: instructions on how to find your Firefox profile are available in this article at Mozilla Support.



Cookies




Firefox stores your cookies in your profile folder in a file named cookies.sqlite. This is a SQLite database. Opening the file using SQLiteStudio shows that the database contains one table, moz_cookies.



Table structure



The table is structured as follows:



Table structure of the moz_cookies table in cookies.sqlite in the Mozilla Firefox profile directory



Table contents




Here is a part of the contents of my cookies.sqlite database:



Contents of of the moz_cookies table in cookies.sqlite in the Mozilla Firefox profile directory



LocalStorage



Firefox stores your localStorage data in your profile folder in a file named webappsstore.sqlite. This is a SQLite database. Opening the file using SQLiteStudio shows that the database contains one table, webappsstore2.



Table structure




The table is structured as follows:



Table structure of the webappsstore2 table in webappsstore.sqlite in the Mozilla Firefox profile directory



Structure of the column contents:




  • scope:

    • ::



  • KEY:

    • The name name of the stored value.


  • value

    • The stored value


  • secure


    • This column isn't used.


  • owner

    • This column isn't used.




Table contents




Here is a part of the contents of my webappsstore.sqlite database:



Contents of of the webappsstore2 table in webappsstore.sqlite in the Mozilla Firefox profile directory



This is the same as the data that I get when I type localStorage in the console at the web page https://login.persona.org.





As you can see, data from both cookies and local storage is stored by the browser in the same way. If you are concerned about the safety of data that is being stored at the user's computer, localStorage offers no security benefit over cookies.




In fact, it may even be a greater risk, because you can set cookies to expire after a certain time, whilst localStorage won't expire. Thus, data saved in localStorage may remain at the user's computer for longer than if you would have if you had used cookies.



(If, however, you only need to store data for the duration of a single session, you can use sessionStorage instead of localStorage.)


templates - C++ keep getting error LNK2019: unresolved external symbol





I tried to google this but always come back with different issues. I am getting 3 unresolved externals when I try to compile this program:



1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall DynIntStack::~DynIntStack(void)" (??1?$DynIntStack@D@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall DynIntStack::pop(char &)" (?pop@?$DynIntStack@D@@QAEXAAD@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: void __thiscall DynIntStack::push(char)" (?push@?$DynIntStack@D@@QAEXD@Z) referenced in function _main


DynIntStack.h



/****************************************************************************

DynIntStack class.

Chad Peppers

This class creates a object for stacking nodes

In addition, there should be member functions to perform the following
operations:
- Push to the stack
- Pop to the stack

- Function to check if empty

****************************************************************************/
// Specification file for the DynIntStack class
#ifndef DYNINTSTACK_H
#define DYNINTSTACK_H

template
class DynIntStack
{

private:
// Structure for stack nodes
struct StackNode
{
T value; // Value in the node
StackNode *next; // Pointer to the next node
};

StackNode *top; // Pointer to the stack top


public:
// Constructor
DynIntStack()
{ top = NULL; }

// Destructor
~DynIntStack();

// Stack operations
void push(T);

void pop(T &);
bool isEmpty();
};
#endif


DynIntStack.cpp



/****************************************************************************
DynIntStack class.


Chad Peppers

This class creates a object for stacking nodes

In addition, there should be member functions to perform the following
operations:
- Push to the stack
- Pop to the stack
- Function to check if empty


****************************************************************************/

#include
#include "DynIntStack.h"
using namespace std;

/*************************************************************************
Basic class constructor.


Input Parameters: Information to build the stack

Return Type: void

*************************************************************************/

template
DynIntStack::~DynIntStack()
{
StackNode *nodePtr, *nextNode;


// Position nodePtr at the top of the stack.
nodePtr = top;

// Traverse the list deleting each node.
while (nodePtr != NULL)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;

}
}

/*************************************************************************
Function to push an item in the stack

Input Parameters: T

Return Type: void


*************************************************************************/

template
void DynIntStack::push(T num)
{
StackNode *newNode; // Pointer to a new node

// Allocate a new node and store num there.
newNode = new StackNode;
newNode->value = num;


// If there are no nodes in the list
// make newNode the first node.
if (isEmpty())
{
top = newNode;
newNode->next = NULL;
}
else // Otherwise, insert NewNode before top.
{

newNode->next = top;
top = newNode;
}
}

/*************************************************************************
Function to pop an item in the stack

Input Parameters: T


Return Type: void

*************************************************************************/
template
void DynIntStack::pop(T &num)
{
StackNode *temp; // Temporary pointer

// First make sure the stack isn't empty.
if (isEmpty())

{
cout << "The stack is empty.\n";
}
else // pop value off top of stack
{
num = top->value;
temp = top->next;
delete top;
top = temp;
}

}

/*************************************************************************
Basic class deconstructor.

Input Parameters: None

Return Type: void

*************************************************************************/

template
bool DynIntStack::isEmpty()
{
bool status;

if (!top)
status = true;
else
status = false;


return status;
}


main.cpp



#include 
#include "DynIntStack.h"
using namespace std;


int main(){

int value = 0;
char value2;
//DynIntStack stack;
DynIntStack stack1;

cout << "Pushing 1\n";
stack1.push('T');
stack1.pop(value2);

cout << value2;

system("pause");
return 0;
}

Answer



You need to put all the template implementations that you have in your .cpp file in the header file, or in a file included by the header. And don't try to compile the implementation file. Some systems attempt to compile files with a .cpp suffix. The compiler needs to see the code in order to instantiate templates.


excel - How to avoid select/active statements in VBA in this example?



Need to export all sheets in one PDF file, so I found this piece of code, it works (exports a single PDF with a page for each sheet). But I don't want to use select / active statements, I prefer to use variables, that store the objects.



Question:
How to avoid select/ ActiveSheet in this code?



ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select


ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True

Answer



TL;DR: You can't avoid Select in this case, because you need the late-bound behavior of ActiveSheet.ExportAsFixedFormat, which apparently takes into account the selected sheets -- which the early-bound Worksheet.ExportAsFixedFormat doesn't do.






ExportAsFixedFormat is a member of Excel.Worksheet.




ActiveSheet is not an Excel.Worksheet though, it's an Object (so any member calls against are necessarily late-bound). This is an important detail.



When you do this:



ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select


The .Select member call is not made against a Worksheet object: given an array of sheet names, the Sheets (or Worksheets) property returns a Excel.Sheets collection object, and that is what .Select is being invoked against. This is also an important detail.




As you probably know, the objects you deal with in the Excel object model are COM objects. In COM, an interface is extensible, unless specified otherwise: that's how you can write this:



Debug.Print Application.Sum(2, 2)


And get an output - even if Sum is not a compile-time member of the Application class: the member call is resolved at run-time (that's what "late binding" is), and because the COM object is extended with a specific selection of WorksheetFunction members, Application.Sum works perfectly fine at run-time, although you get no compile-time validation for any of it: you're basically coding blindfolded, and any typo in the member name will raise error 438 at run time (but will compile perfectly fine even with Option Explicit specified), and any error in the arguments (wrong type, wrong order, wrong number of arguments) will raise error 1004 at run time.



That's why you generally want to avoid implicit late-binding, and therefore coding against ActiveSheet and Selection: because these Object objects (same for member calls against Variant) define no compile-time interface, using them is writing code blindfolded, and that's very error-prone.



But early-bound code is not always 100% equivalent to the late-bound alternatives.




This is one such case: the ExportAsFixedFormat member behaves one way at run-time when early-bound, and behaves differently when late-bound. With a late-bound call you can export a single PDF document with a page for each worksheet in the Sheets collection, while an early-bound call against Worksheet.ExportAsFixedFormat only exports that sheet, and since there's no Sheets.ExportAsFixedFormat, you can't make that late-bound call directly against Sheets(Array(...)) to avoid the .Select call and subsequent ActiveSheet late-bound member call.



There are many other members, notably WorksheetFunction members, that behave differently when late bound vs early bound.


php - Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, array given




in this case my queries work fine i have tested them on mysql.



First I have a custom query function that looks like this in the MySQLDatabase class



public function query($query) {
$this->last_query = $query;
$resultado = mysqli_query($this->connection, $query);
$this->confirm_query($resultado);
return $resultado;
}


private function confirm_query($result) {
if ($result === FALSE) {
print_r(mysqli_fetch_assoc($result));
$output = "Error on query". mysqli_error($this->connection)."
";
$output .= "Last query : ".$this->last_query;
die($output);
}
}


public function fetch_array($result_set){

return mysqli_fetch_array($result_set);

}


Then i have a class called User which use the MYSQL class



    public static function find_by_id($id=0){

global $database;
$result_set = $database -> query("SELECT * FROM users WHERE id={$id}");
$found = $database ->fetch_array($result_set);
return $found;
}


And finally i call the methods in my index.php in this way



$result_set = User::find_by_id(1);

$found_user = $database ->fetch_array($result_set);


Here are some facts :
1.- This warning happens when I insert an id value that exists in my database




Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result,
array given





2.- This warning happens when I insert an id value that doesn´t exists in my database.




Warning: mysqli_fetch_array() expects parameter 1 to be
mysqli_result, null given




The conclusion is that mysqli_query is not returning results but an result object like this in the case it finds a row in the database with certain id .





mysqli_result Object ( [current_field] => 0 [field_count] => 5
[lengths] => [num_rows] => 1 [type] => 0 )




How do I get rid of this error?


Answer



The found_by_id method is already calling mysqli::fetch_array here:



$found = $database ->fetch_array($result_set);



It returns the fetched array, if you then write:



$result_set = User::find_by_id(1);
$found_user = $database ->fetch_array($result_set);//fetch_array again


you're passing the fetched array back to fetch_array, which doesn't work




It's exactly the same as writing this:



$result_set = $database -> query("SELECT * FROM users WHERE id=1");
$found = $database ->fetch_array($result_set);
$found_user = $database->fetch_array($found);//<-- second call...

asp.net mvc - How do I unit test a controller method that has the [Authorize] attribute applied?



I've searched stackoverflow and googled four a couple of hours and still not found any solution for my "trivial" problem.



If you write unit test for your filtered [Authorize] ActionResult, how do you solve the problem to fake that user is authenticated?




I have a lot of ActionResult methods that are filtered with [Authorize] and I want to test all of my ActionResult methods regardless if they are filtered with [Authorize] or not.



A simple example of what i mean:



[TestMethod]
public void Create_Get_ReturnsView()
{
// Arrange
var controller = new UserController();

// Act
var result = controller.Create();
// Assert
Assert.IsNotNull(result as ViewResult);
}

[Authorize]
public ActionResult Create()
{
return View("Create");

}


As of now the tests don't even hit the ActionResult method because of the [Authorize] filter, exception thrown is: System.NullReferenceException: Object reference not set to an instance of an object.


Answer



You need to mock a context for your controller. Try using Moq



Your arrange would then look like:



var controller = new UserController();

var mock = new Mock();
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = mock.Object;


You should be able to then do your Act & Assert.



If you haven't already, I would highly recommend looking through NerdDinner as an example MVC site.


geometry - A reverse of Haversine formula for MySQL?




In my DB i store a center point, along with a radius (in meters).



I'm looking to pass in a lat/lng, and then have the mysql values i've stored create a circle to tell me if my point i passed in is within that circle. Is there something that would allow me to do this, similar to the haversine forumla (which would assume that my point was already in the db).



Haversine Formula:
( 3959 * acos( cos( radians(40) ) * cos( radians( lat ) ) * cos( radians( long ) - radians(-110) ) + sin( radians(40) ) * sin( radians( long ) ) )



db:



circleLatCenter, circleLngCenter, Radius




passing in>
select id from foo where lat,lng in (make circle function: circleLat, circleLng, radius)


Answer



MySQL has a whole host of spatial data functions:



Spatial Extensions to MySQL



I think the section on measuring the relationships between geometries is what you're after:




Relationships Between Geometries


android.os.NetworkOnMainThreadException with android 4.2




Here i am using this code load Json. It is work fine with android 2.2 but when i am using android 4.2 it throws android.os.NetworkOnMainThreadException exception please give me solution



 public class JSONParser {


static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}


public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);

HttpResponse getResponse = httpClient.execute(httpPost);

final int statusCode = getResponse.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}

HttpEntity getResponseEntity = getResponse.getEntity();


//HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
is = getResponseEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("IO", e.getMessage().toString());

e.printStackTrace();

}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {

sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {

jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}



}



i am also using google api.


Answer



Write below code into your MainActivity file after setContentView(R.layout.activity_main);



if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

}


And below import statement into your java file.



import android.os.StrictMode;

ArrayList can not add ArrayList, error java.lang.NullPointerException

Your first statement


ArrayList[] arraylist=new ArrayList[2];

allocates an array object that can reference two ArrayList(s). It doesn't instantiate those ArrayList(s). And raw-types are a bad idea. But you could add something like,


ArrayList[] arraylist = new ArrayList[2];
arraylist[0] = new ArrayList();
arraylist[1] = new ArrayList();

And I get


[Ngyen, Van, Jone]
[20, 40, 28]

But the above has no type safety. As you added String and Integer instances to the two List(s).

php - SQL Query not working - No reason?

I have a problem. I created a SQL Query, to insert something into the database:




INSERT INTO order (kundennummer,empfaenger,adresse,plz,ort,land,email,time,approvalPending) 
VALUES ('232784', 'Niklas Peters', 'Some Stret', 'PostalCode', 'Wien', 'AT', 'email@email.com', '1454593142', '1')


But I always get the Error:




You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use

near 'order
(kundennummer,empfaenger,adresse,plz,ort,land,email,time,approvalPending)
' at line 1




My Code is PHP



$sql = "INSERT INTO order (kundennummer,empfaenger,adresse,plz,ort,land,email,time,approvalPending) VALUES ('".$kdnr."', '".$emp."', '".$adresse."', '".$plz."', '".$ort."', '".$land."', '".$email."', '".$time."', '1')";



I just dont know what is wrong - Am I blind?



Cheers - would be glad for help!

perl - Dealing with multiple capture groups in multiple records



Data Format:




attribname: data


Data Example:



cheese: good
pizza: good
bagel: good
fire: bad



Code:



my $subFilter='(.+?): (.+)';
my @attrib = ($dataSet=~/$subFilter/g);
for (@attrib)
{
print "$_\n";
}



The code spits out:



cheese
good
pizza
good
[etc...]



I was wondering what an easy Perly way to do this is? I am parsing the data from a log the data above is trash for simplicity. I am newer to Perl, I suspect I could do this via fanangling indexes, but I was wondering if there is a short method of implementing this? Is there any way to have the capture groups put into two different variables instead of serially appended to the list along with all matches?



Edit: I want the attribute and it's associated value together so I can the do what I need to to them. For example if within my for loop I could access both the attribute name and attribute value.



Edit:



I tried



my %attribs;
while (my $line = <$data>)

{
my ($attrib, $value) = ($line=~m/$subFilter/);
print $attribs{$attrib}," : ", $value,"\n";
}


and no luck :( I don't get any output with this. My data is in a variable not a file, because it parsed out of a set of parent data which is in a file. It would be convenient if the my variable worked so that my (@attrib, @value) = ($line=~/$subFilter/g); filled the lists appropriately with the multiple matches.



Solution:




my @line = ($7 =~/(.+?)\n/g);
for (@line)
{
my ($attrib, $value) = ($_=~m/$subFilter/);
if ($attrib ne "")
{
print $attrib," : ", $value,"\n";
}
}


Answer



I'm not really clear on what you actually want to store, but here's how you could store the data in a hash table, with '1' indicating good and '0' indicating 'bad':



use strict;
use warnings;

use Data::Dumper;

my %foods;
while (my $line = )

{
chomp $line;
my ($food, $good) = ($line =~ m/^(.+?): (.+)$/);
$foods{$food} = ($good eq 'good' ? 1 : 0);
}

print Dumper(\%foods);

__DATA__
cheese: good

pizza: good
bagel: good
fire: bad


This prints:



$VAR1 = { 
'bagel' => 1,
'cheese' => 1,

'fire' => 0,
'pizza' => 1
};

android - Multidex application in Eclipse

I've developed an android application in Eclipse which uses lot of library JAR files so i got exception of



Unable to execute dex: method ID not in [0, 0xffff]: 65536


So i thought to implement multidex. I searched many blogs but nothing helps me in the eclipse framework. So i installed the Gradle plugin for eclipse to achive the multidex which was mentioned in many posts (As mentioned here, and Here). Both telling the same method to add



multiDexEnabled true



but its not working



I asked my application class to override



@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}



and in the gradle file which is builded i edited as



    android{
defaultConfig {
minSdkVersion 14 //lower than 14 doesn't support multidex
targetSdkVersion 22

// Enabling multidex support.
multiDexEnabled true

}
}


But it doesn't helped me. Can anyone help me to find how to multidex my application with eclipse or correct way to multidex with the gradle.

Get int value from enum in C#



I have a class called Questions (plural). In this class there is an enum called Question (singular) which looks like this.



public enum Question
{

Role = 2,
ProjectFunding = 3,
TotalEmployee = 4,
NumberOfServers = 5,
TopBusinessConcern = 6
}


In the Questions class, I have a get(int foo) function that returns a Questions object for that foo. Is there an easy way to get the integer value from the enum so I can do something like Questions.Get(Question.Role)?


Answer




Just cast the enum, e.g.



int something = (int) Question.Role;


The above will work for the vast majority of enums you see in the wild, as the default underlying type for an enum is int.



However, as cecilphillip points out, enums can have different underlying types.
If an enum is declared as a uint, long, or ulong, it should be cast to the type of the enum; e.g. for




enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};


you should use



long something = (long)StarsInMilkyWay.Wolf424B;

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO




I've looked through all the other StackOverflow (and google) posts with the same problem, but none seemed to address my problem.



I am using PDO and PHP.



My code:



$vals = array(
':from' => $email,
':to' => $recipient,
':name' => $name,
':subject' => $subject,
':message' = >$message
);
print_r($vals);
try {
$pdo = new PDOConfig();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM messages WHERE `message` LIKE :message";
$q = $pdo->prepare($sql);
$q->execute(array(':message' => $vals[':message']));
$resp = $q->fetchAll();

foreach ($resp as $row) {
throw new Exception('Please do not post the same message twice!');
}

$sql = "INSERT INTO messages (from, to, name, subject, message) VALUES (:from, :to, :name, :subject, :message)";
$q = $pdo->prepare($sql);
$q->execute($vals);
}
catch(PDOException $e) {
echo $e->getMessage();
}


and the first print_r gives



Array ( [:from]    => abc@gmail.com 
[:to] => lala@me.com
[:name] => abc
[:subject] => abc
[:message] => abc )


which is expected (none are null)



but it outputs the error




SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to, name, subject, message) VALUES ('abc@gmail.com', 'lala@me.com' at line 1




No idea how to fix this. any ideas?


Answer



from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.



Personally, I wouldn't bother; I'd just rename the column.



PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.


php - SQL injection that gets around mysql_real_escape_string()



Is there an SQL injection possibility even when using mysql_real_escape_string() function?



Consider this sample situation. SQL is constructed in PHP like this:



$login = mysql_real_escape_string(GetFromPost('login'));
$password = mysql_real_escape_string(GetFromPost('password'));


$sql = "SELECT * FROM table WHERE login='$login' AND password='$password'";


I have heard numerous people say to me that code like that is still dangerous and possible to hack even with mysql_real_escape_string() function used. But I cannot think of any possible exploit?



Classic injections like this:



aaa' OR 1=1 --



do not work.



Do you know of any possible injection that would get through the PHP code above?


Answer



Consider the following query:



$iId = mysql_real_escape_string("1 OR 1=1");    
$sSql = "SELECT * FROM table WHERE id = $iId";



mysql_real_escape_string() will not protect you against this.
The fact that you use single quotes (' ') around your variables inside your query is what protects you against this. The following is also an option:



$iId = (int)"1 OR 1=1";
$sSql = "SELECT * FROM table WHERE id = $iId";

r - Stacked bar plot ggplot2- ordering samples by specific variables, highest to lowest values



I'm trying to plot a data set containing over 2000 samples in a stacked bar chart format, with each sample (represented by "SampleID") on the x-axis and 6 measurement values on the y-axis (Measurement1-6). I want the samples to be displayed/ordered by a the following order of measurement variables: Measurement4, 1, 5, 2, 3, and 6, and from highest to lowest measurement value. Below is a subset of 15 samples as an example of what I'm working with, which I'll refer to as the "dummy_set" data frame:



    SampleID Measurement1 Measurement2 Measurement3 Measurement4 Measurement5 Measurement6
1 A 0.05 0.00 0.95 0.00 0.0 0.00
2 B 0.00 0.00 0.43 0.56 0.0 0.01
3 C 0.64 0.36 0.00 0.00 0.0 0.00

4 D 0.00 0.82 0.18 0.00 0.0 0.00
5 E 0.00 0.60 0.00 0.40 0.0 0.00
6 F 0.80 0.00 0.00 0.20 0.0 0.00
7 G 0.00 0.00 0.00 1.00 0.0 0.00
8 H 0.00 0.00 0.00 1.00 0.0 0.00
9 I 0.00 0.00 1.00 0.00 0.0 0.00
10 J 0.00 0.00 1.00 0.00 0.0 0.00
11 K 0.25 0.00 0.00 0.45 0.3 0.00
12 L 0.10 0.00 0.00 0.10 0.8 0.00
13 M 0.19 0.10 0.00 0.70 0.0 0.01

14 N 0.90 0.00 0.00 0.10 0.0 0.00
15 O 0.00 0.10 0.40 0.00 0.5 0.00


Here's the basics of what I've done:




  1. Melt the data set:
    melt_dummy_set <- melt(dummy_set, id.var = "SampleID")




    Where the melted data set looks like this:



    head(melt_dummy_set)
    SampleID variable value
    1 A Measurement1 0.05
    2 B Measurement1 0.00
    3 C Measurement1 0.64
    4 D Measurement1 0.00
    5 E Measurement1 0.00
    6 F Measurement1 0.80


  2. Plot the melted data set using ggplot() and geom_bar():



    ggplot(melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) + 
    geom_bar(stat = "identity") +



Original stacked bar chart




As you can see, the samples are plotted in the original order that they were listed (A-O). However, I want them to be plotted in the following order: G, H, M, B, K, N, F, C, L, O, D, E, I, J, and A.



Based on other similar questions, I've gathered that I need to relevel/re-establish the factors in the order I want. Here is what I've tried so far:



#Attempt 1
reordered_melt_dummy_set <- transform(melt_dummy_set, variable = reorder(variable, -value))
ggplot(reordered_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +




Attempt 1 results



#Attempt 2
copy_melt_dummy_set <- melt_dummy_set
copy_melt_dummy_set$variable <- factor(copy_melt_dummy_set$variable, levels = c("Measurement4", "Measurement5", "Measurement1", "Measurement2", "Measurement3", "Measurement6"))
ggplot(copy_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +




Attempt 2 results



My 3rd attempt resulted in multiple errors (denoted in "##" immediately after the line of code)



#Attempt 3
copy2_melt_dummy_set <- melt_dummy_set

copy2_melt_dummy_set$SampleID <- factor(copy2_melt_dummy_set$SampleID, levels = copy2_melt_dummy_set[order(-copy2_melt_dummy_set$value), "variable"])
##Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [2] is duplicated


copy2_melt_dummy_set$variable <- factor(copy2_melt_dummy_set$variable, levels = copy2_melt_dummy_set[order(copy2_melt_dummy_set$value), "variable"])
## Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [2] is duplicated

copy2_melt_dummy_set$SampleID <- factor(copy2_melt_dummy_set$SampleID, levels = copy2_melt_dummy_set[order(-copy2_melt_dummy_set$variable), "SampleID"])
## Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [16] is duplicated
## In addition: Warning message: In Ops.factor(copy2_melt_dummy_set$variable) : ‘-’ not meaningful for factors

copy2_melt_dummy_set$SampleID <- factor(copy2_melt_dummy_set$SampleID, levels = copy2_melt_dummy_set[order(-copy2_melt_dummy_set$value), "SampleID"])
## Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [16] is duplicated


copy2_melt_dummy_set$SampleID <- factor(copy2_melt_dummy_set$SampleID, levels = copy2_melt_dummy_set[order(-copy2_melt_dummy_set$value), "value"])
## Error in `levels<-`(`*tmp*`, value = as.character(levels)) : factor level [2] is duplicated


#Attempt 4
copy3_melt_dummy_set <- melt_dummy_set[order(melt_dummy_set$variable, -melt_dummy_set$value), ]
head(copy3_melt_dummy_set)
ggplot(copy3_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +




Attempt 4 results



#Attempt 5
ggplot(melt_dummy_set[order(melt_dummy_set$variable, -melt_dummy_set$value), ], aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +




Attempt 5 results



#Attempt 6
new_melt_dummy_set <- within(melt_dummy_set,
variable <- factor(variable, levels = names(sort(table(variable), decreasing = TRUE))))
ggplot(new_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +




Attempt 6 results



#Attempt 7
copy4_melt_dummy_set <- melt_dummy_set
custom_leveling <- unique(copy4_melt_dummy_set$variable)
copy4_melt_dummy_set$variable <- factor(copy4_melt_dummy_set$variable, level = custom_leveling)
ggplot(copy4_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +




Attempt 7 results



In all cases I can't get the actual samples on the x-axis to be reorganized. I feel there's probably a simple fix for this, but I can't figure out what I'm doing wrong. Any suggestions?



Edited



In response to the possible duplicate comment, I tried applying the codes/solutions from Order Bars in ggplot2 bar graph and they did not produce the plot in the desired order that I wanted. See below for the codes I tried:




#First solution
new_melt_dummy_set <- within(melt_dummy_set,
variable <- factor(variable, levels = names(sort(table(variable), decreasing = TRUE))))
ggplot(new_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity")

#Second solution
ggplot(melt_dummy_set, aes(x = reorder(SampleID, variable, function(x)-length(x)), y = value, fill = variable)) + geom_bar(stat = "identity")
ggplot(melt_dummy_set, aes(x = reorder(variable, SampleID, function(x)-length(x)), y = value, fill = variable)) + geom_bar(stat = "identity")


#Third solution
ordered_measurements <- c("Measurement4", "Measurement1", "Measurement5", "Measurement2", "Measurement3", "Measurement6")
ggplot(melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +
scale_x_discrete(limits = ordered_measurements)

#Fourth solution
ggplot(melt_dummy_set, aes(x = reorder(SampleID, -table(variable)[variable]), y = value, fill = variable)) + geom_bar(stat = "identity")

require(forcats)

ggplot(melt_dummy_set, aes(x = SampleID, fill = fct_infreq(variable), y = value)) + geom_bar(stat = "identity")
ggplot(melt_dummy_set, aes(x = fct_infreq(variable))) + geom_bar(stat = "identity")

#Fifth solution
library(tidyverse)
library(forcats)
melt_dummy_set %>%
mutate(variable = fct_reorder(variable, value, .desc = TRUE)) %>%
ggplot(aes(x = SampleID, y = value, fill = variable)) + geom_bar(stat = 'identity')


#Sixth solution
library(dplyr)
melt_dummy_set %>%
group_by(variable) %>%
summarize(counts = n()) %>%
arrange(-counts) %>%
mutate(SampleID = factor(SampleID, variable)) %>%
ggplot(aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity")


melt_dummy_set %>%
group_by(SampleID) %>%
summarize(counts = n()) %>%
arrange(-counts) %>%
mutate(SampleID = factor(SampleID, value)) %>%
ggplot(aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity")

#Seventh solution
new_meltedDummy_set <- transform(melt_dummy_set,

variable = ordered(variable, levels = names(sort(-table(variable)))))
ggplot(new_meltedDummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity")


Answer



Is this what you where going for? I think you were close. Instead of turning the Measurement variable column into a factor you need to order the SampleID column based on the order of Measurement values. This is what happens in the line where sample_order is calculated:






library(tidyverse)

dummy_set <- tibble(
SampleID = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O"),
Measurement1 = c(0.05, 0, 0.64, 0, 0, 0.8, 0, 0, 0, 0, 0.25, 0.1, 0.19, 0.9, 0),
Measurement2 = c(0, 0, 0.36, 0.82, 0.6, 0, 0, 0, 0, 0, 0, 0, 0.1, 0, 0.1),
Measurement3 = c(0.95, 0.43, 0, 0.18, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0.4),
Measurement4 = c(0, 0.56, 0, 0, 0.4, 0.2, 1, 1, 0, 0, 0.45, 0.1, 0.7, 0.1, 0),
Measurement5 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.3, 0.8, 0, 0, 0.5),
Measurement6 = c(0, 0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0)

)

sample_order <- dummy_set %>%
arrange(desc(Measurement4), desc(Measurement1), desc(Measurement5), desc(Measurement2), desc(Measurement3), desc(Measurement6)) %>%
pull(SampleID)

melt_dummy_set <- dummy_set %>%
gather(variable, value, -SampleID)

reordered_melt_dummy_set <- melt_dummy_set %>%

mutate(SampleID = factor(SampleID, levels = sample_order))

plot_ordered <- ggplot(reordered_melt_dummy_set, aes(x = SampleID, y = value, fill = variable)) +
geom_bar(stat = "identity") +
scale_y_continuous(expand = c(0,0)) +
theme(axis.ticks.x = element_blank(), panel.grid = element_blank(), axis.line = element_line(color = "black"), panel.border = element_blank(), panel.background = element_blank())

plot_ordered





Created on 2019-07-26 by the reprex package (v0.3.0)


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...