Monday 30 April 2018

Why not use java.util.logging?



For the first time in my life I find myself in a position where I'm writing a Java API that will be open sourced. Hopefully to be included in many other projects.




For logging I (and indeed the people I work with) have always used JUL (java.util.logging) and never had any issues with it. However now I need to understand in more detail what I should do for my API development. I've done some research on this and with the information I've got I just get more confused. Hence this post.



Since I come from JUL I'm biased on that. My knowledge of the rest is not that big.



From the research I've done I've come up with these reasons why people do not like JUL:




  1. "I started developing in Java long before Sun released JUL and it was just easier for me to continue with logging-framework-X rather than to learn something new". Hmm. I'm not kidding, this is actually what people say. With this argument we could all be doing COBOL. (however I can certainly relate to this being a lazy dude myself)


  2. "I don't like the names of the logging levels in JUL". Ok, seriously, this is just not enough of a reason to introduce a new dependency.



  3. "I don't like the standard format of the output from JUL". Hmm. This is just configuration. You do not even have to do anything code-wise. (true, back in old days you may have had to create your own Formatter class to get it right).


  4. "I use other libraries that also use logging-framework-X so I thought it easier just to use that one". This is a circular argument, isn't ? Why does 'everybody' use logging-framework-X and not JUL?


  5. "Everybody else is using logging-framework-X". This to me is just a special case of the above. Majority is not always right.




So the real big question is why not JUL?. What is it I have missed ? The raison d'ĂȘtre for logging facades (SLF4J, JCL) is that multiple logging implementations have existed historically and the reason for that really goes back to the era before JUL as I see it. If JUL was perfect then logging facades wouldn't exist, or what? To make matters more confusing JUL is to some extent a facade itself, allowing Handlers, Formatters and even the LogManager to be swapped.



Rather than embracing multiple ways of doing the same thing (logging), shouldn't we question why they were necessary in the first place? (and see if those reasons still exist)



Ok, my research so far has led to a couple of things that I can see may be real issues with JUL:





  1. Performance. Some say that performance in SLF4J is superior to the rest. This seems to me to be a case of premature optimization. If you need to log hundreds of megabytes per second then I'm not sure you are on the right path anyway. JUL has also evolved and the tests you did on Java 1.4 may no longer be true. You can read about it here and this fix has made it into Java 7. Many also talk about the overhead of string concatenation in logging methods. However template based logging avoids this cost and it exist also in JUL. Personally I never really write template based logging. Too lazy for that. For example if I do this with JUL:



    log.finest("Lookup request from username=" + username 
    + ", valueX=" + valueX
    + ", valueY=" + valueY));


    my IDE will warn me and ask permission that it should change it to:




    log.log(Level.FINEST, "Lookup request from username={0}, valueX={1}, valueY={2}", 
    new Object[]{username, valueX, valueY});


    .. which I will of course accept. Permission granted ! Thank you for your help.



    So I don't actually write such statements myself, that is done by the IDE.



    In conclusion on the issue of performance I haven't found anything that would suggest that JUL's performance is not ok compared to the competition.



  2. Configuration from classpath. Out-of-the-box JUL cannot load a configuration file from the classpath. It is a few lines of code to make it do so. I can see why this may be annoying but the solution is short and simple.


  3. Availability of output handlers. JUL comes with 5 output handlers out-of-the-box: console, file stream, socket and memory. These can be extended or new ones can be written. This may for example be writing to UNIX/Linux Syslog and Windows Event Log. I have personally never had this requirement nor have I seen it used but I can certainly relate to why it may be a useful feature. Logback comes with an appender for Syslog for example. Still I would argue that




    1. 99.5% of the needs for output destinations are covered by what is in JUL out-of-the-box.

    2. Special needs could be catered for by custom handlers on top of JUL rather than on top of something else. There's nothing to me that suggests that it takes more time to write a Syslog output handler for JUL than it does for another logging framework.




I'm really concerned that there's something I've overlooked. The use of logging facades and logging implementations other than JUL is so widespread that I have to come to the conclusion that it's me who just doesn't understand. That wouldn't be the first time, I'm afraid. :-)




So what should I do with my API? I want it to become successful. I can of course just "go with the flow" and implement SLF4J (which seems the most popular these days) but for my own sake I still need to understand exactly what is wrong with the JUL of today that warrants all the fuzz? Will I sabotage myself by choosing JUL for my library ?



Testing performance



(section added by nolan600 on 07-JUL-2012)



There's a reference below from Ceki about SLF4J's parametrization being 10 times or more faster than JUL's. So I've started doing some simple tests. At first glance the claim is certainly correct. Here are the preliminary results (but read on!):





  • Execution time SLF4J, backend Logback: 1515

  • Execution time SLF4J, backend JUL: 12938

  • Execution time JUL: 16911



The numbers above are msecs so less is better. So 10 times performance difference is by first actually pretty close. My initial reaction: That is a lot !



Here is the core of the test. As can be seen an integer and a string is construted in a loop which is then used in the log statement:



    for (int i = 0; i < noOfExecutions; i++) {

for (char x=32; x<88; x++) {
String someString = Character.toString(x);
// here we log
}
}


(I wanted the log statement to have both a primitive data type (in this case an int) and a more complex data type (in this case a String). Not sure it matters but there you have it.)



The log statement for SLF4J:




logger.info("Logging {} and {} ", i, someString);


The log statement for JUL:



logger.log(Level.INFO, "Logging {0} and {1}", new Object[]{i, someString});


The JVM was 'warmed up' with the same test executed once before the actual measurement was done. Java 1.7.03 was used on Windows 7. Latest versions of SLF4J (v1.6.6) and Logback (v1.0.6) was used. Stdout and stderr was redirected to null device.




However, careful now, it turns out JUL is spending most of its time in getSourceClassName() because JUL by default prints the source class name in the output, while Logback doesn't. So we are comparing apples and oranges. I have to do the test again and configure the logging implementations in a similar manner so that they actually output the same stuff. I do however suspect that SLF4J+Logback will still come out on top but far from the initial numbers as given above. Stay tuned.



Btw: The test was first time I've actually worked with SLF4J or Logback. A pleasant experience. JUL is certainly a lot less welcoming when you are starting out.



Testing performance (part 2)



(section added by nolan600 on 08-JUL-2012)



As it turns out it doesn't really matter for performance how you configure your pattern in JUL, i.e. whether or not it includes the source name or not. I tried with a very simple pattern:




java.util.logging.SimpleFormatter.format="%4$s: %5$s [%1$tc]%n"


and that did not change the above timings at all. My profiler revealed that the logger still spent a lot of time in calls to getSourceClassName() even if this was not part of my pattern. The pattern doesn't matter.



I'm therefore concluding on the issue of performance that at least for the tested template based log statement there seems to be roughly a factor of 10 in real performance difference between JUL (slow) and SLF4J+Logback (quick). Just like Ceki said.



I can also see another thing namely that SLF4J's getLogger() call is a lot more expensive than JUL's ditto. (95 ms vs 0.3 ms if my profiler is accurate). This makes sense. SLF4J has to do some time on the binding of the underlying logging implementation. This doesn't scare me. These calls should be somewhat rare in the lifetime of an application. The fastness should be in the actual log calls.






(section added by nolan600 on 08-JUL-2012)



Thank you for all your answers. Contrary to what I initially thought I've ended up deciding to use SLF4J for my API. This is based on a number of things and your input:




  1. It gives flexibility to choose log implementation at deployment time.


  2. Issues with lack of flexibility of JUL's configuration when run inside an application server.


  3. SLF4J is certainly a lot faster as detailed above in particular if you couple it with Logback. Even if this was just a rough test I have reason to believe that a lot more effort has gone into optimization on SLF4J+Logback than on JUL.



  4. Documentation. The documentation for SLF4J is simply a lot more comprehensive and precise.


  5. Pattern flexibility. As I did the tests I set out to have JUL mimic the default pattern from Logback. This pattern includes the name of the thread. It turns out JUL cannot do this out of the box. Ok, I haven't missed it until now, but I don't think it is a thing that should be missing from a log framework. Period!


  6. Most (or many) Java projects today use Maven so adding a dependency is not that big a thing especially if that dependency is rather stable, i.e. doesn't constantly change its API. This seems to be true for SLF4J. Also the SLF4J jar and friends are small in size.




So the strange thing that happened was that I actually got quite upset with JUL after having worked a bit with SLF4J. I still regret that it has to be this way with JUL. JUL is far from perfect but kind of does the job. Just not quite well enough. The same can be said about Properties as an example but we do not think about abstracting that so people can plug in their own configuration library and what have you. I think the reason is that Properties comes in just above the bar while the opposite is true for JUL of today ... and in the past it came in at zero because it didn't exist.


Answer



Disclaimer: I am the founder of log4j, SLF4J and logback projects.



There are objective reasons for preferring SLF4J. For one, SLF4J allows the end-user the liberty to choose the underlying logging framework. In addition, savvier users tend to prefer logback which offers capabilities beyond log4j, with j.u.l falling way behind. Feature-wise j.u.l may be sufficient for some users but for many others it just isn't. In a nutshell, if logging is important to you, you would want to use SLF4J with logback as the underlying implementation. If logging is unimportant, j.u.l is fine.




However, as an oss developer, you need to take into account the preferences of your users and not just your own. It follows that you should adopt SLF4J not because you are convinced that SLF4J is better than j.u.l but because most Java developers currently (July 2012) prefer SLF4J as their logging API. If ultimately you decide not to care about popular opinion, consider the following facts:




  1. those who prefer j.u.l do so out of convenience because j.u.l is bundled with the JDK. To my knowledge there are no other objective arguments in favor of j.u.l.

  2. your own preference for j.u.l is just that, a preference.



Thus, holding "hard facts" above public opinion, while seemingly brave, is a logical fallacy in this case.




If still not convinced, JB Nizet makes an additional and potent argument:




Except the end user could have already done this customization for his
own code, or another library that uses log4j or logback. j.u.l is
extensible, but having to extend logback, j.u.l, log4j and God only
knows which other logging framework because he uses four libraries that
use four different logging frameworks is cumbersome. By using SLF4J, you
allow him to configure the logging frameworks he wants, not the one
you have chosen. Remember that a typical project uses myriads of

libraries, and not just yours
.




If for whatever reason you hate the SLF4J API and using it will snuff the fun out of your work, then by all means go for j.u.l. After all, there are means to redirect j.u.l to SLF4J.



By the way, j.u.l parametrization is at least 10 times slower than SLF4J's which ends up making a noticeable difference.


html5 - What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.



In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.



localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.






localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).



Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.



localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.






This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.



On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.



As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.





In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.






As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).



As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.



The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.



Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.




localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.



For further reading on client storage technologies see Dive Into Html 5.

gcc - Is it possible to call a built in function from assembly in C++



Considering the following assembly code loop:




#include 

#define ADD_LOOP(i, n, v) \
asm volatile ( \
"movw %1, %%cx ;" \
"movq %2, %%rax ;" \
"movq $0, %%rbx ;" \
"for: ;" \
"addq %%rax, %%rbx ;" \
"decw %%cx ;" \

"jnz for ;" \
"movq %%rbx, %0 ;" \
: "=x"(v) \
: "n"(i), "x"(n) \
: "%cx", "%rax", "%rbx" \
);

int main() {
uint16_t iter(10000);
uint64_t num(5);

uint64_t val;

ADD_LOOP(iter, num, val)

std::cout << val << std::endl;

return 0;
}



Is possible to call a C function (or it's machine code output) from within a loop as specified above?



for example:



#include 

int main() {
__m128i x, y;

for(int i = 0; i < 10; i++) {

x = __builtin_ia32_aesenc128(x, y);
}

return 0;
}


Thanks


Answer



No. Builtin functions aren't real functions that you can call with call. They always inline when used in C / C++.




For example, if you want int __builtin_popcount (unsigned int x) to get either a popcnt instruction for targets with -mpopcnt, or a byte-wise lookup table for targets that don't support the popcnt instruction, you are out of luck. You will have to #ifdef yourself and use popcnt or an alternative sequence of instructions.






The function you're talking about, __builtin_ia32_aesenc128 is just a wrapper for the aesenc assembly instruction which you can just use directly if writing in asm.






If you're writing asm instead of using C++ intrinsics (like #include for performance, you need to have a look at http://agner.org/optimize/ to write more efficient asm (e.g. use %ecx as a loop counter, not %cx. You're gaining nothing from using a 16-bit partial register).




You could also write more efficient inline-asm constraints, e.g. the movq %%rbx, %0 is a waste of an instruction. You could have used %0 the whole time instead of an explict %rbx. If your inline asm starts or ends with a mov instruction to copy to/from an output/input operand, usually you're doing it wrong. Let the compiler allocate registers for you. See the tag wiki.



Or better, https://gcc.gnu.org/wiki/DontUseInlineAsm. Code with intrinsics typically compiles well for x86. See Intel's intrinsics guide: #include and use __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey). (In gcc that's just a wrapper for __builtin_ia32_aesenc128, but it makes your code portable to other x86 compilers.)


asp.net mvc 3 - The name 'model' does not exist in current context in MVC3

I added a cshtml page in an project. When I tried to add the following declaration to it, I get an error: "The name 'model' does not exist in current context".



@model xyz.abc.SomeClass


I checked the references, all of them are in place. I added a web.config in view folder, but that didn't fix it.



Is there anything i am missing?

javascript - Check if localStorage is available



I know there has been many questions about checking for localStorage but what if someone manually shuts it off in their browser? Here's the code I'm using to check:



localStorage.setItem('mod', 'mod');
if (localStorage.getItem('mod') != null){
alert ('yes');
localStorage.removeItem('mod');
} else {
alert ('no');
}


Simple function and it works. But if I go into my Chrome settings and choose the option "Don't Save Data" (I don't remember exactly what it's called), when I try to run this function I get nothing but Uncaught Error: SecurityError: DOM Exception 18. So is there a way to check if the person has it turned off completely?



UPDATE: This is the second function I tried and I still get no response (alert).



try {
localStorage.setItem('name', 'Hello World!');
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}

Answer



Use modernizr's approach (you might want to change my function name to something better):



function lsTest(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}

if(lsTest() === true){
// available
}else{
// unavailable
}


It's not as concise as other methods but that's because it's designed to maximise compatibility.



The original source: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js



Working example: http://jsfiddle.net/6sm54/2/


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.


Creating multiline strings in JavaScript



I have the following code in Ruby. I want to convert this code into JavaScript. what's the equivalent code in JS?



text = <<"HERE"
This
Is

A
Multiline
String
HERE

Answer



Update:



ECMAScript 6 (ES6) introduces a new type of literal, namely template literals. They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.




A template literal is delimited by backticks:



var html = `

Some HTML here

`;


(Note: I'm not advocating to use HTML in strings)




Browser support is OK, but you can use transpilers to be more compatible.






Original ES5 answer:



Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:



"foo \

bar"

javascript - Preventing SQL injection in Node.js



Is it possible to prevent SQL injections in Node.js (preferably with a module) in the same way that PHP had Prepared Statements that protected against them.



If so, how? If not, what are some examples that might bypass the code I've provided (see below).







Some Context:



I'm making a web application with a back-end stack consisting of Node.js + MySql using the node-mysql module. From a usability perspective, the module is great, but it has not yet implemented something akin to PHP's Prepared Statements (though I'm aware it is on the todo).



From my understanding, PHP's implementation of prepared statements, among other things, helped greatly in the prevention of SQL injections. I'm worried, though, that my node.js app may be open to similar attacks, even with the string escaping provided by default (as in the code snippet below).



node-mysql seems to be the most popular mysql connector for node.js, so I was wondering what other people might be doing (if anything) to account for this issue - or if it is even an issue with node.js to begin with (not sure how this wouldn't be, since user/client-side input is involved).




Should I switch to node-mysql-native for the time being, since it does provide prepared statements? I'm hesitant to do this, because it does not seem to be as active as node-mysql (though that may just mean that it is complete).



Here is a snippet of user registration code, which uses the sanitizer module, along with node-mysql's prepared statement-like syntax (which, as I mentioned above, does character escaping), to prevent cross site scripting and sql injections, respectively:



// Prevent xss
var clean_user = sanitizer.sanitize(username);

// assume password is hashed already
var post = {Username: clean_user, Password: hash};


// This just uses connection.escape() underneath
var query = connection.query('INSERT INTO users SET ?', post,
function(err, results)
{
// Can a Sql injection happen here?
});

Answer



The node-mysql library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values



sql - PHP adding information to database




I have a slight problem here with my PHP page. I have difficulties getting the filled in data in a database.



Let me show you the code of the index;




Naam:
Achternaam:



$nm = $_POST['naam;];
$anm = $_POST['achternaam'];
?>


Now I thought I had obtained the variabled and sent to the 'aanmelden.php' file.
The contents of the aanmelden.php file are:




$nm = $_GET['naam'];
$anm = $_GET['achternaam'];
$connect = mysql_connect('localhost', 'root', 'usbw');
mysql_select_db ('kantine');
$sql = "INSERT into kantine (naam, achternaam)
VALUES ('$nm', '$anm')";
$res = mysql_query($sql);
mysql_close ($connect); ?>



Looks all quite good to me, but when I press the submit button I get the following errors.




Notice: Undefined index: naam in I:\USBWebserver v8.6\root\aanmelden.php on line 2



Notice: Undefined index: achternaam in I:\USBWebserver
v8.6\root\aanmelden.php
on line 3





Please help me out if you can.



Regards,



Demiën


Answer



Since your form is configured to use method="post", you should be using the $_POST array rather than $_GET.



$name = $_POST['name'];

$lname = $_POST['lastname'];


See The Method Attribute.



Also, to avoid potential undefined indexes, I'd advise setting these variables with the ternary operator. That way, you can check for the existence of particular indexes before trying to access them.



$name = isset($_POST['name']) ? $_POST['name'] : false;
$lname = isset($_POST['lastname']) ? $_POST['lastname'] : false;



Edit



Other potential issues (or typos) with your code are:



// invalid, should be 
// semi-colon instead of a closing quote, should be $_POST['name']
$name = $_POST['name;];


Java: Printing ALL Args as single string

You can simply String.join the strings together and print them. Like:



public class Foo {

public static void main(String [] args) {

System.out.println(String.join(" ",args));
}

}


The first argument, the delimiter, is here " " (a string containing one space). Such that there is a space between two arguments.



Note that this program is almost identical to the echo program you see on a lot of operating systems.



Finally note that although this program does not contain a loop, the String.join definitely need some form of looping inside the method.

bash - jq not parsing json with spaces





I’m trying to run the following command that reads JSON from a file and formats it with jq :



jq -n -r --arg m $(<$1) '$m | fromjson | {records:[{value:.}]}'



It produces the desired output when the input JSON does not contain spaces, such as {"test":"helloworld"} :



{
"records": [
{
"value": {
"test": "helloworld"
}
}

]
}


However, for an input like {"test":"hello world"} it would give the following error:



jq: error: syntax error, unexpected QQSTRING_START, expecting $end (Unix shell quoting issues?) at , line 1:
world"}
jq: 1 compile error



Can’t figure out what’s causing this problem.



Thanks for any help :)


Answer



It's not a jq problem but a quoting issue (as highlighted in the error).



Change the --arg option to have the value within double quote:



arg='{"test":"hello world"}'

jq -n -r --arg m "$arg" '$m | fromjson | {records:[{value:.}]}'

Sunday 29 April 2018

javascript - Why does my for loop go straight to the end?

I am trying to learn javascript basics through an online course. I have a set of functions that work and I want to run them through a for loop 10 times. Here is the code of my for loop:



for (var count=0; count < 11; count++){
document.getElementById("position1").onclick=function() {
this.style.display="none";
clicked=Date.now();
reaction=(clicked-created)/1000;
document.getElementById("timebox").innerHTML="Time to click: "+reaction+" seconds "+count;
makebox();
}
}


For some reason, the loop starts with the variable count at 11 and infinately runs the code instead of stopping after 10 times. Can anybody give me an idea why it is doing this? I have added the count variable to the output just to see it and all it ever shows is 11.Thank you for any help that you can offer as I am stumped.



David

class - How to invoke the super constructor in Python?



class A:
def __init__(self):
print("world")

class B(A):
def __init__(self):
print("hello")


B() # output: hello


In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but this doesn't work.


Answer



super() returns a parent-like object in new-style classes:



class A(object):
def __init__(self):

print("world")

class B(A):
def __init__(self):
print("hello")
super(B, self).__init__()

B()

Undo working copy modifications of one file in Git?



After the last commit, I modified a bunch of files in my working copy, but I want to undo the changes to one of those files, as in reset it to the same state as the most recent commit.



However, I only want to undo the working copy changes of just that one file alone, nothing else with it.



How do I do that?



Answer



You can use



git checkout -- file


You can do it without the -- (as suggested by nimrodm), but if the filename looks like a branch or tag (or other revision identifier), it may get confused, so using -- is best.



You can also check out a particular version of a file:




git checkout v1.2.3 -- file         # tag v1.2.3
git checkout stable -- file # stable branch
git checkout origin/master -- file # upstream master
git checkout HEAD -- file # the version from the most recent commit
git checkout HEAD^ -- file # the version before the most recent commit

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

Is there a way to figure out the year the movie The Warriors (1979) was first shown on TV or cable?


Answer


According to this webpage, The Warriors was first time on TV in 1983.


How to use jQuery with Angular?



Can anyone tell me, how to use jQuery with Angular?



class MyComponent {
constructor() {
// how to query the DOM element from here?

}
}


I'm aware there are workarounds like manipulating the class or id of the DOM element upfront, but I'm hoping for a cleaner way of doing it.


Answer



Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.



tsd install jquery --save
or

typings install dt~jquery --global --save


TypescriptDefinitions are not required since you could just use any as the type for $ or jQuery



In your angular component you should reference a DOM element from the template using @ViewChild() After the view has been initialized you can use the nativeElement property of this object and pass to jQuery.



Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to jQuery.



import {bootstrap}    from '@angular/platform-browser-dynamic';

import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;

@Component({
selector: 'ng-chosen',
template: `

{{selectedValue}}

`
})

export class NgChosenComponent implements AfterViewInit {
@ViewChild('selectElem') el:ElementRef;
items = ['First', 'Second', 'Third'];
selectedValue = 'Second';

ngAfterViewInit() {
$(this.el.nativeElement)
.chosen()
.on('change', (e, args) => {
this.selectedValue = args.selected;

});
}
}

bootstrap(NgChosenComponent);


This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview



tslint will complain about chosen not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file




interface JQuery {
chosen(options?:any):JQuery;
}

Cannot modify header information - PHP










I have built a website with lots of functions supported by programming. As the website is growing bigger, I found when doing photo upload, login, the following errors appear:-





Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in /var/www/web92/web/li/sli.php on line 63



Warning: Cannot modify header information - headers already sent by (output started at /var/www/web92/web/index826.php:62) in /var/www/web92/web/li/sli.php on line 72




I found adding ob_start(); at the very beginning of index can solve the problem, however, I would like to learn, if the running of php codes may have length limit.


Answer



The message





output started at /var/www/web92/web/index826.php:62




means that you have already written out content and the server has begun streaming the response to the client. You cannot modify the headers because they have already been sent.



Move the header-generating code to a point before the very first output is written.


javascript - Uncaught TypeError: Cannot set property 'onclick' of null




I am creating an HTML page, Which is built using bootstrap. Here is the final HTML code and code of hello.js file:





document.getElementById("subm").onclick = function () {
alert("Hello WOrld");
}





Calculator










Calculator








































When I click on the button using submit then instead of alert I am getting error




Uncaught TypeError: Cannot set property 'onclick' of null





Can anyone please tell me why I am facing this error?? Help to resolve it.


Answer



The problem seems to be you are executing the script before the element is loaded.



I assume this script is added in the hello.js file which is added before the DOM is created.



The solution here is to execute the script after the DOM is ready like:



window.onload = function(){
document.getElementById("subm").onclick=function(){

alert("Hello WOrld");
}
}


All JavaScript code which deals with DOM elements like the one above has to be executed only after the DOM is loaded.



Demo: Fiddle


sql server - connect android to MSSQL db using jtds.jdbc driver to specific port

step by step instructions of how to connect android app to MSSQL database on Windows machine.



struggling to find a right solution for connecting to MSSQL database from android using
jtds.jdbc driver, what makes it worst is that it is not clear for me whether the problem is with database or with jtds.jdbc driver.



public class DBTestActivity extends Activity {         

private static final String url = "jdbc:jtds:sqlserver://10.0.2.2:1433;instance=testdb;DatabaseName=androidtest";
private static final String user = "test\'testuser";

private static final String pass = "testlog";

TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.dbconnect);


final Button button = (Button) findViewById(R.id.connect);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("test3", "text4");
// Perform action on click
Connect();
tv = (TextView) findViewById(R.id.db_text);
}
});


}

private class Connect extends AsyncTask {
@Override
protected String doInBackground(String... urls) {
String response = "";

try {

Log.d("test5", "text5");

Class.forName("net.sourceforge.jtds.jdbc.Driver");
Log.d("test77", "text77");

Connection con = DriverManager.getConnection(url, user, pass);

Log.d("test12", "text12");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from dbo.Test_Manufacturer");
ResultSetMetaData rsmd = rs.getMetaData();*/


while(rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
}
tv.setText(result);
}
catch(Exception e) {
e.printStackTrace();

// tv.setText(e.toString());
}
Log.d("test20", "text212");

return response;

}

@Override
protected void onPostExecute(String result) {

Log.d("test2", "text2");
tv.setText(result);
}
}

public void Connect() {

Log.d("test", "text1");
Connect task = new Connect();
task.execute();


}

}


Got different sort of errors:




  • SQLException: server 10.0.2.2 has no instance named ......


  • ECONNREFUSED

  • COULD NOT FIND METHOD ORG.IETF.JGSS.GSSCONTEXT.INITSECCONTEXT

Machine Gun Preacher

I started watching Machine Gun Preacher. It's not the greatest quality movie I have seen. However the theme is about the warzone in Uganda, and I find it to be a bit coincidental with the whole Kony 2012 hype.


Are they related in any way?


I imagine it would bring more attention to such a movie, not to mention sales going up?


Answer


Well there is the obvious relationship in that they both deal with Joseph Kony and the Lords Resistance Army and its aftermath in Uganda.


Sam Childers, the subject of Machine Gun Preacher is known to the Group Invisible Children as seen in this Google cache from Invisible Children's blog where IC says:



Actually, let’s start with a disclaimer: Invisible Children does not in any way endorse this man’s actions or methods.


Now that that’s settled, we can say ‘what the….?’ In brief, this American preacher is leading a militia of Sudanese and Ugandans with the sole aim of killing Joseph Kony. He claims that this is his God-ordained mission.



There is another distinction that Invisible Children and Sam Childers share; they may be more hype than hope.


According to the Pittsburgh Tribune Sam Childers' orphanage has problems:



Some neighbors around Nimule want Childers removed and the orphanage turned over to local leaders. While Childers was on an American publicity tour, Nimule community leaders told a reporter for the magazine Christianity Today that he dishonored his agreement with them. The resulting story detailed a local government inspection that found the orphanage with no food, little medicine and shelters on the verge of collapse.



Similar charges have been levied against Invisible Children. In a recent post from journalist Michael Wilkerson he notes that:



(Invisible Children)... it spends too much money on administration and filmmaking, while still touting its on the ground NGO-style projects. Also, apparently it's never been externally audited.



Claims that less than one-third of the money raised actually goes to help children in Uganda have been made.


A recent showing in of Kony 2012 in Uganda angered many people. An Al jazzera article notes that:



Towards the end of the film, the mood turned more to anger at what many people saw as a foreign, inaccurate account that belittled and commercialised their suffering, as the film promotes Kony bracelets and other fundraising merchandise, with the aim of making Kony infamous.



Will it drive up sales of the Machine Gun Preacher dvd when it comes out? Probably not. The movie itself didn't even gross $1 million. I doubt the studio is going to see a real reason to push the dvd of a movie that lost $29 million.


if statement - IF/ELSE to echo image in PHP

Answer


Answer




I am trying to echo a specific image based on the results of a IF/ELSE statement, however I can't quite work out the phrasing of the IF/ELSE statement. I'm a relative newbie to PHP, so I'm sure that it's just a little error in the code somewhere, but if anyone could offer any assistance, I'd be grateful!



I'm currently at the stage below:



     $fresh = if ($reviews['reviews']['freshness']) = 'fresh' {

echo 'Fresh';
} else {
echo 'Rotten';
}
?>

foreach($reviews['reviews'] as $rv){
if ($tmp++ < 10);
echo $fresh;

echo '
  • ' . $rv['quote'] . '
  • ';
    }
    ?>


    Thank you!


    Answer



    you cant assign if statement to a value.



    if ($reviews['reviews']['freshness'] == 'fresh') {

    echo 'Fresh';
    } else {
    echo 'Rotten';
    }


    another prettier way would be:



    if ($reviews['reviews']['freshness'] == 'fresh') {
    $image = "fresh";

    }
    else {
    $image = "rotten";
    }

    echo 'Rotten';

    How to format JSON in notepad++




    I want to format JSON String in notepad++. Kindly guide me how to do so. I looked into this solution Notepad ++ JSON Format. It tells me to download the a tool from This web site. But I don't know which link to click out of 4 mentioned in that web site. Also, I just randomly downloaded one of the zip file and then unzipped it and it shows one dll file. Now what to do with that dll. Can some one guide me as I am a complete beginner. I have windows 10 running on my PC



    EDIT 1
    Some people are in so much hurry to give negative points. May be some people want to see code snippet even for this question. Huh!



    EDIT 2
    Anyways I tried below and IT DID NOT WORK



    enter image description here




    This is how my notepad ++ looks like after installing them.



    enter image description here



    EDIT 3
    Ok I fixed the issue. The problem is if you select multiple plugins together
    (multiple checkboxes) and install them there seems to be some issue with notepad++, so the solution for me was to install the plugin individually.


    Answer



    You have to use the plugin manager of Notepad++ and search for the JSON plugin. There you can easily install it.




    This answer explains it pretty good: How to reformat JSON in Notepad++?


    Saturday 28 April 2018

    javascript - how can I cancel an Ajax request?




    In phonegap how to cancel an ajax request in program, I would like to set cancel button for control the request when it's too slow




    $.ajax({
    type: "GET",
    url: url,
    success: function(m) {
    alert( "success");
    }
    });

    Answer



    hi it's similar as Abort Ajax requests using jQuery,anyway This can help you




     var ab = $.ajax({  type: "GET",  url: url,  success: function(m)  {    alert( "success");  } });

    //kill the request
    ab.abort()

    java - Object is same but the output is different ? please help

    Answer


    Answer






    Possible Duplicate:
    String equality vs equality of location




    public class AboutStrings{
    public static void main(String args[]){
    String s1="hello";
    String s2="hel";

    String s3="lo";
    String s4=s2+s3;

    //to know the hash codes of s1,s4.

    System.out.println(s1.hashCode());
    System.out.println(s4.hashCode());

    // these two s1 and s4 are having same hashcodes.


    if(s1==s4){
    System.out.println("s1 and s4 are same.");
    }else
    System.out.println("s1 and s4 are not same.");
    }
    }


    In the above example even though s1 and s4 are refering to
    same object(having same hash codes),




    it is printing s1 and s4 are not same.



    Can anybody explain in detail why it is behaving like this?


    Answer



    Just because two objects have the same hash code does not mean they are the same object (you are checking with == the object identity!).



    You may want to call



    s1.equals(s4)



    instead - but even then, both could have the same hash code without being equal either: two objects that are equal must have the same hash code (to work properly in Collections etc), but not vice versa.


    'documentary' tag wiki - Movies & TV



    Category of nonfictional motion pictures intended to document some aspect of reality, primarily for the purposes of providing a factual or historical record or report. Only to be used on questions about the intricacies of documentaries, not for general questions about specific documentaries.




    Category of nonfictional motion pictures intended to document some aspect of reality, primarily for the purposes of providing a factual or historical record or report. Only to be used on questions about the intricacies of documentaries, not for general questions about specific documentaries.

    excel - Delete entire row if cells in specific range are all empty



    I want to create a macro that would delete an entire row if all the cells in specific range (B to K in each of the 10 rows) are all empty. I tried the following:



    Dim i As Integer
    Dim rng As Range


    For i = 1 To 10
    Set rng = Range("B" & i, "K" & i).SpecialCells(xlCellTypeBlanks)
    rng.EntireRow.Delete
    Next i


    If there are more following lines with empty cells, let's say 1 and 2, it deletes row 1 and move row 2 instead of the deleted one, so it becomes row 1. Then it skips the moved row, because i always increases so it never checks row 1 again. Is there any way to check if the row that was just deleted is really non-empty before moving to the next i?



    Btw: I am using Excel 2013.


    Answer




    Instead of using the Special Cells, why not just use CountA()?



    Sub t()
    Dim i&

    For i = 10 To 1 Step -1
    If WorksheetFunction.CountA(Range("B" & i, "K" & i)) = 0 Then
    Rows(i).EntireRow.Delete
    End If
    Next i

    End Sub


    That way, you can avoid any errors in case there's no blanks. Also, when deleting rows, it's recommended to start at the end, then Step -1 to the beginning.



    Edit:



    Try this as well, it may be quicker:



    Sub T()

    Dim rng As Range

    Set rng = Range("B1:K10") ' Since you're going to loop through row 1 to 10, just grab the blank cells from the start
    rng.SpecialCells(xlCellTypeBlanks).EntireRow.Select ' Just to show you what's being selected. Comment this out in the final code
    rng.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End Sub


    I recommend stepping through that with F8 first, to see how it works. In the range B1:K10, it will first select all rows where there's a blank cell. Then, it'll delete those rows.


    .net - How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?



    How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?


    Answer



    You can use a library called ExcelLibrary. It's a free, open source library posted on Google Code:



    ExcelLibrary



    This looks to be a port of the PHP ExcelWriter that you mentioned above. It will not write to the new .xlsx format yet, but they are working on adding that functionality in.




    It's very simple, small and easy to use. Plus it has a DataSetHelper that lets you use DataSets and DataTables to easily work with Excel data.



    ExcelLibrary seems to still only work for the older Excel format (.xls files), but may be adding support in the future for newer 2007/2010 formats.



    You can also use EPPlus, which works only for Excel 2007/2010 format files (.xlsx files). There's also NPOI which works with both.



    There are a few known bugs with each library as noted in the comments. In all, EPPlus seems to be the best choice as time goes on. It seems to be more actively updated and documented as well.



    Also, as noted by @ĐŃ€Ń‚Ń‘ĐŒĐŠĐ°Ń€ĐžĐŸĐœĐŸĐČ below, EPPlus has support for Pivot Tables and ExcelLibrary may have some support (Pivot table issue in ExcelLibrary)




    Here are a couple links for quick reference:
    ExcelLibrary - GNU Lesser GPL
    EPPlus - GNU Lesser General Public License (LGPL)
    NPOI - Apache License



    Here some example code for ExcelLibrary:



    Here is an example taking data from a database and creating a workbook from it. Note that the ExcelLibrary code is the single line at the bottom:



    //Create the data set and table
    DataSet ds = new DataSet("New_DataSet");
    DataTable dt = new DataTable("New_DataTable");


    //Set the locale for each
    ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
    dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;

    //Open a DB connection (in this example with OleDB)
    OleDbConnection con = new OleDbConnection(dbConnectionString);
    con.Open();

    //Create a query and fill the data table with the data from the DB
    string sql = "SELECT Whatever FROM MyDBTable;";

    OleDbCommand cmd = new OleDbCommand(sql, con);
    OleDbDataAdapter adptr = new OleDbDataAdapter();

    adptr.SelectCommand = cmd;
    adptr.Fill(dt);
    con.Close();

    //Add the table to the data set
    ds.Tables.Add(dt);


    //Here's the easy part. Create the Excel worksheet from the data set
    ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);


    Creating the Excel file is as easy as that. You can also manually create Excel files, but the above functionality is what really impressed me.


    How do I copy the data of an element with jQuery?

    I need to copy data values from one element to another, but jQuery's clone() method doesn't clone the data. And I can't iterate over the data either:



    element.data().each


    because data() is a function and not a jQuery object. It seems I have to keep a separate list of attribute names and reference those but that seems too hacky. So how can I do either of these:




    a) Iterate over data items
    OR
    b) clone() an element with its data.

    Java: Print Array: IndexOutOfBoundsException: Index: 2, Size: 2




    I am trying to print the contents of an array using System.out.print() but I encounter this error:



    Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
    at java.util.ArrayList.rangeCheck(ArrayList.java:604)
    at java.util.ArrayList.get(ArrayList.java:382)
    at Polymorphism.actionPerformed(Polymorphism.java:196)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)

    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6505)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6270)
    at java.awt.Container.processEvent(Container.java:2229)
    at java.awt.Component.dispatchEventImpl(Component.java:4861)
    at java.awt.Container.dispatchEventImpl(Container.java:2287)
    at java.awt.Component.dispatchEvent(Component.java:4687)

    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.java:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2713)
    at java.awt.Component.dispatchEvent(Component.java:4687)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
    at java.awt.EventQueue.access$000(EventQueue.java:101)
    at java.awt.EventQueue$3.run(EventQueue.java:666)
    at java.awt.EventQueue$3.run(EventQueue.java:664)

    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:680)
    at java.awt.EventQueue$4.run(EventQueue.java:678)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)

    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


    The line the error is referring to is line 3:



     else if (e.getSource() == printArray) {
    for (int q=0; q
    System.out.print("Type: " + itemList.get(j).selectedType + " ");
    System.out.print("Width: " + itemList.get(j).selectedWidth + " ");
    System.out.print("Length: " + itemList.get(j).selectedLength + " ");
    }
    }


    I don't have any debugger experience so I appreciate any help, thanks.


    Answer



    Change to .get(j) as Renjith says and you can also make sure to never end up in the situation you're in




    instead of



    for (int q=0; q


    do



    for (int q=0; q



    This way you cannot .get from anything larger than the size of the list/array


    Is X Files shot on location at UMD's campus? - Movies & TV



    This is a somewhat obscure question, but through a bit of Googling and a bit of background work, I've been unable to find an answer. I'm a UMD student, and have been trying to ascertain whether or not the shots of the University of Maryland in the X files are real, or shot somewhere in California.




    There are never action shots, simply lead characters walking into buildings, overhead shots of the campus, etc... It looks like the shots might be real (given that nothing too amazing happens), but as it was the early 90s, the landscaping has changed slightly (and it's a fairly standard east coast school architecture without an amazing amount of distinctive features).



    Is X Files shot on location at UMD's campus?


    Answer



    The credits for locations do not list any Maryland locations. However, since there's no indications of how those locations were used, it would be difficult to identify what locations were used to represent UM, short of finding someone who actually recognizes the specific places.


    java - Unable to intercept and manipulate HttpServletResponse in Spring Boot



    I have a requirement to Base64 decode every JSON request payload that my Spring Boot service receives. The JSON payload would have been Base64 encoded at the client before posting using the HTTP POST method. Further, I also need to Base64 encode the JSON response before presenting to the calling client application.




    I am required to reduce boilerplate code by using handler interceptors.
    I have already achieved the request/incoming leg of the operation by the use of interceptors but is yet to achieve this for the response leg.
    I have posted the code snippets below. The code to intercept the response and base64 encode it is in the postHandle method of the interceptor class.



    What am I doing wrong here?



    Interceptor Class:



    public class Base64ResponseEncodingInterceptor implements HandlerInterceptor {   

    private static final String DECODED_REQUEST_ATTRIB = "decodedRequest";
    private static final String POST = "POST";


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3) throws Exception {
    try {
    if (POST.equalsIgnoreCase(request.getMethod())) {
    CharResponseWrapper res = new CharResponseWrapper(response);
    res.getWriter();

    byte[] encoded = Base64.encodeBase64(res.toString().getBytes());
    byte[] encoded = Base64.encodeBase64(response.getHeader(ENCODED_RESPONSE_ATTRIB).getBytes());
    response.getWriter().write(new String(encoded));
    }
    } catch (Exception e) {
    throw new Exception(e.getMessage());
    }
    }



    // preHandle and afterCompletion methods
    // Omitted
    }


    The CharResponseWrapper Class used above:



    public class CharResponseWrapper extends HttpServletResponseWrapper {

    protected CharArrayWriter charWriter;


    protected PrintWriter writer;

    protected boolean getOutputStreamCalled;

    protected boolean getWriterCalled;


    public CharResponseWrapper(HttpServletResponse response) {
    super(response);

    charWriter = new CharArrayWriter();
    }


    @Override
    public ServletOutputStream getOutputStream() throws IOException {
    if (getWriterCalled) {
    throw new IllegalStateException("getWriter already called");
    }
    getOutputStreamCalled = true;

    return super.getOutputStream();
    }


    @Override
    public PrintWriter getWriter() throws IOException {
    if (writer != null) {
    return writer;
    }
    if (getOutputStreamCalled) {

    throw new IllegalStateException("getOutputStream already called");
    }
    getWriterCalled = true;
    writer = new PrintWriter(charWriter);
    return writer;
    }


    @Override
    public String toString() {

    String s = null;
    if (writer != null) {
    s = charWriter.toString();
    }
    return s;
    }
    }


    JavaConfig Class where Interceptor is registered:




    @Configuration
    @EnableJpaRepositories(repositoryBaseClass = BaseRepositoryBean.class, basePackages = "")
    @EntityScan(basePackages = { "com.companyname", "com.companyname.productname"})
    public class RestConfig extends WebMvcConfigurerAdapter {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new Base64ResponseEncodingInterceptor());

    }

    }


    The Controller Class, where the Interceptor is used (Only the working request leg is shown here):



    @Autowired
    HttpServletRequest request;


    String decodedRequest = null;

    @ModelAttribute("decodedRequest")
    public void getDecodedParam(){
    decodedRequest = (String) request.getAttribute("decodedRequest");
    }


    The code in the postHandle method does not work. It is either the HttpServletResponse is null or I get an exception message:





    getOutputStream already called




    Update: Work around solution to reading the response directly in the ResponseBodyAdvice
    In the Controller Class, I added the following:



    @RestController
    @RequestMapping("/api/ipmanager")
    public class IPProfileRestController extends AbstractRestController {


    @Autowired
    HttpServletResponse response;

    String encodedResponse = null;

    @ModelAttribute("encodedResponse")
    public void getEncodedResponse(){
    response.setHeader("encodedResponse", StringUtils.EMPTY);
    }


    @RequestMapping(value = "/time", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE }, consumes = {
    MediaType.APPLICATION_JSON_VALUE })
    public @ResponseBody String saveAccessClientTime(@RequestBody String ecodedRequest) {

    // Some code here

    String controllerResponse = prettyJson(iPProfileResponse);
    response.setHeader("encodedResponse", controllerResponse);
    return controllerResponse;

    }
    }


    I have the following in the ResponseBodyAdvice



    @ControllerAdvice
    public class Base64EncodedResponseBodyAdvice implements ResponseBodyAdvice {

    @Override

    public boolean supports(MethodParameter returnType,
    Class> converterType) {
    return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
    MethodParameter returnType,
    MediaType selectedContentType,
    Class> converterType,

    ServerHttpRequest request,
    ServerHttpResponse response) {

    String body1 = StringUtils.EMPTY;
    // Encode the response and return

    List listOfHeaderValues = response.getHeaders().get("encodedResponse");

    body1=new String(Base64.encodeBase64(listOfHeaderValues.get(0).getBytes()));


    return body1;
    }

    }

    Answer



    As the Spring MVC documentation states:




    the postHandle method of HandlerInterceptor is not always ideally

    suited for use with @ResponseBody and ResponseEntity methods. In such
    cases an HttpMessageConverter writes to and commits the response
    before postHandle is called which makes it impossible to change the
    response
    , for example to add a header. Instead an application can
    implement ResponseBodyAdvice and either declare it as an
    @ControllerAdvice bean or configure it directly on
    RequestMappingHandlerAdapter.




    With that being said:





    What am I doing wrong here?




    Since the response has been already committed, you can't change it. In order to change the response you should register a ResponseBodyAdvice and put your response encoding logic there:



    @ControllerAdvice
    public class Base64EncodedResponseBodyAdvice implements ResponseBodyAdvice {
    @Override

    public boolean supports(MethodParameter returnType,
    Class> converterType) {
    return true;
    }

    @Override
    public Object beforeBodyWrite(Object body,
    MethodParameter returnType,
    MediaType selectedContentType,
    Class> converterType,

    ServerHttpRequest request,
    ServerHttpResponse response) {

    // Encode the response and return
    }
    }

    php - PHP7 compatibility



    Im looking for fix for PHP7 compatibility.
    I have code which working well with PHP 5.6.2.



    Can you please help me to work with PHP7?



    $select = "SELECT post_title , ID FROM  wp_posts ORDER BY ID DESC LIMIT 60";

    $sql1= mysql_query($select);
    $a = 1;
    while($row = mysql_fetch_array($sql1)){ ?>
    div class="form-group">



    }
    ?>



    Thank you.
    Best Regards
    Jiri


    Answer



    Even when running PHP 5.6.2 you should have seen the deprecation notices for the mysql_* functions, and they have been completely removed in PHP 7. Fortunately, you can use the mysqli_* functions without really changing your code much.



    The primary difference in this example (aside from adding an i to your function names) is that now you'll need to explicitly use the link identifier returned by mysqli_connect() or mysqli_init() which is different because previously if the link identifier was not specified, then the last link opened by mysql_connect() was assumed. This is now required.





    // get a link to the connection
    $link = mysqli_connect("localhost", "my_user", "my_password", "my_db");

    $select = "SELECT post_title , ID FROM wp_posts ORDER BY ID DESC LIMIT 60";

    // use the link here
    // change mysql_query -> mysqli_query
    $sql1= mysqli_query($link, $select);


    $a = 1;

    // change mysql_fetch_array -> mysqli_fetch_array
    while($row = mysqli_fetch_array($sql1)){ ?>
    div class="form-group">




    }
    ?>

    Reading a file line by line into elements of an array in Python




    So in Ruby I can do the following:



    testsite_array = Array.new
    y=0
    File.open('topsites.txt').each do |line|
    testsite_array[y] = line
    y=y+1
    end



    How would one do that in Python?


    Answer



    testsite_array = []
    with open('topsites.txt') as my_file:
    for line in my_file:
    testsite_array.append(line)



    This is possible because Python allows you to iterate over the file directly.



    Alternatively, the more straightforward method, using f.readlines():



    with open('topsites.txt') as my_file:
    testsite_array = my_file.readlines()

    mysql - PHP MySQLI Prevent SQL Injection





    I've build a website that will be going live soon and just have a couple questions about preventing SQL injection, I understand how to use mysqli_real_escape_string but I'm just wondering if I have to use that on all variables that I'm getting for my SQL statement and do I have to use it when I'm doing select statements also or just on insert update and delete? Also what other security would you recommend me implementing before I put the site live, thanks in advance for any help!


    Answer



    Any query can be injected whether it's read or write, persistent or transient. Injections can be performed by ending one query and running a separate one (possible with mysqli), which renders the intended query irrelevant.



    Any input to a query from an external source whether it is from users or even internal should be considered an argument to the query, and a parameter in the context of the query. Any parameter in a query needs to be parameterized. This leads to a properly parameterized query that you can create a prepared statement from and execute with arguments. For example:



    SELECT col1 FROM t1 WHERE col2 = ?


    ? is a placeholder for a parameter. Using mysqli, you can create a prepared statement using prepare, bind a variable (argument) to a parameter using bind_param, and run the query with execute. You don't have to sanitize the argument at all (in fact it's detrimental to do so). mysqli does that for you. The full process would be:




    $stmt = mysqli->prepare("SELECT col1 FROM t1 WHERE col2 = ?");
    $stmt->bind_param("s", $col2_arg);
    $stmt->execute();


    There is also an important distinction between parameterized query and prepared statement. This statement, while prepared, is not parameterized and is thus vulnerable to injection:



    $stmt = mysqli->prepare("INSERT INTO t1 VALUES ($_POST[user_input])");



    To summarize:




    • All Queries should be properly parameterized (unless they have no parameters)

    • All arguments to a query should be treated as hostile as possible no matter their source


    Friday 27 April 2018

    c++ - Concatenating two std::vectors

    How do I concatenate two std::vectors?

    performancecounter - Configuring the PMU to read Perfomance Counters

    I am using Linux 4.19.2 (ubuntu 16.04) on an intel i7-3770 CPU. I have used tools like perf for performance monitoring. I want to write a basic piece of code to read performance counters without using any such tools.



    I came across the rdpmc instruction. Before using it, I am having trouble with configuring the registers to count a particular event. I checked some forums like https://software.intel.com/en-us/forums/software-tuning-performance-optimization-platform-monitoring/topic/745751 but this didn't help.
    What exactly is meant by configuring the PMU here? And how would one do it?




    I want to read from kernel code itself, so there's no issue of privileges. What is the easiest way to do it?



    Also, is rdpmc the least overhead way to this?

    javascript - How to sort an array of integers correctly



    Trying to get the highest and lowest value from an array that I know will contain only integers seems to be harder than I thought.





    var numArray = [140000, 104, 99];
    numArray = numArray.sort();
    alert(numArray)






    I'd expect this to show 99, 104, 140000. Instead it shows 104, 140000, 99. So it seems the sort is handling the values as strings.



    Is there a way to get the sort function to actually sort on integer value?


    Answer



    By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -






    function sortNumber(a, b) {
    return a - b;
    }

    var numArray = [140000, 104, 99];
    numArray.sort(sortNumber);

    console.log(numArray);






    In ES6, you can simplify this with arrow functions:



    numArray.sort((a, b) => a - b); // For ascending sort
    numArray.sort((a, b) => b - a); // For descending sort






    Documentation:



    Mozilla Array.prototype.sort() recommends this compare function for arrays that don't contain Infinity or NaN. (Because Inf - Inf is NaN, not 0).



    Also examples of sorting objects by key.


    android - Device ID Giving null Value





    I am trying to get Unique ID[I.E unique id of a device] by using below code



    TelephonyManager tManager;

    tManager = (TelephonyManager).getSystemService(Context.TELEPHONY_SERVICE);


    String deviceId = tManager.getDeviceId();


    Where deviceId Gives me Unique ID for Android Device. I am not testing this on emulator because in emulator i am getting value 000000000000000



    Any way i am testing it on real devices,and this works fine for mostly all devices , but in some device i am getting value null



    I have tested this on



    Samsung Galaxy S3


    Samsung Galaxy Tab3

    Samsung Galaxy Star

    Google Nexus4

    Google Nexus5

    Google Nexus7



    In all the devices listed above it gives me correct out put except one Device and that is Google Nexus7, in this i m getting value null



    So, ultimately my goal is to get unique value for each particular device, In case if this code gives me null value than i can try some alternate way



    i heard that Device MAC Address is a unique for all devices, But unfortunately it just works on wifi connection.



    So is there any other way to get unique value of each particular device?




    Thanks Any way


    Answer



    You shouldn't really use the ANDROID_ID, you have no real guarantee that it will give you a unique identifier for the device and it is known that some older devices give the value null, or as in Moto's case, the same static value across multiple devices. This value also changes when the phone is reset to the factory default, and is super easy to change on a rooted device.



    The correct way is to generate your own UUID via.



    String uudid = UUID.randomUUID()


    You then save this in your App, for example through a SharedPreference. You can then use Google's Android backup storage to retain this identifier even if the user uninstalls your App.




    More information on Backup here: http://developer.android.com/guide/topics/data/backup.html



    If you don't take my word for it, you should take Reto Meier's word for it, he is a developer advocate at the Google Android team. This video will explain what I just told you, check out around minute 15, he also specifically instructs developers not to use the ANDROID_ID.



    http://www.youtube.com/watch?v=twmuBbC_oB8&list=WL86437554BC3E54B5


    casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

    In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...