Sunday, February 25, 2018

data structures - Array versus linked-list



Why would someone want to use a linked-list over an array?



Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort.



I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array?




This question is not a duplicate of this question because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures.


Answer




  • It's easier to store data of different sizes in a linked list. An array assumes every element is exactly the same size.

  • As you mentioned, it's easier for a linked list to grow organically. An array's size needs to be known ahead of time, or re-created when it needs to grow.

  • Shuffling a linked list is just a matter of changing what points to what. Shuffling an array is more complicated and/or takes more memory.

  • As long as your iterations all happen in a "foreach" context, you don't lose any performance in iteration.


html - Detect click on via PHP





Is there a way to detect a click on a HTML button in PHP, or do I really need to put a form tag around the element and make it an input submit button.





OR







Thanks in advance.


Answer



PHP is a server-side language. If you'd like to tell a server-side script about clicks on HTML elements, you have to either submit the form or use AJAX.


Saturday, February 24, 2018

plot explanation - Are the teletubbies cyborgs?

Look at the evidence:


enter image description here


As the name suggests, they have implanted televisions!


Were they born that way or did they undergo some fiendish experiment?


Answer


I would suggest that the Teletubbies are not cyborgs.


The peculiar antenna and visual display appendages are naturally occurring adaptations which allow them to exist in symbiotic harmony with humans.


They display a distinct and uncontrollable physiological requirement for the reception of (mostly) childrens basic and crucially, innocent thought patterns. This coupled with our own natural requirement for congnative and social development; the 'Tubbies' use their individual personalities and applicable talents to display moral and ethical guidance, through the performance of simplistic song, dance and play scenarios...


I would therefore classify them as Symbiote.


javascript - how to simplify this statement using indexOf?




How can I simplfy the following text inside the if statement in Javascript using "indexof"?



if (a === 1 || a === 2 || a === 3) {

return "correct";
};


I am guessing an array needs to be made for 1,2, and 3, but am unsure of how to us instanceof after that



*edited to say indexOf instead of instanceOf


Answer




The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.





In your case, instanceof wont help you. You can use indexOf() with array as follow.



var arr = [1, 2, 3];

// Check if a is present in the arr array
if (arr.indexOf(a) > -1) {
return "correct";
}


php - "Warning: Cannot modify header information - headers already sent by" error











i keep receiving this error each time i try to submit the a form deletion form.




Warning: Cannot modify header
information - headers already sent by
(output started at
C:\xampp\htdocs\speedycms\deleteclient.php:47)

in
C:\xampp\htdocs\speedycms\deleteclient.php
on line 106




is there something wrong with my code? what do i need to change to make it work?



if (!isset($_SESSION)) {
session_start();

}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;

// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.

// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.

if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}


$MM_restrictGoTo = "login.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;

}
?>

require_once('Connections/speedycms.php');

$client_id = mysql_real_escape_string($_GET['id']);

$con = mysql_connect($hostname_speedycms, $username_speedycms, $password_speedycms);


if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("speedycms") or die(mysql_error());
?>

if (!function_exists("GetSQLValueString")) {

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":

$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":

$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}


if ((isset($_GET['id'])) && ($_GET['id'] != "") && (isset($_POST['deleteForm']))) {
$deleteSQL = sprintf("DELETE FROM tbl_accident WHERE id=%s",
GetSQLValueString($_GET['id'], "int"));

mysql_select_db($database_speedycms, $speedycms);
$Result1 = mysql_query($deleteSQL, $speedycms) or die(mysql_error());

$deleteGoTo = "progress.php";
if (isset($_SERVER['QUERY_STRING'])) {
$deleteGoTo .= (strpos($deleteGoTo, '?')) ? "&" : "?";

$deleteGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $deleteGoTo));
}

mysql_select_db($database_speedycms, $speedycms);
$query_delete = "SELECT * FROM tbl_accident WHERE id=$client_id";
$delete = mysql_query($query_delete, $speedycms) or die(mysql_error());
$row_delete = mysql_fetch_assoc($delete);
$totalRows_delete = mysql_num_rows($delete);

?>

Are you sure you wish to delete the record for ?











thanking you in advance!


Answer



Lines 45-47:



?>




That's sending a couple of newlines as output, so the headers are already dispatched. Just remove those 3 lines (it's all one big PHP block after all, no need to end PHP parsing and then start it again), as well as the similar block on lines 60-62, and it'll work.



Notice that the error message you got actually gives you a lot of information to help you find this yourself:




Warning: Cannot modify header
information - headers already sent by
(output started at
C:\xampp\htdocs\speedycms\deleteclient.php:47
)
in

C:\xampp\htdocs\speedycms\deleteclient.php
on line 106




The two bolded sections tell you where the item is that sent output before the headers (line 47) and where the item is that was trying to send a header after output (line 106).


javascript - Node.js wait for all files read in the loop



I am new to the javascript/node.js event driven paradigm.




I need to stop the for after forEach to make sure all files have been read and then I continue. How should I implement wait_for_all_files_read() in this context?



my_list.forEach(function(element) {
fs.readFile(element.file_path, function(err, data) {
if(err) throw err;
element.obj=JSON.parse(data);
});
});
wait_for_all_files_read(); <-----------
analyze(my_list)



Neither solution [1] or [2] work for me.


Answer



How I would do that:




  1. Promisify fs.readFile (by using, for example Bluebird)

  2. Mark the function as async

  3. Make a list of callbacks (my_list.map instead of forEach)


  4. "await Promise.all(myListOfCallbacks)"

  5. Next line after await will be executed after all the operations been finished



Something like that:





const {promisisfy} = require('util')
const fs = require('fs')

const readFile = promisify(fs.readFile)

const fileNames = getFilenamesArray();

async function executeMe() {
try {
const arrayWithFilesContent = await Promise.all(
fileNames.map(name => readFile(name))
);
return analyze(arrayWithFilesContent);

}
catch (err) {
handleError(err)
}
}

executeMe();





regex - Regular expression to match a line that doesn't contain a word



I know it's possible to match a word and then reverse the matches using other tools (e.g. grep -v). However, is it possible to match lines that do not contain a specific word, e.g. hede, using a regular expression?



Input:



hoho
hihi
haha

hede


Code:



grep "" input


Desired output:




hoho
hihi
haha

Answer



The notion that regex doesn't support inverse matching is not entirely true. You can mimic this behavior by using negative look-arounds:



^((?!hede).)*$



The regex above will match any string, or line without a line break, not containing the (sub)string 'hede'. As mentioned, this is not something regex is "good" at (or should do), but still, it is possible.



And if you need to match line break chars as well, use the DOT-ALL modifier (the trailing s in the following pattern):



/^((?!hede).)*$/s


or use it inline:



/(?s)^((?!hede).)*$/



(where the /.../ are the regex delimiters, i.e., not part of the pattern)



If the DOT-ALL modifier is not available, you can mimic the same behavior with the character class [\s\S]:



/^((?!hede)[\s\S])*$/


Explanation




A string is just a list of n characters. Before, and after each character, there's an empty string. So a list of n characters will have n+1 empty strings. Consider the string "ABhedeCD":



    ┌──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┬───┬──┐
S = │e1│ A │e2│ B │e3│ h │e4│ e │e5│ d │e6│ e │e7│ C │e8│ D │e9│
└──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┴───┴──┘

index 0 1 2 3 4 5 6 7



where the e's are the empty strings. The regex (?!hede). looks ahead to see if there's no substring "hede" to be seen, and if that is the case (so something else is seen), then the . (dot) will match any character except a line break. Look-arounds are also called zero-width-assertions because they don't consume any characters. They only assert/validate something.



So, in my example, every empty string is first validated to see if there's no "hede" up ahead, before a character is consumed by the . (dot). The regex (?!hede). will do that only once, so it is wrapped in a group, and repeated zero or more times: ((?!hede).)*. Finally, the start- and end-of-input are anchored to make sure the entire input is consumed: ^((?!hede).)*$



As you can see, the input "ABhedeCD" will fail because on e3, the regex (?!hede) fails (there is "hede" up ahead!).


plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...