Tuesday 31 January 2017

php - CodeIgniter session work my wamp server properly, But online server does not work

Now a days, I have developed a CodeIgniter Application for a Medical
service website. There has a chat option. for this chat feature, I have create Session.
Config file code



$config['encryption_key'] = 'CoderSaiful';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;

$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;


Autoload file Code:




$autoload['libraries'] = array('database','form_validation','session');


Controller chat.php file code:



function index(){
$user_data = $this->session->all_userdata();
$data['title'] = 'Live Chat';
$data['sub_title'] = 'Chat with each other and free';;
$this->load->model('options_m');

$data['menu']= $this->options_m->menu();
$data['site_info']= $this->options_m->site_info();
$this->load->view('template/header_with_menu_with_top',$data);

if(isset($user_data[0])){
//enter code here
}
else{
$this->load->view('chat/form');
}

/*
$this->load->view('chat/form');

$this->load->model('chat_m');
$data['chat'] = $this->chat_m->get_chat();
*/

$this->load->model('chat_m');
$data['chat'] = $this->chat_m->get_chat();
$this->load->view('chat/live',$data);


if(isset($user_data[0])){
$this->load->view('chat/chat_form',$user_data);
}

$this->load->view('includes/footer');
//dump($data);
}



I think, all are right and it work properly, when I check on my local pc wamp server. But When I have uploaded to my web server. It show error. Like this:



Severity: Warning 

Message: Cannot modify header information - headers already sent by (output started at /home/saifulbd/public_html/jessorepublichealth.com/application/controllers/chat.php:1)

Filename: libraries/Session.php

Line Number: 675



Now I would like to get great solution for this error.

How can I declare optional function parameters in Javascript?











Can I declare default parameter like



function myFunc( a, b=0) 
{
// b is my optional parameter

}


in javascript.


Answer



With ES6: This is now part of the language:



function myFunc(a, b = 0) {
// function body
}



Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).






With ES5:



function myFunc(a,b) {
b = b || 0;


// b will be set either to b or to 0.
}


This works as long as all values you explicitly pass in are truthy.
Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''



It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.


javascript - Can I hide the HTML5 number input’s spin box?



Is there a consistent way across browsers to hide the new spin boxes that some browsers (such as Chrome) render for HTML input of type number? I am looking for a CSS or JavaScript method to prevent the up/down arrows from appearing.






Answer



This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):





input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
/* display: none; <- Crashes Chrome on hover */

-webkit-appearance: none;
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}

input[type=number] {
-moz-appearance:textfield; /* Firefox */
}







You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":



Inspector for input type=number (Chrome)


c++ - Why use apparently meaningless do-while and if-else statements in macros?



In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples.



#define FOO(X) do { f(X); g(X); } while (0)
#define FOO(X) if (1) { f(X); g(X); } else



I can't see what the do while is doing. Why not just write this without it?



#define FOO(X) f(X); g(X)

Answer



The do ... while and if ... else are there to make it so that a
semicolon after your macro always means the same thing. Let's say you
had something like your second macro.




#define BAR(X) f(x); g(x)


Now if you were to use BAR(X); in an if ... else statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.



if (corge)
BAR(corge);
else
gralt();



The above code would expand into



if (corge)
f(corge); g(corge);
else
gralt();



which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.



if (corge)
{f(corge); g(corge);};
else
gralt();


There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.




#define BAR(X) f(X), g(X)


The above version of bar BAR expands the above code into what follows, which is syntactically correct.



if (corge)
f(corge), g(corge);
else
gralt();



This doesn't work if instead of f(X) you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like do ... while to cause the macro to be a single statement that takes a semicolon without confusion.



#define BAR(X) do { \
int i = f(X); \
if (i > 4) g(i); \
} while (0)


You don't have to use do ... while, you could cook up something with if ... else as well, although when if ... else expands inside of an if ... else it leads to a "dangling else", which could make an existing dangling else problem even harder to find, as in the following code.




if (corge)
if (1) { f(corge); g(corge); } else;
else
gralt();


The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare BAR as an actual function, not a macro.



In summary, the do ... while is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.



php - Can't Save MySQL Query

I'm having an issue with my MySQL query/php, I try to update a row in my database that will work usually, but when the string has a ' in it, for example




I don't like green eggs and ham.





The ' in it will cancel the whole response out and not update the row, so if I put something like this without the ' for example:




I dont like green eggs and ham.




The string will save to the row. Below is the MySQL query used and where I get the string from.




$NewMessage = $_POST['message123'];

mysql_query("UPDATE Account SET `function` = 'Message', `note` = '$NewMessage' WHERE `id` = '$ID' AND `Online` = '1'");


If you need anymore source or anything, please let me know, let me know what you think, thanks!

Converting a number string into MD5 with python



Inspired by the XKCD geohashing comic (http://imgs.xkcd.com/comics/geohashing.png), I thought I'd have a go at coding a generator in Python. I've hit a block with the major part of it, though: The converting to MD5 and then to decimal.



Is it at all possible?


Answer



edit: After looking at the comic here is a more complete solution for XKCD geohashing:




>>> md5 = hashlib.md5('2005-05-26-10458.68').hexdigest()     # get MD5 as hex string
>>> float.fromhex('0.' + md5[:16]) # first half as float
0.85771326770700229
>>> float.fromhex('0.' + md5[16:]) # second half as float
0.54454306955928211


Here is a more general answer for "converting to MD5 and then to decimal":



Say you want the decimal MD5 of the string 'hello world', you could use the following:




>>> int(hashlib.md5('hello world').hexdigest(), 16)
125893641179230474042701625388361764291L


The hash.hexdigest() function returns a hexadecimal string, and int(hex_str, 16) is how you can convert a hexadecimal string to a decimal.


intel - Understanding CYCLE_ACTIVITY.* Haswell Performance-Monitoring Events

I'm trying to analyse an execution on an Intel Haswell CPU (Intel® Core™ i7-4900MQ) with the Top-down Microarchitecture Analysis Method (TMAM), described in Chapters B.1 and B.4 of the Intel® 64 and IA-32 Architectures
Optimization Reference Manual
. (I adjust the Sandy Bridge formulas described in B.4 to the Haswell Microarchitecture if needed.)




Therefore I perform performance counter events measurements with Perf. There are some results I don’t understand:




  1. CPU_CLK_UNHALTED.THREAD_P < CYCLE_ACTIVITY.CYCLES_LDM_PENDING




This holds only for a few measurements, but still is weird. Does the PMU count halted cycles for CYCLE_ACTIVITY.CYCLES_LDM_PENDING?





  1. CYCLE_ACTIVITY.CYCLES_L2_PENDING > CYCLE_ACTIVITY.CYCLES_L1D_PENDING
    and CYCLE_ACTIVITY.STALLS_L2_PENDING > CYCLE_ACTIVITY.STALLS_L1D_PENDING



This applies for all measurements. When there is a L1D cache miss, the load gets transferred to the L2 cache, right? So a load missed L2 earlier also missed L1. There is the L1 instruction cache not counted here, but with *_L2_PENDING being 100x or even 1000x greater than *_L1D_PENDING it is probably not that.. Are the stalls/cycles being measured somehow separately? But than there is this formula:



%L2_Bound =
(CYCLE_ACTIVITY.STALLS_L1D_PENDING - CYCLE_ACTIVITY.STALLS_L2_PENDING) / CLOCKS



Hence CYCLE_ACTIVITY.STALLS_L2_PENDING < CYCLE_ACTIVITY.STALLS_L1D_PENDING is assumed (the result of the formula must be positive). (The other thing with this formula is that it should probably be CYCLES instead of STALLS. However this wouldn't solve the problem described above.) So how can this be explained?




edit: My OS: Ubuntu 14.04.3 LTS, kernel: 3.13.0-65-generic x86_64, perf version: 3.13.11-ckt26

php - setcookie, Cannot modify header information - headers already sent

Cookies are sent in the headers of the transmission of the HTTP page. Once you give some output, you cannot modify these anymore.



The problem in your case lies in you outputting some of the HTML-document before trying to set the cookie.



There are a few ways to solve it; one of which is setting the cookie prior to outputting anything on the page like so



    $value = 'something from somewhere';
setcookie("TestCookie", $value);
?>















Alternatively, you could buffer your output so that nothing gets written until you explicitly tell it to



    ob_start(); // Initiate the output buffer
?>









$value = 'something from somewhere';
setcookie("TestCookie", $value);
?>



ob_end_flush(); // Flush the output from the buffer
?>


For more information on this last approach, take a look at the ob_start and ob_end_flush functions.



It might be useful to read about setcookie, too.

c# - Why is there huge performance hit in 2048x2048 versus 2047x2047 array multiplication?



I am making some matrix multiplication benchmarking, as previously mentioned in
Why is MATLAB so fast in matrix multiplication?




Now I've got another issue, when multiplying two 2048x2048 matrices, there is a big difference between C# and others. When I try multiply only 2047x2047 matrices, it seems normal. Added some others for comparsion too.



1024x1024 - 10 seconds.



1027x1027 - 10 seconds.



2047x2047 - 90 seconds.



2048x2048 - 300 seconds.




2049x2049 - 91 seconds. (update)



2500x2500 - 166 seconds



That is three and a half minute difference for the 2k by 2k case.



using 2dim arrays



//Array init like this

int rozmer = 2048;
float[,] matice = new float[rozmer, rozmer];

//Main multiply code
for(int j = 0; j < rozmer; j++)
{
for (int k = 0; k < rozmer; k++)
{
float temp = 0;
for (int m = 0; m < rozmer; m++)

{
temp = temp + matice1[j,m] * matice2[m,k];
}
matice3[j, k] = temp;
}
}

Answer



This probably has do with conflicts in your L2 cache.




Cache misses on matice1 are not the problem because they are accessed sequentially.
However for matice2 if a full column fits in L2 (i.e when you access matice2[0, 0], matice2[1, 0], matice2[2, 0] ... etc, nothing gets evicted) than there is no problem with cache misses with matice2 either.



Now to go deeper in how caches works, if byte address of your variable is X, than the cache line for it would be (X >> 6) & (L - 1). Where L is total number of cache lines in your cache. L is always power of 2.
The six comes from fact that 2^6 == 64 bytes is standard size of cache line.



Now what does this mean? Well it means that if I have address X and address Y and
(X >> 6) - (Y >> 6) is divisible by L (i.e. some large power of 2), they will be stored in the same cacheline.



Now to go back to your problem what is the difference between 2048 and 2049,




when 2048 is your size:



if you take &matice2[x, k] and &matice2[y, k] the difference (&matice2[x, k] >> 6) - (&matice2[y,k] >> 6) will be divisible by 2048 * 4 (size of float). So a large power of 2.



Thus depending on size of your L2 you will have a lot of cache line conflicts, and only utilize small portion of your L2 to store a column, thus you wont actually be able to store full column in your cache, thus you will get bad performance.



When size is 2049, then the difference is 2049 * 4 which is not power of 2 thus you will have less conflicts and your column will safely fit into your cache.



Now to test this theory there are couple things you can do:




Allocate your array matice2 array like this matice2 [razmor, 4096], and run with razmor = 1024, 1025 or any size, and you should see very bad performance compared to what you had before. This is because you forcefully align all columns to conflict with each other.



Then try matice2 [razmor, 4097] and run it with any size and you should see much better performance.


java - How to fix 'android.os.NetworkOnMainThreadException'?



I got an error while running my Android project for RssReader.



Code:



URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();

RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();


And it shows the below error:



android.os.NetworkOnMainThreadException



How can I fix this issue?


Answer



This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:



class RetrieveFeedTask extends AsyncTask {

private Exception exception;


protected RSSFeed doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is = new InputSource(url.openStream());
xmlreader.parse(is);


return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;

return null;
} finally {
is.close();
}
}


protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}


How to execute the task:




In MainActivity.java file you can add this line within your oncreate() method



new RetrieveFeedTask().execute(urlToRssFeed);


Don't forget to add this to AndroidManifest.xml file:





php - Odd behaviour in a switch statement



I'm writing code for a sortable table, where clicking the links in the header change the ORDER BY executed when generating a set of search results (the case where there there is no valid order by causes the query to not be run with order by and just return the results in the order the database returns. this is as designed). The code is being written within a framework provided by my employer.




To validate the ORDER BY part of the query I run the input through the following validation function.



function sortMode ($name)
{
$mode = '';
switch ($name)
{
case 'resnum' : $mode = 'b_resnum'; break;
case 'state' : $mode = 'st_id'; break;

case 'name' : $mode = 'lastname, firstname'; break;
case 'phone' : $mode = 'phone'; break;
case 'email' : $mode = 'email'; break;
case 'opened' : $mode = 'cs_created'; break;
default : $mode = ''; break;
}
return ($mode);
}
?>



Under testing I discovered that if no parameter was provided then the sort order would be resnum. After some experimentation, I discovered that the filtering built into the framework would cause a request for an uninitialized variable such as an unset GET parameter to return integer 0. If the above code got fed a 0 integer as its input it would always follow the first path of execution available to it.



As an experiment I tried rearranging the order of the cases in the switch statement, and found whatever was at the top would be what was executed if this function was passed a 0.



The solution to the problem was using switch (strval($name)) so the particular problem is solved, but now I'm curious as to the general behaviour of PHP switch statements. Is the behaviour I witnessed the correct behaviour for PHP? Is there some fault in PHP that's causing this, or have I made an error in my code of which I'm not aware?


Answer



It's because of the way php casts strings to ints. When you pass in a 0, you are asking it to do an integer comparison, so it will convert all of your case keys to integers. When php casts a string to an int, it looks for an actual number at the beginning of the string, and gobbles the number up until it hits a non-number. Since the string "resnum" has no numbers, it returns 0. See here:



php > echo (int)"100";

100
php > echo (int)"300 dogs";
300
php > echo (int)"resnum";
0
php > echo (int)"resnum 100";
0


Since all of those strings cast to 0, the first case would evaluate to true since 0 == 0.




Resources:
String conversion to numbers
Type comparison tables






Nitpick time. When you're doing simple case statements that map a string to a string, use an array. It's much clearer and actually faster:



function sortMode ($name)
{
$modeMap = array(

'resnum' => 'b_resnum',
'state' => 'st_id',
'name' => 'lastname, firstname',
'phone' => 'phone',
'email' => 'email',
'opened' => 'cs_created'
);

return isset($modeMap[$name]) ? $modeMap[$name] : '';
}



If the $name is set in the map, we return the value that key is mapped to. Otherwise, we return an empty string, which takes the place of the default case.



As a bonus, you would have noticed the bug earlier if you did the above method, because it would be trying to access $modeMap[0] and would have returned your default case instead.


merge two arrays with a separator, javascript





I am trying to merge two arrays and have a separator included between all values (comma). I tried this:



var aAndBWithCommasInBetween = a.concat(b);


But that leads to:




DealerOrigin


instead of:



Dealer, Origin


each a and b can have many values or none.



Answer



your a and b in the example are not arrays but strings, which is why concat creates another string.



['Apple'].concat(['Orange'])
["Apple", "Orange"]


versus



"Apple".concat("Orange")

"AppleOrange"


You could be looking for array.join(), which converts an array into a single string separated by commas or whatever separator you pass in.



["Apple", "Orange"].join(',')
"Apple,Orange"

c++ - Undefined behavior and sequence points




What are "sequence points"?



What is the relation between undefined behaviour and sequence points?



I often use funny and convoluted expressions like a[++i] = i;, to make myself feel better. Why should I stop using them?



If you've read this, be sure to visit the follow-up question Undefined behavior and sequence points reloaded.





(Note: This is meant to be an entry to C++ FAQ. If you want to critique the idea of providing an FAQ in this form, then the posting on meta that started all this would be the place to do that. Answers to that question are monitored in the C++ chatroom, where the FAQ idea started out in the first place, so your answer is very likely to get read by those who came up with the idea.)


Answer



C++98 and C++03



This answer is for the older versions of the C++ standard. The C++11 and C++14 versions of the standard do not formally contain 'sequence points'; operations are 'sequenced before' or 'unsequenced' or 'indeterminately sequenced' instead. The net effect is essentially the same, but the terminology is different.






Disclaimer : Okay. This answer is a bit long. So have patience while reading it. If you already know these things, reading them again won't make you crazy.




Pre-requisites : An elementary knowledge of C++ Standard






What are Sequence Points?



The Standard says





At certain specified points in the execution sequence called sequence points, all side effects of previous evaluations
shall be complete and no side effects of subsequent evaluations shall have taken place. (§1.9/7)




Side effects? What are side effects?



Evaluation of an expression produces something and if in addition there is a change in the state of the execution environment it is said that the expression (its evaluation) has some side effect(s).



For example:




int x = y++; //where y is also an int


In addition to the initialization operation the value of y gets changed due to the side effect of ++ operator.



So far so good. Moving on to sequence points. An alternation definition of seq-points given by the comp.lang.c author Steve Summit:




Sequence point is a point in time at which the dust has settled and all side effects which have been seen so far are guaranteed to be complete.








What are the common sequence points listed in the C++ Standard ?



Those are:




  • at the end of the evaluation of full expression (§1.9/16) (A full-expression is an expression that is not a subexpression of another expression.)1




    Example :



    int a = 5; // ; is a sequence point here

  • in the evaluation of each of the following expressions after the evaluation of the first expression (§1.9/18) 2




    • a && b (§5.14)

    • a || b (§5.15)

    • a ? b : c (§5.16)


    • a , b (§5.18) (here a , b is a comma operator; in func(a,a++) , is not a comma operator, it's merely a separator between the arguments a and a++. Thus the behaviour is undefined in that case (if a is considered to be a primitive type))


  • at a function call (whether or not the function is inline), after the evaluation of all function arguments (if any) which
    takes place before execution of any expressions or statements in the function body (§1.9/17).




1 : Note : the evaluation of a full-expression can include the evaluation of subexpressions that are not lexically
part of the full-expression. For example, subexpressions involved in evaluating default argument expressions (8.3.6) are considered to be created in the expression that calls the function, not the expression that defines the default argument



2 : The operators indicated are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation and the operands form an argument list, without an implied sequence point between them.







What is Undefined Behaviour?



The Standard defines Undefined Behaviour in Section §1.3.12 as




behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements 3.




Undefined behavior may also be expected when this
International Standard omits the description of any explicit definition of behavior.




3 : permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with-
out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).



In short, undefined behaviour means anything can happen from daemons flying out of your nose to your girlfriend getting pregnant.







What is the relation between Undefined Behaviour and Sequence Points?



Before I get into that you must know the difference(s) between Undefined Behaviour, Unspecified Behaviour and Implementation Defined Behaviour.



You must also know that the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified.



For example:



int x = 5, y = 6;


int z = x++ + y++; //it is unspecified whether x++ or y++ will be evaluated first.


Another example here.






Now the Standard in §5/4 says





  • 1) Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression.



What does it mean?



Informally it means that between two sequence points a variable must not be modified more than once.
In an expression statement, the next sequence point is usually at the terminating semicolon, and the previous sequence point is at the end of the previous statement. An expression may also contain intermediate sequence points.



From the above sentence the following expressions invoke Undefined Behaviour:




i++ * ++i;   // UB, i is modified more than once btw two SPs
i = ++i; // UB, same as above
++i = 2; // UB, same as above
i = ++i + 1; // UB, same as above
++++++i; // UB, parsed as (++(++(++i)))

i = (i, ++i, ++i); // UB, there's no SP between `++i` (right most) and assignment to `i` (`i` is modified more than once btw two SPs)



But the following expressions are fine:



i = (i, ++i, 1) + 1; // well defined (AFAIK)
i = (++i, i++, i); // well defined
int j = i;
j = (++i, i++, j*i); // well defined







  • 2) Furthermore, the prior value shall be accessed only to determine the value to be stored.



What does it mean? It means if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written.



For example in i = i + 1 all the access of i (in L.H.S and in R.H.S) are directly involved in computation of the value to be written. So it is fine.



This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification.




Example 1:



std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2


Example 2:



a[i] = i++ // or a[++i] = i or a[i++] = ++i etc



is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. So the behaviour is undefined.



Example 3 :



int x = i + i++ ;// Similar to above





Follow up answer for C++11 here.



Export to excel error in PHP reports

I export reports as excel using PHP & MySql. I can export and open the file from my localhost using my source code, but unable to do in the server. When I try to export it shows
"
Warning: tempnam() [function.tempnam]: open_basedir restriction in effect. File() is not within the allowed path(s): (/home:/tmp:/usr) in /home/xx/xx.inc.php on line 205.
"
I googled through, but I'm unable get the solution.




$this->_tmpfilename=tempnam("/tmp", "excelreport");




$fh=fopen($this->_tmpfilename, "w+b");




This is the code that used. What's wrong.

Monday 30 January 2017

Python + OpenCV - Copying an image to some directory




I would like to copy some images to some directory, rather than cv2.imwrite the images. The reason is that when I use cv2.imwrite in OpenCV, I get images that are larger than the original ones, apart from that I can see that some images are being rotated.



Would that be possible in Python + OpenCV, since I don't want any operation to be made on the original image, which cv2.imwrite seems to be doing?



Thanks.


Answer



You don't need opencv to do this. You can use the shutil library.




import shutil
shutil.copyfile('path/to/1.jpg', 'new/path/to/1.jpg')


Note that the destination path must specify the filename too. If you don't want this, you can use shutil.copy2 which lets you specify a directory as the destination.



shutil.copy2('path/to/1.jpg', 'new/path/to/dir')

production - Why did the ending change in the Fight Club adaptation? - Movies & TV



Recently finishing up the book Fight Club after being a fan of the movie for so long. While the movie retains most of the dialogue and several tones of the book, one giant contrast is now present to me.




In the book, the ending goes similar to how the movie occurs. However, one glaring difference is while in the movie, the Narrator shoots himself through the cheek, doing this kills Tyler, and he and Marla stand atop the building, watching the destruction caused by Project Mayhem in a seemingly (while twisted) peaceful ending.



In the book, however,




The Narrator shoots himself, but is then put into a mental health facility until the end of his days. To me, this seems like a heavy contrast and much more depressing ending to the story compared with the movie version. Also in the book, there is more hostility towards the Narrator when he tries to stop Project Mayhem while near the end of the movie, they seem to "forgive" him by bringing Marla to him.




Is there any reason to these changes or documentation stating why Fincher decided to take these turns with the story?



Answer



Quoted from Wikipedia:




Fincher considered the novel too infatuated with Tyler Durden and changed the ending to move away from him: "I wanted people to love Tyler, but I also wanted them to be OK with his vanquishing."




Something I learned about Fight Club during an interview with Chuck Palanihuk is that he considers Fight Club a coming-of-age story; the narrator grows up and accepts his role in life by rebelling, discovering a mentor and then transcending the mentor.



After he sees through Tyler, the narrator destroys him and is then ready to choose life, apparently embarking on the kids-and-minivan-in-quiet-suburban-life with Marla. A more depressing ending than the book, from one perspective.



pass by reference - swapping of objects in java




I have studied that java is pass by reference but when I execute following code the strings are not swapped in main method why?




static void swap(String s1, String s2){
String temp = s1;
s1=s2;
s2=temp;
}

public static void main(String[] args) {
String s1 = "Hello", s2 = "world";
swap(s1, s2);

System.out.println(s1 + s2);
}

Answer



You studied wrong sources. Java is pass by value. Here is one source more you can study. And from here you can find discussion about example similar to yours.


reactjs - What is this prop syntax in my component?

Answer


Answer





I have the following code:




const cEditor = (onUpdate, props) => ();


What is being done by {...props}? It seems as if it is passing down props to the component. What does this syntax mean?


Answer



That's using spread syntax to "spread" the props to the component. Per the React documentation:




Spread Attributes




If you already have props as an object, and you want to pass it in JSX, you can use ... as a "spread" operator to pass the whole props object. These two components are equivalent:



function App1() {
return ;
}

function App2() {
const props = {firstName: 'Ben', lastName: 'Hector'};
return ;
}



Spread attributes can be useful when you are building generic containers. However, they can also make your code messy by making it easy to pass a lot of irrelevant props to components that don't care about them. We recommend that you use this syntax sparingly.




So, if you have an object with props as keys and the prop values as values, you can use spread syntax to spread them to the component. These two components are the same:



const props = {
a: 5,
b: "string"

}



Is the same as:






In your case, props in the function cEditor is an object will all the props and prop values as keys and values respectively. Then, those props and prop values are passed to the , except for onUpdate, that is passed separately

(but is overridden if props has an onUpdate key and value).


angularjs - PHP $_POST Not Returning Values

In PHP I have a form that submits data to a PHP script. The PHP script prints the values, using:



  $raw_post = file_get_contents('php://input');
print_r($raw_post);
print_r($_POST);
print_r($_REQUEST);


All of these come back empty/null arrays EXCEPT $raw_post (aka, php://input).




Chrome's Developer Tools also show that the values have been submitted through the payload as a POST request and it is a status of 200 OK, yet PHP does not set them to the $_POST array at all.



Results in the $raw_post:



{"company_name":"test","primary_contact":"test","address":"test","function":"test","phone":"test","fax":"test","url":"test"}


Results in $_POST:




Array
(
)


Results in $_REQUEST:



Array
(
)



I am unable to find a solution to this issue ... could anybody help here?



The form is submitted from AngularJS to a PHP script.



New code (url-encoded):



app.factory('Companies', function($resource) {
return $resource('/api.php/companies/:id', {id:''}, {

'query': {method: 'GET', isArray: true},
'view': {method: 'GET', isArray: true},
'save': {
method: 'POST',
isArray: true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}},
});
});

c++ - Are the days of passing const std::string & as a parameter over?



I heard a recent talk by Herb Sutter who suggested that the reasons to pass std::vector and std::string by const & are largely gone. He suggested that writing a function such as the following is now preferable:



std::string do_something ( std::string inval )
{
std::string return_val;
// ... do stuff ...
return return_val;
}


I understand that the return_val will be an rvalue at the point the function returns and can therefore be returned using move semantics, which are very cheap. However, inval is still much larger than the size of a reference (which is usually implemented as a pointer). This is because a std::string has various components including a pointer into the heap and a member char[] for short string optimization. So it seems to me that passing by reference is still a good idea.



Can anyone explain why Herb might have said this?


Answer



The reason Herb said what he said is because of cases like this.



Let's say I have function A which calls function B, which calls function C. And A passes a string through B and into C. A does not know or care about C; all A knows about is B. That is, C is an implementation detail of B.



Let's say that A is defined as follows:



void A()
{
B("value");
}


If B and C take the string by const&, then it looks something like this:



void B(const std::string &str)
{
C(str);
}

void C(const std::string &str)
{
//Do something with `str`. Does not store it.
}


All well and good. You're just passing pointers around, no copying, no moving, everyone's happy. C takes a const& because it doesn't store the string. It simply uses it.



Now, I want to make one simple change: C needs to store the string somewhere.



void C(const std::string &str)
{
//Do something with `str`.
m_str = str;
}


Hello, copy constructor and potential memory allocation (ignore the Short String Optimization (SSO)). C++11's move semantics are supposed to make it possible to remove needless copy-constructing, right? And A passes a temporary; there's no reason why C should have to copy the data. It should just abscond with what was given to it.



Except it can't. Because it takes a const&.



If I change C to take its parameter by value, that just causes B to do the copy into that parameter; I gain nothing.



So if I had just passed str by value through all of the functions, relying on std::move to shuffle the data around, we wouldn't have this problem. If someone wants to hold on to it, they can. If they don't, oh well.



Is it more expensive? Yes; moving into a value is more expensive than using references. Is it less expensive than the copy? Not for small strings with SSO. Is it worth doing?



It depends on your use case. How much do you hate memory allocations?


HTTP get Request in Kotlin and android studio

I'm completely new to Kotlin and android studio.
've URL, server UserID and Password already of my previous project.

I want to get a request with parameters using HttpURLConnection .
my problem I can't list information in textview



class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// get reference to all views

var et_user_ID = findViewById(R.id.et_user_ID) as EditText
var et_password = findViewById(R.id.et_password) as EditText
var btn_reset = findViewById(R.id.btn_reset) as Button
var btn_submit = findViewById(R.id.btn_submit) as Button
val tv1 = findViewById(R.id.tv1) as TextView

btn_reset.setOnClickListener {
// clearing user_nameId and password edit text views on reset button click
et_user_ID.setText("")
et_password.setText("")

}


btn_submit.setOnClickListener {
val userID = et_user_ID.text;
val password = et_password.text;
Toast.makeText(this@MainActivity, userID, Toast.LENGTH_LONG).show()

var reqParam = URLEncoder.encode("userID", "UTF-8") + "=" + URLEncoder.encode(userID.toString(), "UTF-8")
reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password.toString(), "UTF-8")


val mURL = URL("http://localhost:9999/information?"+reqParam)

with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "GET"


BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()


var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
it.close()
//println("Response : $response")
tv1.text = "$response"
}

}
}

}
}

c - What is the better way to check EOF and error of fgetc()?




I always use this approach




int c;
while ((c = fgetc(fp))!=EOF)
{
printf("%c", c);
}


As it seems to me more readable and robust. But to an answer of mine link, chux commented that





if ( feof(fp) ) is more robust than
int c; while ((c = fgetc(fp))!=EOF)




As



    while(1)
{
c = fgetc(fp);

if ( feof(fp) )
{
break ;
}
printf("%c", c);
}


is more robust than the first version. So what version should I use? Please explain me why that version is better.




EDIT



In question Why is “while ( !feof (file) )” always wrong? there asked why feof() in control loop always wrong. But checking feof() in if condition in proper way is always wrong? Explanation is appreciable.


Answer



I usually program input loops like this:



int c;

while (c = fgetc(fp), c != EOF) {
/* do something with c here */

}

/* check if EOF came from an end-of-file or an error */
if (ferror(fp)) {
/* error handling here */
}


You should generally not use a loop condition like this:




while (!feof(fp)) {
/* do stuff */
}


or



for (;;) {
c = fgetc(fp);
if (feof(fp))

break;
}


Because this breaks when an IO error is encountered. In this case, fgetc returns EOF but the end-of-file flag is not set. Your code could enter an infinite loop as an error condition usually persists until external action is taken.



The proper way is to check the result of fgetc(): If it's equal to EOF, you can usually stop reading further data as both in case of an IO error and an end-of-file condition, it's usually not possible to read further data. You should then check if an error occurred and take appropriate action.


datetime - How to get the current time in Python

What is the module/method used to get the current time?

Use Javascript to check if JSON object contain value




I want to check if a certain key in a JSON object like the one below contains a certain value. Let's say I want to check if the key "name", in any of the objects, has the value "Blofeld" (which is true). How can I do that?



[ {

"id" : 19,
"cost" : 400,
"name" : "Arkansas",
"height" : 198,
"weight" : 35
}, {
"id" : 21,
"cost" : 250,
"name" : "Blofeld",
"height" : 216,

"weight" : 54
}, {
"id" : 38,
"cost" : 450,
"name" : "Gollum",
"height" : 147,
"weight" : 22
} ]

Answer




you can also use Array.some() function:





const arr = [{
id: 19,
cost: 400,
name: "Arkansas",
height: 198,
weight: 35

}, {
id: 21,
cost: 250,
name: "Blofeld",
height: 216,
weight: 54
}, {
id: 38,
cost: 450,
name: "Gollum",

height: 147,
weight: 22
}];

console.log(arr.some(item => item.name === 'Blofeld'));
console.log(arr.some(item => item.name === 'Blofeld2'));

// search for object using lodash
const objToFind1 = {
id: 21,

cost: 250,
name: "Blofeld",
height: 216,
weight: 54
};
const objToFind2 = {
id: 211,
cost: 250,
name: "Blofeld",
height: 216,

weight: 54
};
console.log(arr.some(item => _.isEqual(item, objToFind1)));
console.log(arr.some(item => _.isEqual(item, objToFind2)));





What are the differences between the alternative versions of Blade Runner?

I may have lost count, but the last time I checked there were 4 different cuts of Blade Runner. The original cinema release (with the voice over and the spliced from another movie ending) followed by three different versions cut by Ridley Scott.


But what are the key differences between those versions?


Answer


Maybe this Wikipedia site is of help. To sum up the most important things:



  • 1982 Original workprint (failed in audience tests, not released):



    • no voice over

    • no happy ending

    • no unicorn dream


  • 1982 US theatrical release:



    • voice overs

    • happy ending (Deckard and Rachel drive through the countryside)

    • no unicorn dream


  • 1982 International release:



    • more violence in certain scenes


  • 1992 Director's Cut (not done by Scott, but approved by him):



    • no voice overs

    • no happy ending (Deckard and Rachel just leave Deckard's flat)

    • unicorn dream (suggesting that Deckard could be a replicant)


  • 2007 Final Cut (Scott's final version):



    • same content as Director's Cut. Plus new scene Deckard at piano and outside club.

    • many technical improvements



javascript - How to convert jQuery.serialize() data to JSON object?

Is there any better solution to convert a form data that is already serialized by jQuery function serialize(), when the form contains multiple input Array fields. I want to be able to convert the form data in to a JSON object to recreate some other informative tables. So tell me a better way to get the serialize string converted as a JSON object.





// Raf


// Bily
// bily@someemail.com


// Andy
// Andy@somwhere.com


// Adam
// Adam@herenthere.com



The jquery method applied to get the data



var MyForm = $("#sampleform").serialize();
/** result : MyName=Raf&friendname[]=Billy&fiendemail[]=bily@someemail.com&friendname[]=Andy&fiendemail[]=Andy@somwhere.com&friendname[]=Adam&fiendemail[]=Adam@herenthere.com

*/


how do I make this data in to a JSON object?
which should have the following example JSON data from the above form.



{
"MyName":"raf",
"friendname":[
{"0":"Bily"},

{"1":"Andy"},
{"2":"Adam"}
],
"friendemail":[
{"0":"bily@someemail.com"},
{"1":"Andy@somwhere.com"},
{"2":"Adam@herenthere.com"}
]
}

python - Negative list index?











I'm trying to understand the following piece of code:




# node list
n = []
for i in xrange(1, numnodes + 1):
tmp = session.newobject();
n.append(tmp)
link(n[0], n[-1])


Specifically, I don't understand what the index -1 refers to. If the index 0 refers to the first element, then what does -1 refer to?



Answer



Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.


r faq - How to make a great R reproducible example




When discussing performance with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on Stack Overflow, a reproducible example is often asked and always helpful.



What are your tips for creating an excellent example? How do you paste data structures from in a text format? What other information should you include?



Are there other tricks in addition to using dput(), dump() or structure()? When should you include library() or require() statements? Which reserved words should one avoid, in addition to c, df, data, etc.?



How does one make a great reproducible example?


Answer



A minimal reproducible example consists of the following items:




  • a minimal dataset, necessary to demonstrate the problem

  • the minimal runnable code necessary to reproduce the error, which can be run on the given dataset

  • the necessary information on the used packages, R version, and system it is run on.

  • in the case of random processes, a seed (set by set.seed()) for reproducibility1



For examples of good minimal reproducible examples, see the help files of the function you are using. In general, all the code given there fulfills the requirements of a minimal reproducible example: data is provided, minimal code is provided, and everything is runnable. Also look at questions on with lots of upvotes.



Producing a minimal dataset



For most cases, this can be easily done by just providing a vector/data frame with some values. Or you can use one of the built-in datasets, which are provided with most packages.
A comprehensive list of built-in datasets can be seen with library(help = "datasets"). There is a short description to every dataset and more information can be obtained for example with ?mtcars where 'mtcars' is one of the datasets in the list. Other packages might contain additional datasets.



Making a vector is easy. Sometimes it is necessary to add some randomness to it, and there are a whole number of functions to make that. sample() can randomize a vector, or give a random vector with only a few values. letters is a useful vector containing the alphabet. This can be used for making factors.



A few examples :




  • random values : x <- rnorm(10) for normal distribution, x <- runif(10) for uniform distribution, ...

  • a permutation of some values : x <- sample(1:10) for vector 1:10 in random order.

  • a random factor : x <- sample(letters[1:4], 20, replace = TRUE)



For matrices, one can use matrix(), eg :



matrix(1:10, ncol = 2)


Making data frames can be done using data.frame(). One should pay attention to name the entries in the data frame, and to not make it overly complicated.



An example :



set.seed(1)
Data <- data.frame(
X = sample(1:10),
Y = sample(c("yes", "no"), 10, replace = TRUE)
)


For some questions, specific formats can be needed. For these, one can use any of the provided as.someType functions : as.factor, as.Date, as.xts, ... These in combination with the vector and/or data frame tricks.



Copy your data



If you have some data that would be too difficult to construct using these tips, then you can always make a subset of your original data, using head(), subset() or the indices. Then use dput() to give us something that can be put in R immediately :



> dput(iris[1:4, ]) # first four rows of the iris data set
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa",
"versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length",
"Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
4L), class = "data.frame")


If your data frame has a factor with many levels, the dput output can be unwieldy because it will still list all the possible factor levels even if they aren't present in the the subset of your data. To solve this issue, you can use the droplevels() function. Notice below how species is a factor with only one level:



> dput(droplevels(iris[1:4, ]))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5,
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2,
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = "setosa",
class = "factor")), .Names = c("Sepal.Length", "Sepal.Width",
"Petal.Length", "Petal.Width", "Species"), row.names = c(NA,
4L), class = "data.frame")


When using dput, you may also want to include only relevant columns:



> dput(mtcars[1:3, c(2, 5, 6)]) # first three rows of columns 2, 5, and 6
structure(list(cyl = c(6, 6, 4), drat = c(3.9, 3.9, 3.85), wt = c(2.62,
2.875, 2.32)), row.names = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710"
), class = "data.frame")


One other caveat for dput is that it will not work for keyed data.table objects or for grouped tbl_df (class grouped_df) from dplyr. In these cases you can convert back to a regular data frame before sharing, dput(as.data.frame(my_data)).



Worst case scenario, you can give a text representation that can be read in using the text parameter of read.table :



zz <- "Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa"

Data <- read.table(text=zz, header = TRUE)


Producing minimal code



This should be the easy part but often isn't. What you should not do, is:




  • add all kind of data conversions. Make sure the provided data is already in the correct format (unless that is the problem of course)

  • copy-paste a whole function/chunk of code that gives an error. First, try to locate which lines exactly result in the error. More often than not you'll find out what the problem is yourself.



What you should do, is:




  • add which packages should be used if you use any (using library())

  • if you open connections or create files, add some code to close them or delete the files (using unlink())

  • if you change options, make sure the code contains a statement to revert them back to the original ones. (eg op <- par(mfrow=c(1,2)) ...some code... par(op) )

  • test run your code in a new, empty R session to make sure the code is runnable. People should be able to just copy-paste your data and your code in the console and get exactly the same as you have.



Give extra information



In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of sessionInfo() can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible also the necessary information on the setup.



If you are running R in R Studio using rstudioapi::versionInfo() can be helpful to report your RStudio version.



If you have a problem with a specific package you may want to provide the version of the package by giving the output of packageVersion("name of the package").






1 Note: The output of set.seed() differs between R >3.6.0 and previous versions. Do specify which R version you used for the random process, and don't be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use the RNGversion()-function before set.seed() (e.g.: RNGversion("3.5.2")).


css - Is it possible to change only the color of text shadow?




I have 9 differently colored buttons (red, orange, yellow, green, blue, purple, pink, off-white and slate) and I was wondering if it was possible to manipulate and alter only the color of the text-shadow CSS property for these buttons, while keeping the other values the same?



For example, I have two different classes; one is for buttons with 11px font size and the other is for 14px font size (standard across my website):



.button-11 {
font-size: 0.8em;
border-width: 0.09091em;
border-style: solid;
padding: 0 0.90909em;
text-shadow: 0.09091em 0.09091em 0 rgba(0, 0, 0, 0.5);

-webkit-box-shadow: 0 -0.09091em rgba(255, 255, 255, 0.3) inset;
-moz-box-shadow: 0 -0.09091em rgba(255, 255, 255, 0.3) inset;
box-shadow: 0 -0.09091em rgba(255, 255, 255, 0.3) inset;
}

.button-14 {
border-width: 0.07143em;
border-style: solid;
padding: 0 0.71429em;
text-shadow: 0.07143em 0.07143em 0 rgba(0, 0, 0, 0.5);

-webkit-box-shadow: 0 -0.07143em rgba(255, 255, 255, 0.3) inset;
-moz-box-shadow: 0 -0.07143em rgba(255, 255, 255, 0.3) inset;
box-shadow: 0 -0.07143em rgba(255, 255, 255, 0.3) inset;
}


For those unaware, I have two separate classes because each font size requires different values for the borders and text shadow, since I'm using the em measurement - 0.09em equates to 1px at font size 11px, and 0.07em equates to 1px at font size 14px.



So, in order to cut down on the CSS file size, it would help greatly if I could simply change the color of the text-shadow CSS properties without having to include the other values.




Does anyone know if this is possible?



Thank you.


Answer



Unfortunately, no: it seems (according to the specification) that there is no box-shadow-color property.



The above left intact, though it was addressing the wrong properties; to address the question, though it seems that the same point is true of the text-shadow property, with the text-shadow-color similarly unsupported (and non-existent in the specification).


java - what is a serial version id?




Duplicate What is a serialVersionUID and why should I use it?



Using Eclipse for some java work right now. My class name is underlined in yellow. I can either suppress the warning or just add the frickin serial id.




I dont care either way (or should i?), but what exactly IS this serial id?



thanks


Answer



It has to do with Java serialization.



When the fields of a class changes, you can no longer unserialize other versions of the class. If you try, Java will throw an exception.



However sometimes the change in fields don't matter and you want to say "unserialize anyway." To do that, you define this serial number. Now Java will use that number rather than reflection to decide whether your class definition is "different."




Finally, you can get around all this by defining your own serialization functions, and indeed many advocates insist that you should.


Transitions on the CSS display property

I'm currently designing a CSS 'mega dropdown' menu - basically a regular CSS-only dropdown menu, but one that contains different types of content.




At the moment, it appears that CSS 3 transitions don't apply to the 'display' property, i.e., you can't do any sort of transition from display: none to display: block (or any combination).



Is there a way for the second-tier menu from the above example to 'fade in' when someone hovers over one of the top level menu items?



I'm aware that you can use transitions on the visibility: property, but I can't think of a way to use that effectively.



I've also tried using height, but that just failed miserably.



I'm also aware that it's trivial to achieve this using JavaScript, but I wanted to challenge myself to use just CSS, and I think I'm coming up a little short.

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";


c++ - Poster detection in OpenCV?



I'm really new in image processing, so please sorry I'm a newbie. I tried to use the squares.cpp for detecting posters (since they usually are rectangles) without using expensive feature detectors (like SIFT). Unfortunately, the results are pretty much disappointing (as it was pretty predictable, results below).



Actually I don't care that only posters are detected, since statistically the posters are the biggest (or second biggest) rectangle in the image (decent heuristic).



The last image is the result of this code using this Hough Transofrm code (which seems working even worse!).



Any idea how to improve this code?



enter image description here



[enter image description here



enter image description here



enter image description here



enter image description here



enter image description here



enter image description here


Answer



Are you familiar at all with hough transforms? If not, I highly recommend you read up on them here The approach I would take, since it seems like your posters contrast their backgrounds quite a bit, is as follows:



Apply canny edge detection (consider changing to a HSV color space before the edge detection if rgb edge detection gives poor results) to the images, and perform a rectangular hough transform on the results of the canny. This will extract all "rectangular" shapes from your image. From there, you can look for features within the extracted rectangles (text maybe?) in order to further verify that the rectangles that you extracted are indeed posters.



One downfall of this method is that it may not work if the picture of the posters is taken at too great of an angle, but as long as the picture is taken relatively in front of the poster, you should be fine.


android - java.io.IOException: Received authentication challenge is null in ICS 4.0.3

I'm trying to logoff from the server. But it returns "0" response code with this exception. I'm using GET verb to do this.



LogCat



10-17 14:54:13.261: W/System.err(868): java.io.IOException: Received authentication challenge is null
10-17 14:54:13.284: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.processAuthHeader(HttpURLConnectionImpl.java:397)
10-17 14:54:13.284: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.processResponseHeaders(HttpURLConnectionImpl.java:345)
10-17 14:54:13.304: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:276)

10-17 14:54:13.324: W/System.err(868): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
10-17 14:54:13.324: W/System.err(868): at com.remote.synchronizer.haris.CustomHttpClient.executeGet(CustomHttpClient.java:131)
10-17 14:54:13.354: W/System.err(868): at com.remote.synchronizer.haris.OptionsActivity$1$3$1.run(OptionsActivity.java:87)
10-17 14:54:13.364: W/System.err(868): at android.os.Handler.handleCallback(Handler.java:605)
10-17 14:54:13.384: W/System.err(868): at android.os.Handler.dispatchMessage(Handler.java:92)
10-17 14:54:13.384: W/System.err(868): at android.os.Looper.loop(Looper.java:137)
10-17 14:54:13.404: W/System.err(868): at android.app.ActivityThread.main(ActivityThread.java:4424)
10-17 14:54:13.424: W/System.err(868): at java.lang.reflect.Method.invokeNative(Native Method)
10-17 14:54:13.424: W/System.err(868): at java.lang.reflect.Method.invoke(Method.java:511)
10-17 14:54:13.454: W/System.err(868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)

10-17 14:54:13.474: W/System.err(868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-17 14:54:13.474: W/System.err(868): at dalvik.system.NativeStart.main(Native Method)
10-17 14:54:13.484: E/HTTP Response(868): java.io.IOException: Received authentication challenge is null


CustomHttpClient.java



public class CustomHttpClient {

static HttpClient client = new DefaultHttpClient();

static HttpURLConnection connection = null;

public static int executePost(String url, String postParameters)
{
int response=0;

OutputStream output = null;
try
{
connection = (HttpURLConnection)new URL(url).openConnection();

System.setProperty("http.keepAlive", "false");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

connection.connect();

output = connection.getOutputStream();
output.write(postParameters.getBytes("UTF-8"));


response=connection.getResponseCode();
}
catch(Exception e)
{
e.printStackTrace();
Log.e("HTTP Response", e.toString());
}
finally {
if(connection != null) {

// connection.disconnect();
if (output != null)
try { output.close(); }
catch (IOException logOrIgnore) {}
}
}

return response;
}


public static int executeGet(String url)
{
int response=0;

//HttpURLConnection connection = null;
try
{
connection = (HttpURLConnection) new URL(url).openConnection();
System.setProperty("http.keepAlive", "false");
//connection.setRequestProperty("Accept-Charset", "UTF-8");

connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.connect();
response=connection.getResponseCode();
}
catch(Exception e)
{
e.printStackTrace();
Log.e("HTTP Response", e.toString());
}

finally {
if(connection != null) {
// connection.disconnect();
}
}
return response;
}

}



Before this I'm using DefaultHTTPClient in Gingerbird 2.3 its working perfectly but in ICS DefaultHTTPClient is not working so I need to use HttpURLConnection. POST verb is working fine.

php - I have a trouble with converting utf-8 . I am reading from file to keep in array

I'm trying to read file line by line and keeping them in array. But I have Turkish chars in that file and I tried everything to fix that problem but no result.



The file has content like:




  • Aksesuar ve Sarf / Pil / Taşınabilir Şarj Cihazı (PowerBank)

  • Aksesuar ve Sarf / Pil / Çinko

  • Aksesuar ve Sarf / Profesyonel Kaset /



You can see the Ş, ı chars. I see them as ? in array. What should I do?



Here is my code:



 public function getCategoriesByFile($fileUrl){
$file = fopen($fileUrl,"r");
$lines = array();
$last = array();
while(! feof($file))
{
$line= fgets($file);
$line = $line;
array_push($lines , $line);
}

fclose($file);

foreach($lines as $line){
$parsedLines[] = preg_replace("/\s+/"," ",preg_split('/;/', trim($line)));
}
foreach($parsedLines as $parsed){
$parse1 = rtrim($parsed[0] , " / ");
$parse2 = rtrim($parsed[1] , " / ");
array_push($last,array($parse1,$parse2));
}
return $last;
}


the output like :



  }
[2] => array(2) {
[0] => string(64) "Aksesuar ve Sarf / Pil / Taşınabilir Åarj Cihazı (PowerBank)"
[1] => string(0) ""
}
[3] => array(2) {
[0] => string(31) "Aksesuar ve Sarf / Pil / Çinko"
[1] => string(0) ""


Need your help guys. Thank you.

javascript - How to bind onclick handlers to `this` properly on React



Explanation to why this is not a duplicate: My code is already working, I have included as a comment. The question is why the this context change when I include it to click handler function.
I'm attempting a calculator project in React. The goal is to attach onclick handlers to number buttons so the numbers are displayed on the calculator display area. If the handler is written directly to render method it is working, however, if I'm trying from the ComponentDidMount I get an error this.inputDigit is not a function. How do I bind this.inputDigit(digit) properly?



import React from 'react';
import './App.css';


export default class Calculator extends React.Component {

// display of calculator initially zero
state = {
displayValue: '0'
}

//click handler function
inputDigit(digit){

const { displayValue } = this.state;
this.setState({
displayValue: displayValue+String(digit)
})
}

componentDidMount(){

//Get all number keys and attach click handler function
var numberKeys = document.getElementsByClassName("number-keys");

var myFunction = function() {
var targetNumber = Number(this.innerHTML);
return this.inputDigit(targetNumber); // This is not working
};
for (var i = 0; i < numberKeys.length; i++) {
numberKeys[i].onclick = myFunction;
}

}


render() {
const { displayValue } = this.state;
return (

{displayValue}





{/* This will Work*/}}
















)
}
}

Answer



Thats because you are writing it inside a function which is not bound,




Use



var myFunction = function() {
var targetNumber = Number(this.innerHTML);
return this.inputDigit(targetNumber);
}.bind(this);


or




const myFunction = () => {
var targetNumber = Number(this.innerHTML);
return this.inputDigit(targetNumber);
}


After this you need to bind the inputDigit function as well since it also uses setState



//click handler function

inputDigit = (digit) => {
const { displayValue } = this.state;
this.setState({
displayValue: displayValue+String(digit)
})
}


Since you want to use the button text as well, in that case you should use a separate variable in place of this to call the inputDigit function like






class Calculator extends React.Component {

// display of calculator initially zero
state = {
displayValue: '0'
}

//click handler function

inputDigit(digit){
const { displayValue } = this.state;
this.setState({
displayValue: displayValue+String(digit)
})
}

componentDidMount(){

//Get all number keys and attach click handler function

var numberKeys = document.getElementsByClassName("number-keys");
var that = this;
var myFunction = function() {
var targetNumber = Number(this.innerHTML);
console.log(targetNumber);
return that.inputDigit(targetNumber); // This is not working
};
for (var i = 0; i < numberKeys.length; i++) {
numberKeys[i].onclick = myFunction;
}


}

render() {
const { displayValue } = this.state;
return (

{displayValue}






{/* This will Work*/}















)
}
}


ReactDOM.render(, document.getElementById('app'))







javascript - How do I attach events to dynamic HTML elements with jQuery?




Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass.



For example:



$(function(){
$(".myclass").click( function() {
// do something
});
});


And my HTML might be as follows:



test1
test2
test3


That works with no problem.
However, consider if the .myclass elements were written to the page at some future time.



For example:



create link dynamically



In this case, the test4 link is created when a user clicks on a#anchor1.



The test4 link does not have the click() handler associated with it, even though it has class="myclass".



Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML. Any idea how I can fix this?


Answer



I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.



From http://api.jquery.com/live/




As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().




For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.



See http://api.jquery.com/on/



So instead of...



$(".myclass").click( function() {
// do something
});


You can write...



$('body').on('click', 'a.myclass', function() {
// do something
});


This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.



The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:



$('ul').on('click', 'li', function() {
alert( $(this).text() );
});


As long as the ul tag exists this will work (no li elements need exist yet).


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