So, here is the question (https://www.hackerrank.com/challenges/library-fine) I am trying to solve. To solve this, I created a simple function calculateFine and set the conditions to calculate the fine. What's the problem, then? Well, when I run the code on my machine, everything seems fine, but hackerrank won't accept the code. I am new to PHP and concept of functions was a bit confusing for me, but I tried. Below is my code:
<?php
$_fp = fopen("php://stdin", "r");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
$_a = explode(" ",fgets($_fp));
$_b = explode(" ",fgets($_fp));
// Initialising variable
$_fine = "";
// Calling Function
calculateFine($_a,$_b);
// Defining Function
function calculateFine($actualDate, $returnDate)
{
// Checking various conditions
if ($actualDate[0] <= $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_fine = 0;
echo $_fine;
}
elseif($actualDate[0] > $returnDate[0] && $actualDate[1] == $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[0] - $returnDate[0];
$_fine = 15*$_late;
echo $_fine;
}
elseif($actualDate[1] > $returnDate[1] && $actualDate[2] == $returnDate[2])
{
$_late = $actualDate[1] - $returnDate[1];
$_fine = 500*$_late;
echo $_fine;
}
elseif($actualDate[2] > $returnDate[2])
{
$_fine = 10000;
echo $_fine;
}
else
{
$_fine = 0;
echo $fine; // Updated (This is the undefined variable causing error )
}
}
?>
It seems there's a newline in $actualDate[2]. So if you trim it you'll get the right answer:
trim($actualDate[2])
But would be better to trim it here already:
$_a = explode(" ",trim(fgets($_fp)));
$_b = explode(" ",trim(fgets($_fp)));
I got it, sorry for the carelessness. The last echo is $fine instead of $_fine. That's why the condition was not matching with some of the test cases. Thankyou.
Related
I am sorry to ask such a question but am bit confused about this.
I am having simple variables defined.
$a =1;
$b=2;
$c=3;
$d="";
for($i=0;$i<10;$i++)
{
$testa = 1;
$testb = 4;
$testc = 3;
$testd = 7;
if($a!="" || $b!="" || $c!="" || $d!="") {
if($a==$testa && $b==$testb && $c==$testc && $d==$testd) {
echo $testa;
echo $testb;
echo $testc;
echo $testd;
}
}
}
This is sample php code.
what I need is that I have variables defined at top. SO in my loop i want to display result if user has any 1 variable but in below loop display result based on "and" parameter.
I actually want to skip the empty variable. SO in this case, I want as $d is empty, so it should be prevented somehow from if($a==$testa && $b==$testb && $c==$testc && $d==$testd) from here.
Any help is really appreciated.
To skip the empty values from the check, use ||
if ( ... && (empty($d) || $d == $testd)) {
Then if you also want to skip it in your echos :
echo !empty($d) ? $testd : '';
I'm trying to do a loop that display a few conditions based on load average and cpus/memory etc. However, it seems like it only pull the usage information once for the entire loop. I want it to update it on each loop: Here's what I got, any kind of help on this is great appreciated!
<?php
exec("cat /proc/cpuinfo | grep processor | wc -l",$processors);
$totalc=$processors[0];
function sys_getloadavg_hack()
{
$str = substr(strrchr(shell_exec("uptime"),":"),1);
$avs = array_map("trim",explode(",",$str));
return $avs;
}
$load = sys_getloadavg_hack();
function get_memory() {
foreach(file('/proc/meminfo') as $ri)
$m[strtok($ri, ':')] = strtok('');
return 100 - round(($m['MemFree'] + $m['Buffers'] + $m['Cached']) / $m['MemTotal'] * 100);
}
function print_exec(){
$out_arr=array();
$last_line=exec("mpstat",$out_arr);
return $last_line;
}
for ($i=1; $i<=50; $i++)
{
$memory = get_memory();
$cpu = substr(print_exec(),-5);
if($memory>"10" && $cpu>"10" && $load[0]<$totalc) {
echo "Everything is good!";
} else {
}
echo "Memory: $memory || CPU: $cpu || Load AVG: $load[0] || #CPU's: $totalc<br> || #Runtime: $i\n\n";
usleep(800000);
}
?>
You have to make all calculations every loop.
For example: You call sys_getloadavg_hack() only once before your loop.
Try to add the sys_getloadavg_hack() call in the for loop.
for(...)
{
$load = sys_getloadavg_hack();
...
}
I have a function that will take an id and with that find out other information in the database relating to it spread among 3 tables. It then compares this to a csv file which at most times is cpu intensive. Running this once with one id takes approx 8 to 10 sec at most but I have been asked to have it run automatically across a varing number of ids in the database. To do this I created an array of the ids that match the criteria in the database at any point and then run a 'while' statement to repeat the function for each element in the array but it gets as far as maybe 4 of them and I get the following error:
Server error!
The server encountered an internal error and was unable to complete
your request. Either the server is overloaded or there was an error in
a CGI script.
If you think this is a server error, please contact the webmaster.
Error 500
I'll admit that my code could be much much cleaner as I'm still learning as I go but the real bottle neck appears to be reading the csv which is a report which size changes each day. I have tried different combinations and the best result is (please don't chastise me for this as I know it is stupid but the other ways haven't works as of yet) to run the code as follows:
$eventArray = eventArray($venueId);
$totalEvents = count($eventArray);
for($i=0; $i<$totalEvents; $i++)
{
$eventId = $eventArray[$i];
echo $eventId;
echo $datename = getEventDetails($eventId, $zone);
// date of event
echo $eventDate = $datename['eventDate'];
// vs team
echo $eventName = $datename['eventName'];
$file_handle = fopen("data/rohm/sales/today.csv", "r");
while (!feof($file_handle) )
{
$line_of_text = fgetcsv($file_handle, 200);
include('finance_logic.php');
}
fclose($file_handle);
}
Yes, it is repeating the reading of the csv every time but I couldn't get it to function at all any other way so if this is the issue I would really appreciate some guidence on dealing with the csv better. Incase it is relevent the code it 'finance_logic.php' is listed below:
if($line_of_text[0] == "Event: $eventName ")
{
$f = 1;
$ticketTotalSet = "no";
$killSet = 'no';
// default totals zero
$totalHolds = 0;
$totalKills = 0;
$ticketSold = 0;
$ticketPrice = 0;
$totalCap = 0;
}
if($f == 1 && $line_of_text[0] == "$eventDate")
{
$f = 2;
}
if($f == 2 && $line_of_text[0] == "Holds")
{
$f = 3;
while($line_of_text[$col] !== "Face Value Amt")
{
$col++;
}
}
if($f == 3 && $line_of_text[0] !== "Face Value Amt")
{
if($f == 3 && $line_of_text[0] == "*: Kill")
{
$totalKills = $line_of_text[$col];
}
$holdsArray[] = $line_of_text[$col];
}
if($f == 3 && $line_of_text[0] == "--")
{
$f = 4;
}
if($f == 4 && $line_of_text[0] == "Capacity")
{
$totalCap = $line_of_text[$col];
$f = 5;
}
if($f == 5 && $line_of_text[0] == "Abbreviated Performance Totals")
{
$f = 6;
}
if($f == 6 && $line_of_text[0] == "$eventName")
{
// change when 1 ticket exists
$ticketTotalSet = "yes";
// set season tickets
include("financial/seasontickets/$orgShortName.php");
// all non season are single tickets
if(!isset($category))
{
$category = 'single';
}
$ticketName = $line_of_text[2];
$ticketSold = $line_of_text[3];
$ticketPrice = $line_of_text[4];
addTicketType($eventId, $ticketName, $category, $ticketSold, $ticketPrice);
unset($category);
}
if($f == 6 && $ticketTotalSet == "yes" && $line_of_text[0] !== "$eventName")
{
$totalHolds = (array_sum($holdsArray) - $totalKills);
// add cap, holds and kills
addKillsHoldsCap($eventId, $totalCap, $eventId, $totalHolds, $totalKills);
// reset everything
$f = 0;
$ticketTotalSet = "no";
echo "$eventName updated!";
}
Thanks in advance!
p.s. The reason the report is called each time is so that the 'eventName' and 'eventDate' are searched for with the 'finance_logic.php'. Obviously if this was set with all event names and dates already it would take one search of the report to find them all but I'm not sure how I could do this dynamically. Any suggestions would be welcome as I'm sure there is something out there that I just haven't learnt yet.
I have some heavy script i use with localhost sometimes and if i don't add anything they will just time out.
A simple solution is to limit the number of execution of your function, then reload the page, then restart where you stopped.
I'm just working on the Backend of a project an have a small problem with this snippet
if (isset($_POST['id'])) {
$cat_delete = "DELETE FROM category WHERE categoryid='".$_POST['id']."' ";
$cat_delete_ex = mysql_query($cat_delete);}`
But if the id is set with post, nothing happens.
The mysql query is working when I delete the
if (isset($_POST['id']))
anyone have an idea ?
Well I am not sure if your method is safe or not, but I would do it like this, might even throw in a regex to check for just numbers if the id is numeric:
EDIT: I made a revision, since you are dealing with an ID, I will assume the ID is numeric only, so instead of escaping it, I just will strip out everything but numbers. This may be a better fit for your situation. I also converted the function to a class so you will be able to reuse the script for several types of sanitizing strings. Maybe its because I am an overachiever too, I don't know. ADD, OCD, etc. Blame it on that :)
$postID = isset($_POST['id']) ? sanitize::ID($_POST['id']) : '';
if (sanitize::email("test#example.com")){
echo "Real email";
} else {
echo "Fake email";
}
if ($postID != ''){
$cat_delete = "DELETE FROM category WHERE categoryid='".$postID."' ";
$cat_delete_ex = mysql_query($cat_delete);
}
class sanitize{
function ID($string){
$string = preg_replace('/[^0-9,]|,[0-9]*$/','',$string);
return $string;
}
# I added another sanitize function so you can see what you can do
# with it. Add phone numbers, domain names, etc... Each one could
# be called with sanitize::{FUNCTION}
function email($string){
if (!ereg("^[^#]{1,64}#[^#]{1,255}$", $string)) {
return false;
}
$email_array = explode("#", $string);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",$local_array[$i])) return false;
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) return false;
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) return false;
}
}
return true;
}
}
are you sure you are using post for the id?(asking because is the right way, but i have one too many times
<form action="action.php?id=hereistheid"
which will bring the id in the $_GET not $_POST.
next the checking
$id=(int)$_POST['id'];
if($id)
{
//do smth
}
Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.