/** * {@inheritdoc} */ protected function composeDetails(PaymentInterface $payment, TokenInterface $token) { if ($payment->getDetails()) { return; } $order = $payment->getOrder(); $details = array(); $details['payment_method'] = $this->apiMethod($payment->getMethod()->getName()); $details['payment_type'] = 1; $details['checkout_url'] = $this->tokenFactory->createNotifyToken($token->getPaymentName(), $payment)->getTargetUrl(); $details['order_code'] = $order->getNumber() . '-' . $payment->getId(); $details['cur_code'] = $order->getCurrency(); $details['total_amount'] = round($order->getTotal() / 100, 2); $details['total_item'] = count($order->getItems()); $m = 0; foreach ($order->getItems() as $item) { $details['item_name' . $m] = $item->getId(); $details['item_amount' . $m] = round($item->getTotal() / $item->getQuantity() / 100, 2); $details['item_quantity' . $m] = $item->getQuantity(); $m++; } if (0 !== ($taxTotal = $this->calculateNonNeutralTaxTotal($order))) { $details['tax_amount'] = $taxTotal; } if (0 !== ($promotionTotal = $order->getAdjustmentsTotal(AdjustmentInterface::PROMOTION_ADJUSTMENT))) { $details['discount_amount'] = $promotionTotal; } if (0 !== ($shippingTotal = $order->getAdjustmentsTotal(AdjustmentInterface::SHIPPING_ADJUSTMENT))) { $details['fee_shipping'] = $shippingTotal; } $payment->setDetails($details); }
function calculateGFRResult() { $tmpArr = array(); $tmpArr[] = date('Y-m-d H:i:s'); //observation time $tmpArr[] = 'GFR (CALC)'; //desc $gender = NSDR::populate($this->_patientId . "::com.clearhealth.person.displayGender"); $crea = NSDR::populate($this->_patientId . "::com.clearhealth.labResults[populate(@description=CREA)]"); $genderFactor = null; $creaValue = null; $personAge = null; $raceFactor = 1; switch ($gender[key($gender)]) { case 'M': $genderFactor = 1; break; case 'F': $genderFactor = 0.742; break; } if ((int) strtotime($crea['observation_time']) >= strtotime('now - 60 days') && strtolower($crea[key($crea)]['units']) == 'mg/dl') { $creaValue = $crea[key($crea)]['value']; } $person = new Person(); $person->personId = $this->_patientId; $person->populate(); if ($person->age > 0) { $personAge = $person->age; } $personStat = new PatientStatistics(); $personStat->personId = $this->_patientId; $personStat->populate(); if ($personStat->race == "AFAM") { $raceFactor = 1.21; } $gfrValue = "INC"; if ($personAge > 0 && $creaValue > 0) { $gfrValue = "" . (int) round(pow($creaValue, -1.154) * pow($personAge, -0.203) * $genderFactor * $raceFactor * 186); } trigger_error("gfr:: " . $gfrValue, E_USER_NOTICE); $tmpArr[] = $gfrValue; // lab value $tmpArr[] = 'mL/min/1.73 m2'; //units $tmpArr[] = ''; //ref range $tmpArr[] = ''; //abnormal $tmpArr[] = 'F'; //status $tmpArr[] = date('Y-m-d H:i:s') . '::' . '0'; // observationTime::(boolean)normal; 0 = abnormal, 1 = normal $tmpArr[] = '0'; //sign //$this->_calcLabResults[uniqid()] = $tmpArr; $this->_calcLabResults[1] = $tmpArr; // temporarily set index to one(1) to be able to include in selected lab results return $tmpArr; }
protected function renderResultList(array $countdowns, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($countdowns, 'PhabricatorCountdown'); $viewer = $this->requireViewer(); $list = new PHUIObjectItemListView(); $list->setUser($viewer); foreach ($countdowns as $countdown) { $id = $countdown->getID(); $ended = false; $epoch = $countdown->getEpoch(); if ($epoch <= PhabricatorTime::getNow()) { $ended = true; } $item = id(new PHUIObjectItemView())->setUser($viewer)->setObject($countdown)->setObjectName("C{$id}")->setHeader($countdown->getTitle())->setHref($this->getApplicationURI("{$id}/"))->addByline(pht('Created by %s', $handles[$countdown->getAuthorPHID()]->renderLink())); if ($ended) { $item->addAttribute(pht('Launched on %s', phabricator_datetime($epoch, $viewer))); $item->setDisabled(true); } else { $time_left = $epoch - PhabricatorTime::getNow(); $num = round($time_left / (60 * 60 * 24)); $noun = pht('Days'); if ($num < 1) { $num = round($time_left / (60 * 60), 1); $noun = pht('Hours'); } $item->setCountdown($num, $noun); $item->addAttribute(phabricator_datetime($epoch, $viewer)); } $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No countdowns found.')); return $result; }
function dateDiff($start, $end) { $start_ts = strtotime($start); $end_ts = strtotime($end); $diff = $end_ts - $start_ts; return round($diff / 86400); }
function query_operon_gene_percentage($species_id) { $spe = array(); $spe['name'] = ''; $spe['ncs'] = array(); $spe['total_gene'] = 0; $spe['in_operon'] = 0; $species_id = mysql_real_escape_string($species_id); $sql = "SELECT id, name FROM Species WHERE id={$species_id}"; $result = mysql_query($sql) or die("Invalid query: " . mysql_error()); $row = mysql_fetch_array($result); $spe['name'] = $row['name']; unset($result); $sql = "SELECT id,NC_id,protein_gene_number,rna_gene_number,operon_number FROM NC WHERE species_id={$species_id}"; $result = mysql_query($sql) or die("Invalid query: " . mysql_error()); $n = mysql_num_rows($result); for ($i = 0; $i < $n; $i++) { $row = mysql_fetch_array($result); $NC_id = $row['id']; $row['total_gene_num'] = $row['protein_gene_number'] + $row['rna_gene_number']; $sql2 = "SELECT sum(size) as total_genes FROM Operon WHERE size>=2 AND NC_id={$NC_id} ORDER BY id"; $result2 = mysql_query($sql2) or die("Invalid query: " . mysql_error()); $row2 = mysql_fetch_array($result2); $row['gene_in_operon'] = $row2['total_genes']; #$row['percent'] = round($row['gene_in_operon'] / $row['total_gene_num'],2); array_push($spe['ncs'], $row); $spe['total_gene'] += $row['total_gene_num']; $spe['in_operon'] += $row['gene_in_operon']; } $spe['percent'] = round(100 * $spe['in_operon'] / $spe['total_gene'], 2); return $spe; }
function getThumbnailDimension($path, $w, $h) { $dim = array('w' => $w, 'h' => $h); if ($w && $h || (!$w && !$h)) return $dim; if (@is_readable($path) && function_exists('getimagesize')) { $info = @getimagesize($path); if (!empty($info) && count($info) > 1) { if (empty($w)) { $w = round($h * $info[0] / $info[1]); $dim['w'] = $w; } else { $h = round($w * $info[1] / $info[0]); $dim['h'] = $h; } } } return $dim; }
function imageDualResize($filename, $cleanFilename, $wtarget, $htarget) { if (!file_exists($cleanFilename)) { $dims = getimagesize($filename); $width = $dims[0]; $height = $dims[1]; while ($width > $wtarget || $height > $htarget) { if ($width > $wtarget) { $percentage = $wtarget / $width; } if ($height > $htarget) { $percentage = $htarget / $height; } /*if($width > $height) { $percentage = ($target / $width); } else { $percentage = ($target / $height); }*/ //gets the new value and applies the percentage, then rounds the value $width = round($width * $percentage); $height = round($height * $percentage); } $image = new SimpleImage(); $image->load($filename); $image->resize($width, $height); $image->save($cleanFilename); $image = null; } //returns the new sizes in html image tag format...this is so you can plug this function inside an image tag and just get the return "src=\"{$baseurl}/{$cleanFilename}\""; }
public static function tearDownAfterClass() { if (!self::$timing) { echo "\n"; return; } $class = get_called_class(); echo "Timing results : {$class}\n"; $s = sprintf("%40s %6s %9s %9s %4s\n", 'name', 'count', 'total', 'avg', '% best'); echo str_repeat('=', strlen($s)) . "\n"; echo $s; echo str_repeat('-', strlen($s)) . "\n"; array_walk(self::$timing, function (&$value, $key) { $value['avg'] = round($value['total'] / $value['count'] * 1000000, 3); }); usort(self::$timing, function ($a, $b) { $at = $a['avg']; $bt = $b['avg']; return $at === $bt ? 0 : ($at < $bt ? -1 : 1); }); $best = self::$timing[0]['avg']; foreach (self::$timing as $timing) { printf("%40s %6d %7.3fms %7.3fus %4.1f%%\n", $timing['name'], $timing['count'], round($timing['total'] * 1000, 3), $timing['avg'], round($timing['avg'] / $best * 100, 3)); } echo str_repeat('-', strlen($s)) . "\n\n"; printf("\nTiming compensated for avg overhead for: timeIt of %.3fus and startTimer/endTimer of %.3fus per invocation\n\n", self::$timeItOverhead * 1000000, self::$startEndOverhead * 1000000); parent::tearDownAfterClass(); }
/** * Format value as string * @param bool $withUnit * @return string */ public function string($withUnit = true) { if ($this->isUnknown()) { return ''; } return round($this->Percent) . ($withUnit ? ' ' . $this->unit() : ''); }
function cuttingimg($zoom, $fn, $sz) { @mkdir(WUO_ROOT . '/photos/maps'); $img = imagecreatefrompng(WUO_ROOT . '/photos/maps/0-0-0-' . $fn); // получаем идентификатор загруженного изрбражения которое будем резать $info = getimagesize(WUO_ROOT . '/photos/maps/0-0-0-' . $fn); // получаем в массив информацию об изображении $w = $info[0]; $h = $info[1]; // ширина и высота исходного изображения $sx = round($w / $sz, 0); // длинна куска изображения $sy = round($h / $sz, 0); // высота куска изображения $px = 0; $py = 0; // координаты шага "реза" for ($y = 0; $y <= $sz; $y++) { for ($x = 0; $x <= $sz; $x++) { $imgcropped = imagecreatetruecolor($sx, $sy); imagecopy($imgcropped, $img, 0, 0, $px, $py, $sx, $sy); imagepng($imgcropped, WUO_ROOT . '/photos/maps/' . $zoom . '-' . $y . '-' . $x . '-' . $fn); $px = $px + $sx; } $px = 0; $py = $py + $sy; } }
function GetRatio($UniVisit = false, $UniSome = false) { if (!$UniVisit || !$UniSome) { return 0; } return round(100 / $UniVisit * $UniSome, 2); }
public function topic($p = 0) { $active_key = $this->redis_event_key_prefix . "topics:valid"; $tid = $this->redis_server->lindex($active_key, $p); $topic = $this->redis_server->lindex($this->redis_event_key_prefix . "topics:all", $tid); // var_dump($tid); // var_dump($topic); $topic = $this->formatString($topic); // var_dump($topic); $topic = json_decode($topic, true); //var_dump($topic); $events = array(); foreach ($topic['events'] as $e) { $event = $this->redis_server->lindex($this->redis_event_key_prefix . "events", $e); //var_dump($event); $event = json_decode($this->formatString($event), true); //var_dump($event); asort($event['keywords']); $events[$e] = $event; } $data['p'] = $p; $data['percentage'] = round(100 * ($p + 1.0) / $this->redis_server->llen($active_key), 2); $data['topic'] = $topic; $data['events'] = $events; $this->assign($data); $this->display(); // var_dump($data); }
function lib_peak_memory() { $oneMb = 1024 * 1024; $memory = memory_get_peak_usage() / $oneMb; $memory = round($memory, 4); return floatval($memory); }
function Zend_Locale_Math_Sub($op1, $op2, $op3 = null) { if (empty($op1)) { $op1 = 0; } $result = $op1 - $op2; if ((string) ($result + $op2) != (string) $op1) { /** * @see Zend_Locale_Math_Exception */ require_once 'Zend/Locale/Math/Exception.php'; throw new Zend_Locale_Math_Exception("subtraction overflow: {$op1} - {$op2} != {$result}", $op1, $op2, $result); } if ($op3 != 0) { $result = round($result, $op3); } else { if ($result > 0) { $result = floor($result); } else { $result = ceil($result); } } if ($op3 > 0) { if ((string) $result == "0") { $result = "0."; } if (strlen($result) < $op3 + 2) { $result = str_pad($result, $op3 + 2, "0", STR_PAD_RIGHT); } } return $result; }
public function checkout_form($order_id, $button_text = null) { if (empty($button_text)) { $button_text = 'Перейти к оплате'; } $order = $this->orders->get_order((int) $order_id); $payment_method = $this->payment->get_payment_method($order->payment_method_id); $payment_currency = $this->money->get_currency(intval($payment_method->currency_id)); $settings = $this->payment->get_payment_settings($payment_method->id); $price = round($this->money->convert($order->total_price, $payment_method->currency_id, false), 2); // описание заказа // order description $desc = 'Оплата заказа №' . $order->id; // Способ оплаты $paymode = $settings['pay2pay_paymode']; $success_url = $this->config->root_url . '/order/'; $result_url = $this->config->root_url . '/payment/Pay2Pay/callback.php'; $currency = $payment_currency->code; if ($currency == 'RUR') { $currency = 'RUB'; } $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n <request>\r\n <version>1.2</version>\r\n <merchant_id>" . $settings['pay2pay_merchantid'] . "</merchant_id>\r\n <language>ru</language>\r\n <order_id>{$order->id}</order_id>\r\n <amount>{$price}</amount>\r\n <currency>{$currency}</currency>\r\n <description>{$desc}</description>\r\n <result_url>{$result_url}</result_url>\r\n <success_url>{$success_url}</success_url>\r\n <fail_url>{$success_url}</fail_url>"; if ($settings['pay2pay_testmode'] == '1') { $xml .= "<test_mode>1</test_mode>"; } $xml .= "</request>"; $xml_encoded = base64_encode($xml); $merc_sign = $settings['pay2pay_secret']; $sign_encoded = base64_encode(md5($merc_sign . $xml . $merc_sign)); $button = '<form action="https://merchant.pay2pay.com/?page=init" method="POST" />' . '<input type="hidden" name="xml" value="' . $xml_encoded . '" />' . '<input type="hidden" name="sign" value="' . $sign_encoded . '" />' . '<input type="submit" class="checkout_button" value="' . $button_text . '">' . '</form>'; return $button; }
public function getMatchRateAttribute() { $user_skills = UserSkill::with('skill')->where('user_id', '=', $this->user_id)->get()->toArray(); if (count($user_skills) > 0) { $skill_percentage = 0; $job_traits = 0; $user_traits = 0; foreach ($this->job_details->job_skills->load('skill')->toArray() as $job_skill) { $avg_user_job_rate = 0; foreach ($user_skills as $user_skill) { if ($job_skill['skill_id'] == $user_skill['skill_id']) { if ($user_skill['skill']['type'] == 'soft') { $user_traits++; } if ($user_skill['skill']['type'] == 'hard') { if ($user_skill['rate'] >= $job_skill['rate']) { $avg_user_job_rate = 1; } else { $avg_user_job_rate = $user_skill['rate'] / $job_skill['rate']; } $over_all_skill_match = $avg_user_job_rate * 100 * ($job_skill['importance'] / 100); $skill_percentage += $over_all_skill_match; } } } if ($job_skill['skill']['type'] == 'soft') { $job_traits++; } } $trait_percentage = $user_traits / $job_traits * 100 * ($this->job_details->traits_importance / 100); $skill_percentage = $skill_percentage * ((100 - $this->job_details->traits_importance) / 100); return round($trait_percentage + $skill_percentage); } return 0; }
protected function setUp() { parent::setUp(); $kb = Bytes::KILOBYTE; $this->exact_test_cases = array('1 byte' => 1, '1 KB' => $kb, '1 MB' => $kb * $kb, '1 GB' => $kb * $kb * $kb, '1 TB' => $kb * $kb * $kb * $kb, '1 PB' => $kb * $kb * $kb * $kb * $kb, '1 EB' => $kb * $kb * $kb * $kb * $kb * $kb, '1 ZB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb, '1 YB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb); $this->rounded_test_cases = array('2 bytes' => 2, '1 MB' => $kb * $kb - 1, round(3623651 / $this->exact_test_cases['1 MB'], 2) . ' MB' => 3623651, round(67234178751368124 / $this->exact_test_cases['1 PB'], 2) . ' PB' => 67234178751368124, round(2.3534682382112583E+26 / $this->exact_test_cases['1 YB'], 2) . ' YB' => 2.3534682382112583E+26); }
public function display($tpl = null) { // Initialise variables $this->state = $this->get("State"); $this->items = $this->get('Items'); $this->pagination = $this->get('Pagination'); // Get params $this->params = $this->state->get("params"); /** @var $this->params Joomla\Registry\Registry */ $this->numberInRow = $this->params->get("items_row", 3); $this->items = CrowdfundingHelper::prepareItems($this->items, $this->numberInRow); // Get the folder with images $this->imageFolder = $this->params->get("images_directory", "images/crowdfunding"); // Get currency $currency = Crowdfunding\Currency::getInstance(JFactory::getDbo(), $this->params->get("project_currency")); $this->amount = new Crowdfunding\Amount($this->params); $this->amount->setCurrency($currency); $this->displayCreator = $this->params->get("integration_display_creator", true); // Prepare social integration. if (!empty($this->displayCreator)) { $socialProfilesBuilder = new Prism\Integration\Profiles\Builder(array("social_platform" => $this->params->get("integration_social_platform"), "users_ids" => CrowdfundingHelper::fetchUserIds($this->items))); $socialProfilesBuilder->build(); $this->socialProfiles = $socialProfilesBuilder->getProfiles(); } $this->layoutData = array("items" => $this->items, "params" => $this->params, "amount" => $this->amount, "socialProfiles" => $this->socialProfiles, "imageFolder" => $this->imageFolder, "titleLength" => $this->params->get("discover_title_length", 0), "descriptionLength" => $this->params->get("discover_description_length", 0), "span" => !empty($this->numberInRow) ? round(12 / $this->numberInRow) : 4); $this->prepareDocument(); parent::display($tpl); }
public function getPaymentCart() { $values = Session::get('payment'); foreach ($values as $key => $value) { $product[$key]['name'] = $value['name']; $price = round((int) $value['price'] / 21270); $product[$key]['price'] = $price; $product[$key]['quantity'] = 1; $product[$key]['product_id'] = $value['id']; } $tmpTransaction = new TmpTransaction(); $st = Str::random(16); $baseUrl = URL::to('/product/payment/return?order_id=' . $st); // $value[1]['name'] = "sản phẩm 1"; // $value[1]['price'] = "20000"; // $value[1]['quantity'] = "1"; // $value[1]['product_id'] = "3"; // $value[2]['name'] = "sản phẩm 2"; // $value[2]['price'] = "20000"; // $value[2]['quantity'] = "1"; // $value[2]['product_id'] = "3"; $payment = $this->makePaymentUsingPayPalCart($product, 'USD', "{$baseUrl}&success=true", "{$baseUrl}&success=false"); $tmpTransaction->order_id = $st; $tmpTransaction->payment_id = $payment->getId(); $tmpTransaction->save(); header("Location: " . $this->getLink($payment->getLinks(), "approval_url")); exit; return "index"; }
private function calculate($complexity, $bgst) { //THE FORMULA STEP BY STEP CALCULATION //1) Material Expense //already submitted when declaring object //2) Indirect Material Expense $this->indirect_material_expense = $bgst['cogs_matexp_indirect'] / 100 * $this->material_expense; //3) Cost based on Products Complexity if (strlen($complexity) > 1) { $complexity = substr($complexity, 0, 1); } $complexity = strtoupper($complexity); $this->cost_based_on_complexity = $bgst['cogs_complexity_' . $complexity]; //4) Variable Cost $this->cost_variable = $bgst['cogs_variable']; //5) Fixed Cost $this->cost_fixed = $bgst['cogs_fixed']; //Sum Point 1-5 $sum_1to5 = $this->material_expense + $this->indirect_material_expense + $this->cost_based_on_complexity + $this->cost_variable + $this->cost_fixed; //6) Handling Cost $this->cost_handling = $bgst['cogs_handling'] / 100 * $sum_1to5; //FINALLY, COGS $cogs = $sum_1to5 + $this->cost_handling; $this->value = round($cogs, 2); //Purchase Price from cogs $this->purchase_price = $this->value * $bgst['cogs_purchase_price_multiplier']; }
/** * @return Highchart */ public function getWeekWeightGraph() { $weeksWeight = $this->statisticEntryHelper->calculateWeeks((new \DateTime())->modify('-1 year')->modify('sunday this week'), new \DateTime(), StatisticEntry::WEIGHT); $averageWeight = $this->statisticEntryHelper->calculateAverage($weeksWeight); $weightRange = $this->statisticEntryHelper->getHighAndLow($averageWeight); $roundedWeightRange = array(round($weightRange[0] - 5, -1) - 10, round($weightRange[1] + 5, -1)); //ignore minus kg, not possible, range are +- to 10, at 0 its rounded to -10 $roundedWeightRange[0] < 0 ? $roundedWeightRange[0] = 0 : null; $weeksBodyFat = $this->statisticEntryHelper->calculateWeeks((new \DateTime())->modify('-1 year')->modify('sunday this week'), new \DateTime(), StatisticEntry::BODY_FAT); $averageBodyFat = $this->statisticEntryHelper->calculateAverage($weeksBodyFat); $bodyFatRange = $this->statisticEntryHelper->getHighAndLow($averageBodyFat); $weeksMuscleMass = $this->statisticEntryHelper->calculateWeeks((new \DateTime())->modify('-1 year')->modify('sunday this week'), new \DateTime(), StatisticEntry::MUSCLE_MASS); $averageMuscleMass = $this->statisticEntryHelper->calculateAverage($weeksMuscleMass); $muscleMassRange = $this->statisticEntryHelper->getHighAndLow($averageMuscleMass); $combinedRange = array_merge($bodyFatRange, $muscleMassRange); $combinedRange = $this->statisticEntryHelper->getHighAndLow($combinedRange); $roundedCombinedRange = array(round($combinedRange[0] - 5, -1), round($combinedRange[1] + 5, -1)); //ignore minus %, not possible $roundedCombinedRange[0] < 0 ? $roundedCombinedRange[0] = 0 : null; $months = array(); for ($i = 0; $i <= 52; $i++) { $months[52 - $i] = $this->_trans(date("W", strtotime(date('Y-m-01') . " -{$i} weeks"))); } $chart = $this->_populateNewChart($averageWeight, $averageBodyFat, $averageMuscleMass, $roundedCombinedRange, $roundedWeightRange, $months); $chart->chart->renderTo('linechartWeekWeight'); return $chart; }
function VentriloInfoEX1_PrettyTime($time) { $week = $time / 604800; if ($week < 1) { $week = 0; } else { $week = round($week); } $day = round($time - $week * 604800) / 86400; if ($day < 1) { $day = 0; } else { $day = round($day); } $hour = round($time - $week * 604800 - $day * 86400) / 3600; if ($hour < 1) { $hour = 0; } else { $hour = round($hour); } $minute = round($time - $week * 604800 - $day * 86400 - $hour * 3600) / 60; if ($minute < 1) { $minute = 0; } else { $minute = round($min); } $secs = round($time - $week * 604800 - $day * 86400 - $hour * 3600 - $minute * 60); return $week . 'wks' . $day . 'days' . $hour . 'hours' . $minute . 'min' . $secs . 's'; }
function tree_treeview1($startNode, $deep = 99, $startlevel = 1) { global $cms; foreach ($startNode->childNodes as $cNode) { if ($cNode->nodeType == 1 && $cNode->nodeName == 'page' && $cNode->getAttribute('display') != 'hide') { $thisId = $cNode->getAttribute('id'); $loc = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php?cmsid=' . $thisId; $pri = round(1 / $startlevel, 2) >= 1 ? round(1 / $startlevel, 2) : round(1 / $startlevel, 2) + 0.2; echo "<url>\r\n <loc>{$loc}</loc>\r\n <priority>{$pri}</priority>\r\n</url>\r\n"; $hasChildPage = 0; if ($cNode->hasChildNodes()) { foreach ($cNode->childNodes as $ccNode) { if ($ccNode->nodeName == "page") { $hasChildPage = 1; continue; } } } if ($hasChildPage) { if ($deep > 1) { tree_treeview1($cNode, $deep - 1, $startlevel + 1); } } } } }
function draw() { $this->beginForm(); global $display; $id = (int) Url::get("id", 0); $cmd = Url::get("cmd"); if ($id && $cmd == "edit") { $item = DB::fetch("SELECT * FROM admin_notice_user WHERE id={$id}"); $display->add('user_name', $item['user_name']); $display->add('content', $item['content']); $expire = (int) round(($item['expire_date'] - TIME_NOW) / 86400); $display->add('expire', $expire); if ($item["expire_date"] > TIME_NOW && $item["active"]) { $item["active"] = 1; } else { $item["active"] = 0; } $display->add('active', $item['active']); } elseif ($cmd == "add") { $display->add('user_name', Url::get('user_name')); $display->add('content', Url::get('content')); $display->add('active', (int) Url::get('active', 1)); $display->add('expire', Url::get('expire', 7)); } $display->add('cmd', $cmd); $display->add('msg', $this->showFormErrorMessages(1)); $display->output('EditAdminNoticeUser'); $this->endForm(); }
function tpl_modifier_time_ago($string) { $uts = tpl_make_timestamp($string); $mins = round((time() - $uts) / 60); if ($mins < 60) { return $mins . " " . l('mins_ago'); } else { $hours = round($mins / 60); if ($hours < 24) { return $hours . " " . l('hours_ago'); } else { $days = round($hours / 24); if ($days < 7) { return $days . " " . l('days_ago'); } else { $weeks = round($days / 7); if ($weeks < 3) { return $weeks . " " . l('weeks_ago'); } else { $months = round($days / 30); if ($months < 12) { return $months . " " . l('months_ago'); } else { $years = round($months / 12); return $years . " " . l('years_ago'); } } } } } return; }
public function convert() { $paddingTop = array_key_exists('SpaceBefore', $this->idmlContext) ? $this->idmlContext['SpaceBefore'] : '0'; $paddingRight = array_key_exists('RightIndent', $this->idmlContext) ? $this->idmlContext['RightIndent'] : '0'; $paddingBottom = array_key_exists('SpaceAfter', $this->idmlContext) ? $this->idmlContext['SpaceAfter'] : '0'; $paddingLeft = array_key_exists('LeftIndent', $this->idmlContext) ? $this->idmlContext['LeftIndent'] : '0'; // InDesign allows negative SpaceBefore and SpaceAfter, but CSS does not allow negative padding. $paddingTop = max(0, $paddingTop); $paddingBottom = max(0, $paddingBottom); $paddingTop = round($paddingTop); $paddingRight = round($paddingRight); $paddingBottom = round($paddingBottom); $paddingLeft = round($paddingLeft); if ($paddingTop == $paddingRight && $paddingRight == $paddingBottom && $paddingBottom == $paddingLeft) { $this->registerCSS('padding', $paddingTop . 'px'); } else { $this->registerCSS('padding', sprintf("%dpx %dpx %dpx %dpx", $paddingTop, $paddingRight, $paddingBottom, $paddingLeft)); } // IDML differs from CSS in it's implementation of space before the first paragraph. // IDML only uses SpaceBefore for the second and subsequent paragraphs, so we need CSS // to suppress padding-top on the first paragraph. if ($paddingTop > 0 && $this->decodeContext == 'Typography') { $this->registerPseudoCSS('first-of-type', 'padding', sprintf("%dpx %dpx %dpx %dpx", 0, $paddingRight, $paddingBottom, $paddingLeft)); } }
function order_list_by_time($filter) { //require_once('includes/sql_connection.inc.php'); global $DBC; $result = pg_query_params($DBC, "SELECT \n\t\t\t\t\t\t\t\t\t\t\tdate_trunc(\$1, orderdate) as date_filter, \n\t\t\t\t\t\t\t\t\t\t\tcount(distinct orderid) as numberof_order,\n\t\t\t\t\t\t\t\t\t\t\tcount(distinct customerid) as numberof_customer,\n\t\t\t\t\t\t\t\t\t\t\tcount(distinct prod_id) as numberof_prod,\n\t\t\t\t\t\t\t\t\t\t\tsum(quantity) as quantity_by_time,\n\t\t\t\t\t\t\t\t\t\t\tsum(total) as total_by_time \n\t\t\t\t\t\t\t\t\t\tFROM orders NATURAL JOIN orderlines\n\t\t\t\t\t\t\t\t\t\tGROUP BY date_filter\n\t\t\t\t\t\t\t\t\t\tORDER BY total_by_time DESC", array($filter)); if ($result) { $order_list_by_time = pg_fetch_all($result); switch ($filter) { case 'day': $format = 'D d/M/Y'; break; case 'week': $format = 'W M/Y'; break; case 'month': $format = 'M/Y'; break; case 'year': $format = 'Y'; break; default: break; } for ($i = 0; $i < count($order_list_by_time); $i++) { echo '<tr> <td>' . date($format, strtotime($order_list_by_time[$i]['date_filter'])) . '</td> <td>' . $order_list_by_time[$i]['numberof_order'] . '</td> <td>' . $order_list_by_time[$i]['numberof_customer'] . '</td> <td>' . $order_list_by_time[$i]['numberof_prod'] . '</td> <td>' . $order_list_by_time[$i]['quantity_by_time'] . '</td> <td style="font-weight: bold;" class="price">' . round($order_list_by_time[$i]['total_by_time']) . '</td> </tr>'; } } }
/** * Returns a mask * * @param \WideImage\Image $image * @return \WideImage\Image */ public function execute($image) { $width = $image->getWidth(); $height = $image->getHeight(); $mask = TrueColorImage::create($width, $height); $mask->setTransparentColor(-1); $mask->alphaBlending(false); $mask->saveAlpha(false); for ($i = 0; $i <= 255; $i++) { $greyscale[$i] = ImageColorAllocate($mask->getHandle(), $i, $i, $i); } imagefilledrectangle($mask->getHandle(), 0, 0, $width, $height, $greyscale[255]); $transparentColor = $image->getTransparentColor(); $alphaToGreyRatio = 255 / 127; for ($x = 0; $x < $width; $x++) { for ($y = 0; $y < $height; $y++) { $color = $image->getColorAt($x, $y); if ($color == $transparentColor) { $rgba['alpha'] = 127; } else { $rgba = $image->getColorRGB($color); } imagesetpixel($mask->getHandle(), $x, $y, $greyscale[255 - round($rgba['alpha'] * $alphaToGreyRatio)]); } } return $mask; }
function valida_valor($valor, $aceita_float) { // valida valor if ($valor == null) { // informa que nao e um valor return false; } // remove a virgula se houver $valor = str_replace(",", ".", $valor); // remove espaco vazio no meio se houver $valor = str_replace(" ", null, $valor); // remove o espaco em branco $valor = trim($valor); // valida se e numero, e se e numero positivo if (is_numeric($valor) == false or $valor < 0) { // informa que nao e um numero return false; } // arredonda valor se nao aceitar float if ($aceita_float == false) { // arredonda $valor = round($valor, 0); } // se aceitar float, e for float entao arredonda if ($aceita_float == true) { // arredonda $valor = round($valor, 2); } // retorno return $valor; }
public function execute(CommandSender $sender, $currentAlias, array $args) { if (!$this->testPermission($sender)) { return true; } $chunksCollected = 0; $entitiesCollected = 0; $tilesCollected = 0; $memory = memory_get_usage(); foreach ($sender->getServer()->getLevels() as $level) { $diff = [count($level->getChunks()), count($level->getEntities()), count($level->getTiles())]; $level->doChunkGarbageCollection(); $level->unloadChunks(true); $chunksCollected += $diff[0] - count($level->getChunks()); $entitiesCollected += $diff[1] - count($level->getEntities()); $tilesCollected += $diff[2] - count($level->getTiles()); $level->clearCache(true); } $cyclesCollected = $sender->getServer()->getMemoryManager()->triggerGarbageCollector(); $sender->sendMessage(TextFormat::GREEN . "---- " . TextFormat::WHITE . "Garbage collection result" . TextFormat::GREEN . " ----"); $sender->sendMessage(TextFormat::GOLD . "Chunks: " . TextFormat::RED . number_format($chunksCollected)); $sender->sendMessage(TextFormat::GOLD . "Entities: " . TextFormat::RED . number_format($entitiesCollected)); $sender->sendMessage(TextFormat::GOLD . "Tiles: " . TextFormat::RED . number_format($tilesCollected)); $sender->sendMessage(TextFormat::GOLD . "Cycles: " . TextFormat::RED . number_format($cyclesCollected)); $sender->sendMessage(TextFormat::GOLD . "Memory freed: " . TextFormat::RED . number_format(round(($memory - memory_get_usage()) / 1024 / 1024, 2)) . " MB"); return true; }