Monday, 1 October 2018

plot explanation - Verifying Contents of the Book in "The Book of Eli"? - Movies & TV



In the Movie, "The Book of Eli", after getting the book in his hands, why did he (the town's mayor or whatever) not ask Eli for the key on the spot to verify the contents of the book?


Answer



I do not know the answer, however I give a logical reason for Carnegie's actions which is the meat of the question




Carnegie (the town's mayor) has been searching for the book for some time. He believes that the Bible is a source of power that will allow him to build more towns and control people. Eli's first encounter with Carnegie, Carnegie considers killing him until he finds out that Eli is a learned man.



Carnegie makes a offer and sweetens the deal with Carnegie's blind concubine Claudia's daughter Solara. However Solara finds out Eli is not easily swayed by offers of the flesh. Carnegie stumbles across the fact that Eli has a Bible (supposedly the last one).



Eli escapes and Solara follows him, Carnegie chases them to the house with the old cannibals. At this point the excitement gets the better of him and he grabs the book without asking about the key. Once he has the book he leaves to go back to town with Solara in tow in which she causes issues. Carnegie is forced to return to town due to low gas.



So logically the answer is either:





  1. Carnegie is so excited to get the book he forgets the key, fiquring the Engineer can open the book. More so he is prevented from returning due to the actions of Solara.


  2. Plot hole



Java regex - erase characters followed by b (backspace)



I have a string constructed from user keyboard types, so it might contain '\b' characters (backspaces).



I want to clean the string, so that it will not contain the '\b' characters, as well as the characters they are meant to erase. For instance, the string:



String str = "\bHellow\b world!!!\b\b\b.";


Should be printed as:




Hello world.


I have tried a few things with replaceAll, and what I have now is:



System.out.println(str.replaceAll("^\b+|.\b+", ""));


Which prints:





Hello world!!.




Single '\b' is handled fine, but multiples of it are ignored.



So, can I solve it with Java's regex?



EDIT:




I have seen this answer, but it seem to not apply for java's replaceAll.
Maybe I'm missing something with the verbatim string...


Answer



It can't be done in one pass unless there is a practical limit on the number of consecutive backspaces (which there isn't), and there is a guarantee (which there isn't) that there are no "extra" backspaces for which there is no preceding character to delete.



This does the job (it's only 2 small lines):



while (str.contains("\b"))
str = str.replaceAll("^\b+|[^\b]\b", "");



This handles the edge case of input like "x\b\by" which has an extra backspace at the start, which should be trimmed once the first one consumes the x, leaving just "y".


Red's parole hearings in The Shawshank Redemption

In The Shawshank Redemption (1994) Red has three parole hearings. For the first two, in 1947 (YouTube link) and in 1957, he tells the parole board what he thinks they want to hear, and is unsuccessful. In his third in 1967 (YouTube link) he takes a different approach, saying, quoting from the IMDB quotes page:



1967 Parole Hearings Man: Ellis Boyd Redding, your files say you've served 40 years of a life sentence. Do you feel you've been rehabilitated?


Red: Rehabilitated? Well, now let me see. You know, I don't have any idea what that means.


1967 Parole Hearings Man: Well, it means that you're ready to rejoin society...


Red: I know what you think it means, sonny. To me it's just a made up word. A politician's word, so young fellas like yourself can wear a suit and a tie, and have a job. What do you really want to know? Am I sorry for what I did?


1967 Parole Hearings Man: Well, are you?


Red: There's not a day goes by I don't feel regret. Not because I'm in here, or because you think I should. I look back on the way I was then: a young, stupid kid who committed that terrible crime. I want to talk to him. I want to try and talk some sense to him, tell him the way things are. But I can't. That kid's long gone and this old man is all that's left. I got to live with that. Rehabilitated? It's just a bullshit word. So you go on and stamp your form, sonny, and stop wasting my time. Because to tell you the truth, I don't give a shit.



Red is then granted parole. Why, after this disparaging and weary speech? Was it because he was being so bluntly honest? Was intimidation a factor?


Answer


I'm not sure if I'd agree with parts of Wbogacz answer. The Humility part specifically. I always got a more resigned vibe from Red.


He doesn't believe that the board will really grant his parole, and as such doesn't see the point in lying to them. He is honesty, sincere and expresses true regret for his actions, rather than trying to convince the board that he's been "Rehabilitated" as he did in the prior attempts.


I don't think there was any intimidation either, if I recall the scene correctly Red was sat in a relaxed pose for the interview, not in a leaning forward threatening manner.


javascript - how can splice item if item existing in array?

i have one line code like this




$scope.selectItem.push(item['id']);


now i want check if item['id'] existing in $scope.selectItem splice it.



any idea Honorable

c++ - undefined reference to CLASS::function()




So when I try to simply compile my code using "g++ Asg5.cpp" I receive the following error




/tmp/cczhpSGO.o: In function 'main':



Asg5.cpp:(.text+0x2fb): undefined reference to 'BinomialTree::insert(int)'



collect2: ld returned 1 exit status





If anyone's wondering why I'm not using a makefile, my professor simply wants to type g++ <.cpp with main()> to compile..



Anyway here's my code I really appreciate the assistance!



Asg5.cpp



#include "BinomialTree.h"
#include "BinomialNode.h"
#include
#include

#include
#include
#include
#include
#include

using namespace std;
int main(int argc, char* argv[])
{
//input handling

if(argc != 2)
{
cout << "Incorrect Usage. \n Example: ./a.out " << endl;
exit(1);
}
BinomialTree *tree = new BinomialTree();

char *buffer;
char *token;
//read file into buffer.**************************************

string input;
ifstream file;
file.open(argv[1]);
if(file.is_open())
{
string str;
while(file.good())
{
getline(file,str);
input += " " + str;

}
}
else{
cout << "File not found"<< endl;
return 1;
}
file.close();

int buf;
stringstream ss(input);


vector tokens;

while(ss >> buf)
{
tokens.push_back(buf);
}
int i = 0;
for(i = 0; i < tokens.size(); i++)
tree->insert(tokens[i]);

//end file reading *******************************************
delete tree;
}


BinomialNode.h



#ifndef _BINOMIALNODE_H_
#define _BINOMIALNODE_H_
#include "BinomialTree.h"

class BinomialNode
{
public:
int k;
BinomialNode *children[20];
int data;

BinomialNode();
};
#endif



BinomialNode.cpp



class BinomialNode
{
BinomialNode::BinomialNode(int n)
{
this->k = 0;
this->data = n;

}
}


BinomialTree.h



#ifndef _MULTIMAP_H_
#define _MULTIMAP_H_
#include "BinomialNode.h"


class BinomialTree
{
public:
BinomialNode * BQ[20];


void insert(int n);
void merge(BinomialNode *queue, BinomialNode *in, int k);
void print(BinomialNode *root, int tab);
};

#endif


BinomialTree.cpp



#include "BinomialNode.h"
#include "BinomialTree.h"
#include
#include



class BinomialTree
{
void BinomialTree::insert(int n)
{
BinomialNode *in = new BinomialNode(n);
if(BQ[0] == NULL)
{
BQ[0] = in;
return;

}
else
merge(BQ[0], in, 0);
}
void BinomialTree::merge(BinomialNode *queue, BinomialNode *in, int k)
{
if(queue == NULL)
{
BQ[k] = in;
return;

}
if(n == NULL)
{
BQ[k] = queue;
return;
}
if(queue->data > in->data)
{
merge(in, queue);
return;

}
queue->k++;
BinomialNode* temp[queue->k];
int i;
for(i = 0; i < queue->k-1; i++)
temp[i] = queue->children[i];
temp[queue->k-1] = in;
for(i = 0; i < queue->k; i++)
queue->children[i] = temp[i];
if(BQ[queue->k] == NULL)

{
BQ[queue->k] = queue;
return;
}
else
merge(queue, BQ[queue->k]);
}
void BinomialTree::print(BinomialNode *root, int tab)
{
if(root == NULL)

return;
int i;
for(i = 0; i < tab*5; i++) cout << " ";
cout << root->data << endl;
for(i = 0; i < root->k; i++) print(root->children[i], tab+1);
}
}

Answer



You cpp files shouldn't have Class in them. They should look more like:




BinomialNode.cpp



#include "BinomialNode.h"

BinomialNode::BinomialNode(int n) :
k(0)
{
data = n;
}



And of course the corollary for the much longer BinomialTree.cpp. Also, you should compile it with something like:



g++ BinomialTree.cpp BinomialNode.cpp Asg5.cpp -o asg5


Also you're going to run into a lot of other problems with you code. For instance:



BinomialNode * BQ[20];



I don't see BQ being initialized anywhere, which means you're pretty much guaranteed a seg fault if you were to run this. You need to initialize this or allocate it. Seeing lines like:



if(BQ[0] == NULL)


Makes me think you really wanted:



BinomialNode BQ[20];



Though you would still need to initialize it to all NULLs since you aren't guaranteed that will be full of NULLs when you run the program. Also, this is recursive and infinite and can't possibly work (in BinomialNode.h):



BinomialNode *children[20];


There are likely more issues with this code, but that wasn't your question, so I'll stop now!


MySQL and PHP: UTF-8 with Cyrillic characters




I'm trying to insert a Cyrillic value in the MySQL table, but there is a problem with encoding.



Php:




$servername = "localhost";
$username = "a";
$password = "b";

$dbname = "c";

$conn = new mysqli($servername, $username, $password, $dbname);

mysql_query("SET NAMES 'utf8';");
mysql_query("SET CHARACTER SET 'utf8';");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci';");

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

}

$sql = "UPDATE `c`.`mainp` SET `search` = 'test тест' WHERE `mainp`.`id` =1;";

if ($conn->query($sql) === TRUE) {
}
$conn->close();

?>



MySQL:



| id |    search   |            
| 1 | test ав |


Note: PHP file is utf-8, database collation utf8_general_ci


Answer





You are mixing APIs here, mysql_* and mysqli_* doesn't mix. You should stick with mysqli_ (as it seems you are anyway), as mysql_* functions are deprecated, and removed entirely in PHP7.




Your actual issue is a charset problem somewhere. Here's a few pointers which can help you get the right charset for your application. This covers most of the general problems one can face when developing a PHP/MySQL application.




  • ALL attributes throughout your application must be set to UTF-8

  • Save the document as UTF-8 w/o BOM (If you're using Notepad++, it's Format -> Convert to UTF-8 w/o BOM)

  • The header in both PHP and HTML should be set to UTF-8





    • HTML (inside tags):





    • PHP (at the top of your file, before any output):



      header('Content-Type: text/html; charset=utf-8');



  • Upon connecting to the database, set the charset to UTF-8 for your connection-object, like this (directly after connecting)



    mysqli_set_charset($conn, "utf8"); /* Procedural approach */
    $conn->set_charset("utf8"); /* Object-oriented approach */


    This is for mysqli_*, there are similar ones for mysql_* and PDO (see bottom of this answer).


  • Also make sure your database and tables are set to UTF-8, you can do that like this:



    ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;

    ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;


    (Any data already stored won't be converted to the proper charset, so you'll need to do this with a clean database, or update the data after doing this if there are broken characters).







  • If you're using json_encode(), you might need to apply the JSON_UNESCAPED_UNICODE flag, otherwise it will convert special characters to their hexadecimal equivalent.




Remember that EVERYTHING in your entire pipeline of code needs to be set to UFT-8, otherwise you might experience broken characters in your application.



In addition to this list, there may be functions that has a specific parameter for specifying a charset. The manual will tell you about this (an example is htmlspecialchars()).



There are also special functions for multibyte characters, example: strtolower() won't lower multibyte characters, for that you'll have to use mb_strtolower(), see this live demo.




Note 1: Notice that its someplace noted as utf-8 (with a dash), and someplace as utf8 (without it). It's important that you know when to use which, as they usually aren't interchangeable. For example, HTML and PHP wants utf-8, but MySQL doesn't.




Note 2: In MySQL, "charset" and "collation" is not the same thing, see Difference between Encoding and collation?. Both should be set to utf-8 though; generally collation should be either utf8_general_ci or utf8_unicode_ci, see UTF-8: General? Bin? Unicode?.



Note 3: If you're using emojis, MySQL needs to be specified with an utf8mb4 charset instead of the standard utf8, both in the database and the connection. HTML and PHP will just have UTF-8.







Setting UTF-8 with mysql_ and PDO





  • PDO: This is done in the DSN of your object. Note the charset attribute,



    $pdo = new PDO("mysql:host=localhost;dbname=database;charset=utf8", "user", "pass");

  • mysql_: This is done very similar to mysqli_*, but it doesn't take the connection-object as the first argument.



    mysql_set_charset('utf8');



jquery - JavaScript: Global variables after Ajax requests




the question is fairly simple and technical:



var it_works = false;


$.post("some_file.php", '', function(data) {

it_works = true;

});

alert(it_works); # false (yes, that 'alert' has to be here and not inside $.post itself)



What I want to achieve is:



alert(it_works); # true


Is there a way to do that? If not can $.post() return a value to be applied to it_works?


Answer



What you expect is the synchronous (blocking) type request.



var it_works = false;


jQuery.ajax({
type: "POST",
url: 'some_file.php',
success: function (data) {
it_works = true;
},
async: false // <- this turns it into synchronous
});​


// Execution is BLOCKED until request finishes.

// it_works is available
alert(it_works);


Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.



Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.







The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:



$.post("some_file.php", '', function(data) {
iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
// You should do your work here that depends on the result of the request!

alert(param)
}

// All code here should be INDEPENDENT of the result of your AJAX request
// ...



Asynchronous programming is slightly more complicated because the consequence
of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly

better
because they will not see a sluggish server or sluggish network cause the
browser to act as though it had crashed. Synchronous programming is disrespectful
and should not be employed in applications which are used by people.




Douglas Crockford (YUI Blog)


php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...