Saturday, 1 July 2017

What does the PHP error message "Notice: Use of undefined constant" mean?



PHP is writing this error in the logs: "Notice: Use of undefined constant".



Error in logs:



PHP Notice:  Use of undefined constant department - assumed 'department' (line 5)
PHP Notice: Use of undefined constant name - assumed 'name' (line 6)
PHP Notice: Use of undefined constant email - assumed 'email' (line 7)

PHP Notice: Use of undefined constant message - assumed 'message' (line 8)


Relevant lines of code:



$department = mysql_real_escape_string($_POST[department]);
$name = mysql_real_escape_string($_POST[name]);
$email = mysql_real_escape_string($_POST[email]);
$message = mysql_real_escape_string($_POST[message]);



What does it mean and why am I seeing it?


Answer



You should quote your array keys:



$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);



As is, it was looking for constants called department, name, email, message, etc. When it doesn't find such a constant, PHP (bizarrely) interprets it as a string ('department', etc). Obviously, this can easily break if you do defined such a constant later (though it's bad style to have lower-case constants).


marvel cinematic universe - In the Avengers movie, why did the Chitauri troops die almost instantly when the portal closed?

Although the Avengers is a great movie in most aspects, it has its own faults or in need of explanations in certain situations, such as:


Why would Chitauri troops die as soon as the portal closed!? It's as if their brains were wired to mother-ship.


Why would their resistance to gravitation depend upon the portal/mother-ship!?


Answer


During the Avengers director commentary, Joss Whedon touches on this (and how he hated to take this shortcut!). He refers to it as being a sort of queen bee and drones situation. When the proverbial queen on the other side of the portal dies, all the minions lose all guidance and will to live, so they all just drop dead.


Mr. Whedon states they took this route so as to allow the fight to wrap up then and there. Otherwise they'd have to have this triumphant strike happen, the portal would close, and then the Avengers would have to spend hours hunting down all the Chitauri in New York City. That would rob the good guys of their victorious moment.


php syntax error on line 9

I have been staring at this for an hour now. It says I have an
Parse error: syntax error, unexpected '{' in line 9.



Could someone please look at this for me. Thanks in advance.





if(isset($_POST['submit']))
{
function foo($a, $b)
{
foreach(array_keys($a) as $i)
{
if(array_key_exists($i, $b){
$result[$i] = $a[$i]*$b[$i];

}else{
$result[$i] = 0;
}
}
foreach(array_keys($b) as $i)
{
if(not array_key_exists($i, $a){ //exists in b but not i a
$result[$i] = 0;
}
}

return $result
}
}

?>

javascript - Return Promise result instead of Promise in Nodejs



Background




I am trying to learn promises, and I have a promise chain I want to improve on.



Problem



While learning how to chain promises, I fail to see why anyone would rather return a promise instead of returning it's value.



Take the following example, which uses promise chaining:



let myObj = new MyClass();


myObj.getInfo()
.then(result => writeOutput(FILE_NAME, result))
.then(console.log(FILE_NAME + " complete"))
.catch(error => console.error(error));

class MyClass{

getInfo() {
return new Promise(function(fulfil, reject) {
fulfill("I like bananas");

});
}


Here I have to chain 2 times. But if I were to directly return the result from the method getInfo() instead of returning a Promise I could potentially do something like the following:



let myObj = new MyClass();

let str = myObj.getInfo();


writeOutput(FILE_NAME, str)
.then(console.log(FILE_NAME + " complete"))
.catch(error => console.error(error));


Questions



So as you can see I am a little confused.





  1. Given that getInfo() is in fact async, is it possible to achieve a similar code to the one in my second code sample?

  2. If it were possible, would it be a good idea? How would you do it?


Answer



You can only return a value from some function if that value is immediately available when that function is called (on the same tick of the event loop). Remember that return is synchronous.



If it is not available right away then you can only return a promise (or you can use a callback but here you are specifically asking about promises).



For a more detailed explanation see this answer that I wrote some time ago to a question asking on how to return a result of an AJAX call from some function. I explained why you cannot return the value but you can return a promise:






Here is another related answer - it got downvoted for some reason but I think it explains a similar issue that you're asking about her:




c - Memory allocation and addressing in Assembly

I am trying to learn assembly and there a couple of instructions whose purpose I do not fully understand.



C code




#include 

int main(int argc, char* argv[])
{
printf("Argument One - %s\n", argv[1]);
return 0;
}


Assembly




    .section    __TEXT,__text,regular,pure_instructions
.build_version macos, 10, 14
.intel_syntax noprefix
.globl _main ## -- Begin function main
.p2align 4, 0x90
_main: ## @main
## %bb.0:
push rbp
mov rbp, rsp

sub rsp, 32
lea rax, [rip + L_.str]
mov dword ptr [rbp - 4], 0
mov dword ptr [rbp - 8], edi
mov qword ptr [rbp - 16], rsi
mov rsi, qword ptr [rbp - 16]
mov rsi, qword ptr [rsi + 8]
mov rdi, rax
mov al, 0
call _printf

xor ecx, ecx
mov dword ptr [rbp - 20], eax ## 4-byte Spill
mov eax, ecx
add rsp, 32
pop rbp
ret
## -- End function
.section __TEXT,__cstring,cstring_literals
L_.str: ## @.str
.asciz "Argument One - %s\n"



.subsections_via_symbols


Q1. sub rsp, 32



Why is space allocated for 32 bytes when there are no local variables? I believe argc and argv are saved in the registers edi and rsi respectively. If its so that they can be moved onto the stack, wouldn't that require only 12 bytes?



Q2. lea rax, [rip + L_.str] and mov rdi, rax




Am I correct in understanding that L_.str has the address of the string ""Argument One - %s\n"? From what I've understood, printf gets access to this string through the register rdi. So, why doesn't the instruction mov rdi, L_.str work instead?



Q3. mov dword ptr [rbp - 4], 0



Why is zero being pushed onto the stack?



Q4. mov dword ptr [rbp - 8], edi and mov qword ptr [rbp - 16], rsi



I believe these instruction are to get argc and argv onto the stack. Is it pure convention to use edi and rsi?




Q5. mov dword ptr [rbp - 20], eax



I haven't a clue what this does.

Performance optimization strategies of last resort




There are plenty of performance questions on this site already, but it occurs to me that almost all are very problem-specific and fairly narrow. And almost all repeat the advice to avoid premature optimization.




Let's assume:




  • the code already is working correctly

  • the algorithms chosen are already optimal for the circumstances of the problem

  • the code has been measured, and the offending routines have been isolated

  • all attempts to optimize will also be measured to ensure they do not make matters worse




What I am looking for here is strategies and tricks to squeeze out up to the last few percent in a critical algorithm when there is nothing else left to do but whatever it takes.



Ideally, try to make answers language agnostic, and indicate any down-sides to the suggested strategies where applicable.



I'll add a reply with my own initial suggestions, and look forward to whatever else the community can think of.


Answer



OK, you're defining the problem to where it would seem there is not much room for improvement. That is fairly rare, in my experience. I tried to explain this in a Dr. Dobbs article in November 1993, by starting from a conventionally well-designed non-trivial program with no obvious waste and taking it through a series of optimizations until its wall-clock time was reduced from 48 seconds to 1.1 seconds, and the source code size was reduced by a factor of 4. My diagnostic tool was this. The sequence of changes was this:




  • The first problem found was use of list clusters (now called "iterators" and "container classes") accounting for over half the time. Those were replaced with fairly simple code, bringing the time down to 20 seconds.



  • Now the largest time-taker is more list-building. As a percentage, it was not so big before, but now it is because the bigger problem was removed. I find a way to speed it up, and the time drops to 17 seconds.


  • Now it is harder to find obvious culprits, but there are a few smaller ones that I can do something about, and the time drops to 13 sec.




Now I seem to have hit a wall. The samples are telling me exactly what it is doing, but I can't seem to find anything that I can improve. Then I reflect on the basic design of the program, on its transaction-driven structure, and ask if all the list-searching that it is doing is actually mandated by the requirements of the problem.



Then I hit upon a re-design, where the program code is actually generated (via preprocessor macros) from a smaller set of source, and in which the program is not constantly figuring out things that the programmer knows are fairly predictable. In other words, don't "interpret" the sequence of things to do, "compile" it.




  • That redesign is done, shrinking the source code by a factor of 4, and the time is reduced to 10 seconds.




Now, because it's getting so quick, it's hard to sample, so I give it 10 times as much work to do, but the following times are based on the original workload.




  • More diagnosis reveals that it is spending time in queue-management. In-lining these reduces the time to 7 seconds.


  • Now a big time-taker is the diagnostic printing I had been doing. Flush that - 4 seconds.


  • Now the biggest time-takers are calls to malloc and free. Recycle objects - 2.6 seconds.


  • Continuing to sample, I still find operations that are not strictly necessary - 1.1 seconds.





Total speedup factor: 43.6



Now no two programs are alike, but in non-toy software I've always seen a progression like this. First you get the easy stuff, and then the more difficult, until you get to a point of diminishing returns. Then the insight you gain may well lead to a redesign, starting a new round of speedups, until you again hit diminishing returns. Now this is the point at which it might make sense to wonder whether ++i or i++ or for(;;) or while(1) are faster: the kinds of questions I see so often on Stack Overflow.



P.S. It may be wondered why I didn't use a profiler. The answer is that almost every one of these "problems" was a function call site, which stack samples pinpoint. Profilers, even today, are just barely coming around to the idea that statements and call instructions are more important to locate, and easier to fix, than whole functions.



I actually built a profiler to do this, but for a real down-and-dirty intimacy with what the code is doing, there's no substitute for getting your fingers right in it. It is not an issue that the number of samples is small, because none of the problems being found are so tiny that they are easily missed.



ADDED: jerryjvl requested some examples. Here is the first problem. It consists of a small number of separate lines of code, together taking over half the time:




 /* IF ALL TASKS DONE, SEND ITC_ACKOP, AND DELETE OP */
if (ptop->current_task >= ILST_LENGTH(ptop->tasklist){
. . .
/* FOR EACH OPERATION REQUEST */
for ( ptop = ILST_FIRST(oplist); ptop != NULL; ptop = ILST_NEXT(oplist, ptop)){
. . .
/* GET CURRENT TASK */
ptask = ILST_NTH(ptop->tasklist, ptop->current_task)



These were using the list cluster ILST (similar to a list class). They are implemented in the usual way, with "information hiding" meaning that the users of the class were not supposed to have to care how they were implemented. When these lines were written (out of roughly 800 lines of code) thought was not given to the idea that these could be a "bottleneck" (I hate that word). They are simply the recommended way to do things. It is easy to say in hindsight that these should have been avoided, but in my experience all performance problems are like that. In general, it is good to try to avoid creating performance problems. It is even better to find and fix the ones that are created, even though they "should have been avoided" (in hindsight). I hope that gives a bit of the flavor.



Here is the second problem, in two separate lines:



 /* ADD TASK TO TASK LIST */
ILST_APPEND(ptop->tasklist, ptask)
. . .
/* ADD TRANSACTION TO TRANSACTION QUEUE */
ILST_APPEND(trnque, ptrn)



These are building lists by appending items to their ends. (The fix was to collect the items in arrays, and build the lists all at once.) The interesting thing is that these statements only cost (i.e. were on the call stack) 3/48 of the original time, so they were not in fact a big problem at the beginning. However, after removing the first problem, they cost 3/20 of the time and so were now a "bigger fish". In general, that's how it goes.



I might add that this project was distilled from a real project I helped on. In that project, the performance problems were far more dramatic (as were the speedups), such as calling a database-access routine within an inner loop to see if a task was finished.



REFERENCE ADDED:
The source code, both original and redesigned, can be found in www.ddj.com, for 1993, in file 9311.zip, files slug.asc and slug.zip.



EDIT 2011/11/26:

There is now a SourceForge project containing source code in Visual C++ and a blow-by-blow description of how it was tuned. It only goes through the first half of the scenario described above, and it doesn't follow exactly the same sequence, but still gets a 2-3 order of magnitude speedup.


c++ - Why can't gcc deduce templated size for array argument? (C++11)



The following code gives a compiler error (gcc-4.7 run with -std=c++11):



#include 
#include

template
std::ostream & operator <<(std::ostream & os, const std::array & arr) {
int i;
for (i=0; i os << arr[i] << " ";
os << arr[i];
return os;
}

int main() {
std::array lower{1.0, 1.0};
std::cout << lower << std::endl;
return 0;
}


Error message:




tmp6.cpp: In function ‘int main()’: tmp6.cpp:16:16: error: cannot bind
‘std::ostream {aka std::basic_ostream}’ lvalue to
‘std::basic_ostream&&’ In file included from
/usr/include/c++/4.7/iostream:40:0,
from tmp6.cpp:1: /usr/include/c++/4.7/ostream:600:5: error:
initializing argument 1 of ‘std::basic_ostream<_CharT,
_Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits; _Tp = std::array]’




When I get rid of the template function declaration and replace T with double and N with 2, it compiles just fine (edit: leaving T and replacing N with 2 works, but specifying N=2 as the default argument for N doesn't work.).




  1. Does anyone know why gcc can't automatically bind this?

  2. What would be the syntax for calling the << operator with explicitly specified template parameters?



Answer to question 2: operator<<(std::cout, lower);



Edit: This is also true for the following function, which is only templated in the array size:



template 
void print(const std::array & arr) {
std::cout << "print array here" << std::endl;
}

int main() {
std::array lower{1.0, 1.0};
print<2>(lower); // this works
print(lower); // this does NOT work
return 0;
}


Thanks a lot for your help.


Answer



Consider your declaration:



template 
std::ostream & operator <<(std::ostream & os, const std::array & arr) {


The definition for std::array is:



template class array {...};


You are using int instead of std::size_t, and that's why it doesn't match.


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