function vote() { if ($_SESSION['userid'] == '') { echo "0Please login to vote"; exit; } $id = sanitize($_POST['id'], "int"); $sql = "select userid from comments where id = '" . escape($id) . "'"; $query = mysql_query($sql); $comment = mysql_fetch_array($query); if ($comment['userid'] == $_SESSION['userid']) { echo "0You cannot upvote your own comment"; exit; } $sql = "select * from comments_votes where commentid = '" . escape($id) . "' and userid = '" . escape($_SESSION['userid']) . "'"; $query = mysql_query($sql); $result = mysql_fetch_array($query); if ($result['id'] > 0) { $sql = "delete from comments_votes where commentid = '" . escape($id) . "' and userid = '" . escape($_SESSION['userid']) . "'"; $query = mysql_query($sql); $sql_nest = "update comments set votes = votes-1 where id = '" . escape($id) . "'"; $query_nest = mysql_query($sql_nest); score('c_upvoted_removed', $id, $comment['userid']); } else { $sql = "insert into comments_votes (commentid,userid) values ('" . escape($id) . "','" . escape($_SESSION['userid']) . "')"; $query = mysql_query($sql); $sql_nest = "update comments set votes = votes+1 where id = '" . escape($id) . "'"; $query_nest = mysql_query($sql_nest); score('c_upvoted', $id, $comment['userid']); } echo "1"; exit; }
function vote() { if ($_SESSION['userid'] == '') { echo "0Please login to vote"; exit; } $id = sanitize($_POST['id'], "int"); $sql = "SELECT userid FROM comments WHERE id = '" . escape($id) . "'"; $query = mysql_query($sql); $comment = mysql_fetch_array($query); if ($comment['userid'] == $_SESSION['userid']) { echo "0You cannot upvote your own comment"; exit; } $sql = "SELECT * FROM comments_votes WHERE commentid = '" . escape($id) . "' AND userid = '" . escape($_SESSION['userid']) . "'"; $query = mysql_query($sql); $result = mysql_fetch_array($query); if ($result['id'] > 0) { $sql = "DELETE FROM comments_votes WHERE commentid = '" . escape($id) . "' AND userid = '" . escape($_SESSION['userid']) . "'"; $query = mysql_query($sql); $sql_nest = "UPDATE comments SET votes = votes-1 WHERE id = '" . escape($id) . "'"; $query_nest = mysql_query($sql_nest); score('c_upvoted_removed', $id, $comment['userid']); } else { $sql = "INSERT INTO comments_votes (commentid,userid) VALUES ('" . escape($id) . "','" . escape($_SESSION['userid']) . "')"; $query = mysql_query($sql); $sql_nest = "UPDATE comments SET votes = votes+1 WHERE id = '" . escape($id) . "'"; $query_nest = mysql_query($sql_nest); score('c_upvoted', $id, $comment['userid']); } echo "1"; exit; }
function gradient($data, $parameters) { $learn_rate = 0.01; $hypothesis = hypothesis($parameters[0], $parameters[1]); $deriv = deriv($data, $hypothesis); $score = score($data, $hypothesis); $parameters[0] = $parameters[0] - $learn_rate * $deriv[0]; $parameters[1] = $parameters[1] - $learn_rate * $deriv[1]; // Create a new hypothesis to test our score $hypothesis = hypothesis($parameters[0], $parameters[1]); if ($score < score($data, $hypothesis)) { return false; } return $parameters; }
function posts($post_id = '') { if (empty($post = get_post($post_id))) { return; } // Check the post ID passed to this function if (!is_int($post_id)) { $post_id = $post->ID; } // Allow other functions to filter the taxonomies options // Weighted taxonomy: array( 'post_tag' => 1 ) // Unweighted taxonomy: array( 'post_tag' ) $taxonomies = (array) apply_filters('ubik_related_taxonomies', option('taxonomies')); if (empty($taxonomies)) { return; } // Allow other functions to filter the maximum number of results returned $max_results = (int) apply_filters('ubik_related_max_results', option('max_results')); // Test the taxonomies argument and call the appropriate function if (count($taxonomies) > 1) { $related = posts_multi($post_id, $taxonomies); } else { // This part would be straight-forward except that we might receive an array with a single entry; furthermore, this array may or may not be weighted $taxonomy = $taxonomies; // Copy the original taxonomies argument; we'll need the original for the counts (below) if (is_numeric(current($taxonomy))) { // Presumably a weighted array $taxonomy = array_keys($taxonomy); } // All we want is the key $related = posts_single($post_id, $taxonomy[0]); } // Nothing found? Time to break out of this... if (empty($related) || !is_array($related)) { return; } // Score the results and filter; this allows other functions to hook in and modify counts in creative ways // Note 1: this approach automatically removes duplicate post IDs // Note 2: if you hook into this function be sure to return a sorted list of results $related = score($related, $taxonomies); // Trim the array and return the keys (the related post IDs) return array_slice($related, 0, $max_results, true); }
* * @author Benoit Asselin <contact(at)ab-d.fr> * @version benchmark.php, 2014-03-12 * @link http://www.ab-d.fr * */ error_reporting(E_ALL); ini_set('display_error', true); /** * Display result * @param string $label [optional] */ function score($label = '') { static $microtime_start = null; static $test = 0; if (null === $microtime_start) { // First run $microtime_start = microtime(true); return; } $microtime_score = microtime(true) - $microtime_start; ++$test; echo '<p style="font-family:sans-serif;font-size:1em;">Test #' . $test . ($label ? ' <code style="font-size:1.1em;">' . $label . '</code> ' : '') . '<br />'; echo '<span style="color:blue;">Time: ' . sprintf('%.8f', $microtime_score) . ' sec</span></p>'; // Reset $microtime_start = microtime(true); } // First run score();
/** * display a list of votes * * @param array $proposals * @param resource $result * @param string $token (optional) token of the logged in member for highlighting */ public static function display_votes(array $proposals, $result, $token="") { ?> <table class="votes"> <? // table head if (count($proposals) == 1) { $show_scores = false; ?> <tr><th><?=_("Vote token")?></th><th><?=_("Voting time")?></th><th><?=_("Acceptance")?></th></tr> <? } else { $show_scores = true; ?> <tr><th rowspan="2"><?=_("Vote token")?></th><th rowspan="2"><?=_("Voting time")?></th><? foreach ($proposals as $proposal) { ?><th colspan="2"><?=_("Proposal")?> <?=$proposal->id?></th><? } ?></tr> <tr><? /** @noinspection PhpUnusedLocalVariableInspection */ foreach ($proposals as $proposal) { ?><th><?=_("Acceptance")?></th><th><?=_("Score")?></th><? } ?></tr> <? } // votes $last_token = null; while ( $row = DB::fetch_assoc($result) ) { ?> <tr class="<?=stripes(); // highlight votes of the logged in member if ($token == $row['token']) { ?> self<? } // strike through votes, which have been overridden by a later vote if ($row['token'] == $last_token) { ?> overridden<? } else $last_token = $row['token']; ?>"><td><?=$row['token']?></td><? if ($row['vote']) { ?><td class="tdc"><?=date(VOTETIME_FORMAT, strtotime($row['votetime']))?></td><? $vote = unserialize($row['vote']); foreach ($proposals as $proposal) { ?><td><?=acceptance($vote[$proposal->id]['acceptance'])?></td><? if ($show_scores) { ?><td class="tdc"><?=score($vote[$proposal->id]['score'])?></td><? } } } else { // member did not vote ?><td class="tdc"></td><? /** @noinspection PhpUnusedLocalVariableInspection */ foreach ($proposals as $proposal) { ?><td></td><? if ($show_scores) { ?><td class="tdc"></td><? } } } ?></tr> <? } ?> </table> <? }
die("something is going wrong"); } } if ($_POST['action'] == "bet" and $_POST['bet'] >= 1 and $_POST['bet'] <= 250 and $_SESSION['game'] != 'running') { $_SESSION['bet'] = $_POST['bet']; } if ($_SESSION['game'] != 'running') { $content = "<b>Deine Karten (" . score() . "):</b><br />" . showcards() . "<br /><b>Der Bank ihre Karten (" . bankscore() . "):</b><br />" . showbankcards() . '<br /><a href="?action=new&' . SID . '">[Runde starten!]</a><br /><br /><form method="post" action="?' . SID . '" enctype="multipart/form-data"> Der Einsatz beträgt: <input type="text" name="bet" value="' . $_SESSION['bet'] . '" size="4" /> <input type="hidden" name="action" value="bet" /> <input type="hidden" name="ok" value="1" /> <input type="submit" name="submit" value="ändern" /></form>Minimum: 1 / Maximum: 250'; } elseif ($_SESSION['card'] == 2) { $content = showcards() . "<br /><b>Derzeitige Punkte: " . score() . '</b><br /><a href="?action=hit&' . SID . '">hit</a> / <a href="?action=stand&' . SID . '">stand</a><br />'; } else { $content = showcards() . "<br /><b>Derzeitige Punkte: " . score() . '</b><br /><a href="?action=hit&' . SID . '">hit</a> / <a href="?action=stand&' . SID . '">stand</a>'; } $content = str_replace("%content%", $content, template1()); $content = str_replace("%status%", $_SESSION['game'], $content); $content = str_replace("%credits%", number_format($ressis['display_gold'], 0, '', '.'), $content); $content = str_replace("%bet%", $_SESSION['bet'], $content); mysql_query("UPDATE `ressis` SET `gold` = '" . $_SESSION['credit'] . "' WHERE `omni` = '" . $_SESSION['user']['omni'] . "' LIMIT 1;"); $ressis = ressistand($_SESSION['user']['omni']); // get playerinfo template and replace tags $status = template('playerinfo'); $status = tag2value('name', $_SESSION['user']['name'], $status); $status = tag2value('base', $_SESSION['user']['base'], $status); $status = tag2value('ubl', $_SESSION['user']['omni'], $status); $status = tag2value('points', $_SESSION['user']['points'], $status); echo tag2value('onload', $onload, template('head')) . $status . $ressis['html'] . $content . '</table>' . template('footer'); // debug
function vote() { if ($_SESSION['userid'] == '') { echo "0" . _("Please login to vote"); exit; } $id = sanitize($_POST['id'], "int"); $vote = sanitize($_POST['vote'], "string"); if ($vote == 'plus') { $vote = '+1'; } else { $vote = '-1'; } $sql = "select questions.userid,questions_votes.id qvid,questions_votes.vote qvvote from questions left join questions_votes on (questions.id = questions_votes.questionid and questions_votes.userid = '" . escape($_SESSION['userid']) . "') where questions.id = '" . escape($id) . "'"; $query = mysql_query($sql); $question = mysql_fetch_array($query); if ($question['userid'] == $_SESSION['userid']) { echo "0" . _("You cannot up/down vote your own question"); exit; } if ($question['qvid'] > 0) { if ($question['qvvote'] == 1 && $vote == '+1') { $vote = "-1"; score('q_upvoted_removed', $id, $question['userid']); } else { if ($question['qvvote'] == 1 && $vote == '-1') { $vote = "-2"; score('q_upvoted_removed', $id, $question['userid']); score('q_downvoter', $id); score('q_downvoted', $id, $question['userid']); } else { if ($question['qvvote'] == -1 && $vote == '-1') { $vote = "+1"; score('q_downvoter_removed', $id); score('q_downvoted_removed', $id, $question['userid']); } else { if ($question['qvvote'] == -1 && $vote == '+1') { $vote = "+2"; score('q_downvoter_removed', $id); score('q_downvoted_removed', $id, $question['userid']); score('q_upvoted', $id, $question['userid']); } else { if ($question['qvvote'] == 0) { if ($vote == 1) { score('q_upvoted', $id, $question['userid']); } else { score('q_downvoter', $id); score('q_downvoted', $id, $question['userid']); } } } } } } $sql = "update questions_votes set vote = vote" . escape($vote) . " where id = '" . $question['qvid'] . "'"; $query = mysql_query($sql); } else { $sql = "insert into questions_votes (questionid,userid,vote) values ('" . escape($id) . "','" . escape($_SESSION['userid']) . "','" . escape($vote) . "')"; $query = mysql_query($sql); if ($vote == 1) { score('q_upvoted', $id, $question['userid']); } else { score('q_downvoter', $id); score('q_downvoted', $id, $question['userid']); } } $sql_nest = "update questions set votes = votes" . escape($vote) . " where id = '" . escape($id) . "'"; $query_nest = mysql_query($sql_nest); echo "1" . _("Thankyou for voting"); exit; }
echo PHP_EOL; } } $enc = 'http://gist.github.com/tqbf/3132752/raw/cecdb818e3ee4f5dda6f0847bfd90a83edb87e73/gistfile1.txt'; $enc = base64_decode(file_get_contents($enc)); for ($keysize = 2; $keysize <= 40; $keysize++) { $blockA = substr($enc, 0, $keysize); $blockB = substr($enc, $keysize, $keysize); $blockC = substr($enc, $keysize * 2, $keysize); $blockD = substr($enc, $keysize * 3, $keysize); $lenA = strlen($blockA); $lenB = strlen($blockB); $lenC = strlen($blockC); $lenD = strlen($blockD); if ($lenA != $lenB || $lenB != $lenC || $lenC != $lenD) { die('Block sizes differ.'); } printf("(Keysize = %d)\t%.2f\n", $keysize, hamdist($blockA, $blockB) / $keysize + hamdist($blockC, $blockD) / $keysize); } $keysize = 5; $enc_blocks = str_split($enc, $keysize); for ($i = 0; $i < $keysize; $i++) { foreach ($enc_blocks as $block) { $bytes[] = bin2hex(substr($block, $i, 1)); } $string = implode('', $bytes); $unique = array_unique(array_filter($bytes)); printf("\n\n-- Block %d --\n0x%s\n\n", $i + 1, $string); score($string, $unique, $keysize, ' eta', 'bin2hex'); unset($bytes); }
<?php include '../benchmark.php'; # TEST 1 for ($i = 0; $i < 10000; $i++) { echo $i; } score('echo'); # TEST 2 for ($i = 0; $i < 10000; $i++) { echo $i; } score('<?php echo'); # TEST 3 for ($i = 0; $i < 10000; $i++) { print $i; } score('print'); # TEST 3 for ($i = 0; $i < 10000; $i++) { print $i; } score('<?php print'); # TEST 5 - Winner! for ($i = 0; $i < 10000; $i++) { echo $i; } score('<?= ?>');
<p> <?php /** * If you can't find a function you need in PHP, you can create it! * Let's modify our previous exercise to print the score for every name. */ // Create a function to clean the name and // print out the person's name and their "score" function score($name) { $name = ucwords(strtolower(trim($name))); $explodedNames = explode(" ", $name); $score = stripos($name, "a") * strlen($explodedNames[count($explodedNames) - 1]) / str_word_count($name); echo "{$name} = {$score} </br>"; } $names = ['JASON hunter', ' eRic Schwartz', 'mark zuckerburg ']; // Add a couple extra names to the $names array array_push($names, " Bob ArK"); array_push($names, "JAcoB foArD"); sort($names); // loop through our names and call our function foreach ($names as $name) { echo score($name); } ?> </p> </body> </html>
/** * Inserta un tag * @param array $values valores a insertar * @return void */ function insert_tags($values) { $values = split(',', $values); $this->load->helper('inflector'); foreach ($values as $value) { $value = trim($value); $tmp['name'] = $value; $tmp['slug'] = score($value); $this_tag = $this->_check_insert($tmp); if ($this_tag == FALSE) { $id = $this->_insertar($tmp); $tags[] = $this->term_taxonomy->insertar_tag($id); } else { $tags[] = $this_tag; } } return $tags; }
score('array()'); # TEST 2 for ($i = 0; $i < 10000; $i++) { $tmp_array = array(); $tmp_array[] = '1'; $tmp_array[] = '2'; $tmp_array[] = '3'; $tmp_array[] = 'a'; $tmp_array[] = 'b'; $tmp_array[] = 'c'; } score('[]..'); # TEST 3 for ($i = 0; $i < 10000; $i++) { $tmp_array = array(); $x = 0; $tmp_array[$x++] = '1'; $tmp_array[$x++] = '2'; $tmp_array[$x++] = '3'; $tmp_array[$x++] = 'a'; $tmp_array[$x++] = 'b'; $tmp_array[$x++] = 'c'; } score('[$x]..'); # TEST 4 - Winner! for ($i = 0; $i < 10000; $i++) { // PHP 5.4+ $tmp_array = ['1', '2', '3', 'a', 'b', 'c']; } score('[ .. ]');
/** * Sube un archivo * @param boolean $ie6 es Internet Explorer 6 * @return array */ function _upload($ie = NULL) { $tmp['allowed_types'] = 'doc|pdf'; $tmp['encrypt_name'] = TRUE; $this->load->model('options'); $tmp['upload_path'] = $this->options->get_('upload_path') . date('/Y/m/'); $values['guid'] = $this->options->get_('upload_url_path') . date('/Y/m/'); $this->load->library('upload', $tmp); if (!$this->upload->do_upload('Filedata')) { $error = array('error' => $this->upload->display_errors(), 'upload_data' => $this->upload->data()); return NULL; } else { $doc = $this->upload->data(); //debe insertar en un post, la imagen, ver wp_post id=18 $this->load->model('post'); $this->load->model('postmeta'); $this->load->helper('inflector'); $values['post_author'] = $this->input->post('id'); $values['post_title'] = score(ereg_replace($doc['file_ext'], '', $doc['file_name'])); $values['post_name'] = $values['post_title']; $values['post_mime_type'] = 'application/' . ereg_replace('\\.', '', $doc['file_ext']); $values['guid'] = $values['guid'] . $doc['file_name']; $the_doc = $this->post->insert_attach($values); $meta['_wp_attached_file'] = date('Y/m/') . $doc['file_name']; $meta['_wp_attachment_metadata'] = 'a:0{}'; $this->postmeta->insertar($meta, $the_doc); if ($this->_is_ie6() == TRUE or $ie != NULL) { return $the_doc; } else { echo $the_doc; } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ require 'C:\\wamp\\www\\malaria_camp\\config\\connect.php'; require 'C:\\wamp\\www\\malaria_camp\\config\\constants.php'; if (isset($_GET['nav']) && isset($_GET['type']) && isset($_GET['question_id'])) { $next = 'Next'; $prev = 'Prev'; $nav = $_GET['nav']; (int) ($question_id = (int) $_GET['question_id']); $player_type = $_GET['type']; if ($nav === $next) { $aws = (int) $_GET['answer_id']; score($question_id, $aws); //score answer //then go to the next queston if (canDoNext($player_type, $question_id)) { $question_id = $question_id + 1; $ques = getoneQuestion($question_id, $player_type); $opts = getAnswerOpt($ques); echo json_encode(laodQueston($ques, $opts, $player_type)); } else { echo json_encode(checkIfSabinusOrKoi((int) $_SESSION['result'])); } } else { if ($nav === $prev) { $question_id = $question_id - 1; removeScore($question_id); //remove scored answer
<?php include '../benchmark.php'; # TEST 1 for ($i = 0; $i < 100000; $i++) { $var = 3200 / 2; } score('/2'); # TEST 2 - Winner! for ($i = 0; $i < 100000; $i++) { $var = 3200 >> 1; } score('>>1');
<?php include '../benchmark.php'; # TEST 1 for ($i = 0; $i < 10000; $i++) { echo '<span style="display:none;">' . $i . '</span>' . "\n"; } score('echo .$i.'); # TEST 2 for ($i = 0; $i < 10000; $i++) { echo '<span style="display:none;">', $i, '</span>', "\n"; } score('echo ,$i,'); # TEST 3 - Winner... for ($i = 0; $i < 10000; $i++) { echo '<span style="display:none;">'; echo $i; echo '</span>'; echo "\n"; } score('echo echo echo'); # TEST 4 for ($i = 0; $i < 10000; $i++) { echo "<span style=\"display:none;\">{$i}</span>\n"; } score('echo {$i}');
echo "<input type=\"submit\" value=\"Update weights\">"; echo "</form>"; echo "<br>"; $candidate_peer_infos = get_peer_infos(); // echo json_encode($candidate_peer_infos); echo "<br><br>"; $requestor = $candidate_peer_infos[0]; echo "Requestor: " . $requestor['client']; echo "<br><br>"; $peer_count = count($candidate_peer_infos); use_algorithm_weights(get_algorithm_weights()); if ($peer_count > 1) { for ($i = 1; $i < $peer_count; $i++) { $candidate = $candidate_peer_infos[$i]; echo "<b>Candidate " . $candidate['client'] . "</b><br><br>"; $score = score($requestor, $candidate); echo "<br><br>"; echo "<b>Score for candidate " . $candidate['client'] . ": " . $score . "<br><br></b>"; } } // echo "<br><br>"; // echo "<div>"; // print_r($allclients); // echo "<br>"; // print_r($links); // echo "<br>"; // print_r($assets); // echo var_dump($candidate_peer_infos["client_1"]); // echo "</div>"; ?>
$resultReqs = mysql_query($query); $numReqs = mysql_numrows($resultReqs); $i = 0; while ($i < $numReqs) { score(0, mysql_result($resultReqs, $i, "opsreq_pri1")); score(1, mysql_result($resultReqs, $i, "opsreq_pri2")); score(2, mysql_result($resultReqs, $i, "opsreq_pri3")); score(3, mysql_result($resultReqs, $i, "opsreq_pri4")); score(4, mysql_result($resultReqs, $i, "opsreq_pri5")); score(5, mysql_result($resultReqs, $i, "opsreq_pri6")); score(6, mysql_result($resultReqs, $i, "opsreq_pri7")); score(7, mysql_result($resultReqs, $i, "opsreq_pri8")); score(8, mysql_result($resultReqs, $i, "opsreq_pri9")); score(9, mysql_result($resultReqs, $i, "opsreq_pri10")); score(10, mysql_result($resultReqs, $i, "opsreq_pri11")); score(11, mysql_result($resultReqs, $i, "opsreq_pri12")); $i++; } // print table echo '<table border="1">'; echo '<tr><th>Layout</th><th>Start</th><th>Spots</th><th>Sum</th><th>1st</th><th>2nd</th><th>3rd</th><th>4th</th><th>5th</th><th>6th</th><th>7th</th><th>8th</th><th>9th</th><th>10th</th><th>11th</th><th>12th</th></tr>'; $i = 0; $grandtotal = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); while ($i < $numSessions) { $key = mysql_result($resultSessions, $i, "ops_id"); echo '<tr>'; echo '<td><a href="?session=' . mysql_result($resultSessions, $i, "ops_id") . '">' . mysql_result($resultSessions, $i, "show_name") . '</a></td>'; echo '<td>' . mysql_result($resultSessions, $i, "start_date") . '</td>' . "\n"; $include = FALSE; if (mysql_result($resultSessions, $i, "show_name") != NULL) { $include = TRUE;
/** * Sube un archivo * @param boolean $ie6 es Internet Explorer 6 * @return array */ function _upload($ie = NULL) { $tmp['allowed_types'] = 'jpg|jpeg|gif|png'; $tmp['encrypt_name'] = TRUE; $this->load->model('options'); $tmp['upload_path'] = $this->options->get_('upload_path') . date('/Y/m/'); $values['guid'] = $this->options->get_('upload_url_path') . date('/Y/m/'); $this->load->library('upload', $tmp); if (!$this->upload->do_upload('Filedata')) { $error = array('error' => $this->upload->display_errors(), 'upload_data' => $this->upload->data()); return NULL; } else { $photo = $this->upload->data(); //debe insertar en un post, la imagen, ver wp_post id=18 $this->load->model('post'); $this->load->model('postmeta'); $this->load->helper('inflector'); $values['post_author'] = $this->input->post('id'); $values['post_title'] = score(ereg_replace($photo['file_ext'], '', $photo['file_name'])); $values['post_name'] = $values['post_title']; $values['post_mime_type'] = 'image/' . ereg_replace('\\.', '', $photo['file_ext']); $values['guid'] = $values['guid'] . $photo['file_name']; $the_photo = $this->post->insert_attach($values); $meta['_wp_attached_file'] = date('Y/m/') . $photo['file_name']; //debo manipular la imagen if (function_exists('getimagesize')) { //Configuraciones general $config['image_library'] = 'gd2'; $config['maintain_ratio'] = TRUE; $config['master_dim'] = 'auto'; $config['source_image'] = $photo['full_path']; $config['new_image'] = 'thumb_' . $photo['file_name']; $this->load->library('image_lib'); //Consigo la info de la img if (FALSE !== ($D = @getimagesize($photo['full_path']))) { $from['w'] = $D['0']; $from['h'] = $D['1']; } $the_meta['width'] = strval($from['w']); $the_meta['height'] = strval($from['h']); $the_meta['hwstring_small'] = "height='96' width='96'"; $the_meta['file'] = $meta['_wp_attached_file']; //thumbnail $tmp_size = 'thumbnail_size'; $to['w'] = $this->options->get_($tmp_size . '_w'); $to['h'] = $this->options->get_($tmp_size . '_h'); $tmp = $this->_crop($from, $to, $photo, $config); if ($tmp != FALSE) { $the_meta['sizes']['thumbnail'] = $tmp; } //echo 'thum: ' . print_r($tmp); //medium_size $tmp_size = 'medium_size'; $to['w'] = $this->options->get_($tmp_size . '_w'); $to['h'] = $this->options->get_($tmp_size . '_h'); $tmp = $this->_resize($from, $to, $photo, $config); if ($tmp != FALSE) { $the_meta['sizes']['medium'] = $tmp; } //echo 'm: ' . print_r($tmp); //large_size $tmp_size = 'large_size'; $to['w'] = $this->options->get_($tmp_size . '_w'); $to['h'] = $this->options->get_($tmp_size . '_h'); $tmp = $this->_resize($from, $to, $photo, $config); if ($tmp != FALSE) { $the_meta['sizes']['large'] = $tmp; } //echo 'l: ' . print_r($tmp); $image_meta = array('aperture' => '0', 'credit' => '', 'camera' => '', 'caption' => '', 'created_timestamp' => '0', 'copyright' => '', 'focal_length' => '0', 'iso' => '0', 'shutter_speed' => '0', 'title' => ''); $the_meta['image_meta'] = $image_meta; //die(print_r($image_meta)); $this->load->library('wpfunctions'); $meta['_wp_attachment_metadata'] = $this->wpfunctions->maybe_serialize($the_meta); } $this->postmeta->insertar($meta, $the_photo); if ($this->_is_ie6() == TRUE or $ie != NULL) { return $the_photo; } else { $tmp = '<img class="thumb-carga" src="' . $values['guid'] . '" />'; echo $the_photo . '#' . $tmp; } } }
<?php include '../benchmark.php'; # TEST 1 for ($i = 0; $i < 100000; $i++) { if (10) { $var = 10; } else { $var = 20; } } score('if else'); # TEST 2 for ($i = 0; $i < 100000; $i++) { $var = 10 ? 10 : 20; } score('.. ? .. : .. '); # TEST 3 - Winner! for ($i = 0; $i < 100000; $i++) { // PHP 5.3+ $var = 10 ?: 20; } score('.. ?: ..');
function accept() { authenticate(1); $answerid = sanitize($_GET['id'], "int"); $sql = "select questionid,userid from answers where id = '" . escape($answerid) . "'"; $query = mysql_query($sql); $answer = mysql_fetch_array($query); $sql = "select questions.*,answers.id answerid, answers.userid answeruserid from questions left join answers on (questions.id = answers.questionid and answers.accepted = 1) where questions.id = '" . escape($answer['questionid']) . "'"; $query = mysql_query($sql); $result = mysql_fetch_array($query); if ($result['kb'] == 1) { header("Location: {$basePath}/questions/view/{$result['id']}/{$result['slug']}"); exit; } if ($result['answerid'] > 0) { score('a_accepted_removed', $answerid, $result['answeruserid']); } else { score('a_accepter', $answerid); } if ($result['userid'] == $_SESSION['userid']) { $sql = "update answers set accepted = '0' where questionid = '" . escape($result['id']) . "'"; $query = mysql_query($sql); $sql = "update answers set accepted = '1' where questionid = '" . escape($result['id']) . "' and id = '" . escape($answerid) . "'"; $query = mysql_query($sql); $sql = "update questions set accepted = '1' where id = '" . escape($result['id']) . "' and userid = '" . escape($_SESSION['userid']) . "'"; $query = mysql_query($sql); score('a_accepted', $answerid, $answer['userid']); } $basePath = basePath(); header("Location: {$basePath}/questions/view/{$result['id']}/{$result['slug']}"); }
$score = "C"; } if ($attendance > 60 && $attendance <= 80) { $score = "B"; } if ($attendance > 80) { $score = "A"; } $output = number_format($attendance) . "/" . $score; return $output; } if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $personname = $row["name"]; $personname = str_replace(' ', '_', $personname); $output = score($row, $timepoints); echo "<tr class=namerow><td class='peopleName'>" . $row["name"] . "</td> <td>" . $output . "</td><td><input type=checkbox id=mid_{$personname} name=\"mid_" . $row["name"] . "\" onClick='submit_on_check(this.name)'/></td>"; for ($i = 0; $i < ($today - 1) * 2; $i++) { echo "<td>" . $row[$timepoints[$i]] . "</td>"; } if ($row[$timepoints[($today - 1) * 2]] != NULL) { echo "<td>" . $row[$timepoints[($today - 1) * 2]] . "</td>"; } else { echo "<td class='itemin'><input type=checkbox name=in_{$personname} id=in_{$personname} onClick='submit_on_check(this.name)' /><label for=in_{$personname}>In</label></td>"; } if ($row[$timepoints[($today - 1) * 2 + 1]] != NULL or $row[$timepoints[($today - 1) * 2 + 1]] == NULL and $row[$timepoints[($today - 1) * 2]] == NULL) { echo "<td>" . $row[$timepoints[($today - 1) * 2 + 1]] . "</td>"; } else { echo "<td class='itemout'><input type=checkbox class='checkthem' name=out_{$personname} id=out_{$personname} onClick='submit_on_check(this.name)' /><label for=out_{$personname}>Out</label></td>"; } for ($i = 0; $i < (7 - $today) * 2; $i++) {
* If you can't find a function you need in PHP, you can create it! * Let's modify our previous exercise to print the score for every name. */ // Create a function to clean the name and // print out the person's name and their "score" function score($name) { $name = ucwords(strtolower(trim($name))); $posA = stripos($name, 'a'); $parts = explode(' ', $name); $last = array_pop($parts); $lenLast = strlen($last); $numWords = str_word_count($name); $score = $posA * $lenLast / $numWords; // Print out the person's name and their "score" echo "{$name}: {$score}" . "<br />"; } $names = ['JASON hunter', ' eRic Schwartz', 'mark zuckerburg ']; // Add a couple extra names to the $names array array_push($names, 'Bob ArK'); array_push($names, 'Derek WaLL'); // loop through our names and call our function foreach ($names as $name) { score($name); } ?> </p> </body> </html>
function upgrade($slot,$currentitemname,$stats,$statslist,$mainhand,$offhand,$spec) { // if no name was entered, assume "None (Slot)" was intended if($currentitemname=="") $currentitemname = "None (".$slot.")"; // create array with old values of stats $oldstats = array(); foreach($stats as $stat) { $oldstats[$stat[1]] = $stats[$stat[1]][0]; } $currentitemname_escaped = mysql_real_escape_string($currentitemname); // get stats for current equipped item $record = mysql_query("SELECT ".$statslist.",uniqgrp,itemid,slot FROM items WHERE name='$currentitemname_escaped' AND itemid IN (SELECT itemid FROM class WHERE ".$spec."='1')") or die(mysql_error()); $result = mysql_fetch_assoc($record) or die("<p>Item not found, please check spelling.</p>"); // create array with stats of current item $currentstats = array(); foreach($stats as $stat) { $currentstats[$stat[1]] = $result[$stat[1]]; } $currentstats["uniqgrp"] = $result['uniqgrp']; $currentzamurl = "http://rift.zam.com/en/item/".$result['itemid']."/"; $currentslot = $result['slot']; // remove modifications on base stats to score properly $stats = modifications_undo($stats); // keep score without dps in case one of the ignore-dps checkboxes is used $oldscorewithoutdps = score($stats,$slot); $stats["dps"][0] = $currentstats["dps"]; $oldscore = score($stats,$slot); // set all stats to their correct values again $stats = talents_calculate($stats); $stats = buffs_calculate($stats); $stats = stats_derive($stats); $stats = talents_calculate_derived($stats); $stats = buffs_calculate_derived($stats); // build the SQL string for the query, use $mainhand and $offhand from settings.php // also, greater essence slot can be filled with lesser essences if($slot=="mainhand") $slotstr = $mainhand; else if($slot=="offhand") $slotstr = $offhand; else if($slot=="greater") $slotstr = "slot='greater' or slot='lesser'"; else $slotstr = "slot='$slot'"; // get info for alternatives in this slot $record = mysql_query("SELECT * FROM items WHERE (".$slotstr.") AND itemid IN (SELECT itemid FROM class WHERE ".$spec."='1')") or die(mysql_error()); // start building the html table ?><div id="suggestions"><p style="font-size:12pt;">Upgrades for <a href="<? echo $currentzamurl; ?>"><? echo stripslashes($currentitemname); ?></a>:</p> <table id="outputtable" class="outputtable" border="0" cellpadding="0" cellspacing="1"> <thead> <tr> <th>Item Name</th> <th>+Score</th> <th>Source</th> <? foreach($stats as $stat) if($stat[4]) echo "<th>".$stat[2]."</th>"; ?> </tr> </thead> <tbody> <? // fill table with results $count = 0; while ($result = mysql_fetch_assoc($record)) { // create array with stats of suggested item $newstats = array(); foreach($stats as $stat) { $newstats[$stat[1]] = $result[$stat[1]]; } $newstats["uniqgrp"] = $result['uniqgrp']; // reset dps variable before adding dps from current weapon (only need dps from 1 slot) $stats["dps"][0] = "0"; // remove any modifications by talents/buffs/derivatives before changing base stats $stats = modifications_undo($stats); // calculate current stats when replacing current item with suggested item // when adding up dps, check if ignore dps checkbox isnt set foreach($stats as $stat) { if($stat[1]=="dps") { if($slot=="ranged"&&$_POST['ignorerngdps']) { $stats[$stat[1]][0] = "0"; $oldscore = $oldscorewithoutdps; } else if($slot=="mainhand"&&$_POST['ignoremhdps']) { $stats[$stat[1]][0] = "0"; $oldscore = $oldscorewithoutdps; } else if($slot=="offhand"&&$_POST['ignoreohdps']) { $stats[$stat[1]][0] = "0"; $oldscore = $oldscorewithoutdps; } else { $stats[$stat[1]][0] = $stats[$stat[1]][0] + $newstats[$stat[1]]; } } else { $stats[$stat[1]][0] = $stats[$stat[1]][0] - $currentstats[$stat[1]] + $newstats[$stat[1]]; } } $newscore = score($stats,$slot); // arrays used for source filtering $t1normals = array("FC","IT","ROTF","KB","LH"); $t2normals = array("DD","DSM","RD","CC","AP"); $t1experts = array("FC (Expert)","IT (Expert)","ROTF (Expert)","KB (Expert)","LH (Expert)"); $t2experts = array("DD (Expert)","DSM (Expert)","RD (Expert)","CC (Expert)","AP (Expert)"); $t1raids = array("GSB","RoS","Sliver - Gilded Prophecy","Sliver - The Drowned Halls"); $t2raids = array("HK"); $zones = array("World","Stillmoor","Iron Pine Peaks","Shimmersand","Stonefield","Gloamwood","Lake of Solace","Moonshade Highlands","Droughtlands","Silverwood","Freemarch","Scarlet Gorge","Scarwood Reach"); // only display upgrades if($newscore > $oldscore) { // skip twohanders if the filter setting for this has been checked if($_POST['ignoretwohanded'] && $result['slot']=="twohanded") $filtered = true; // hide the scrub world drop items "...of the Fortress" etc if the filter setting for this hasn't been enabled elseif(!$_POST['showworlddrop'] && ( (strpos($result['name'],"of the Fortress")>0 && $result['source']=="other") || (strpos($result['name'],"of the Anointed")>0 && $result['source']=="other") || (strpos($result['name'],"of the Devout")>0 && $result['source']=="other") || (strpos($result["name"],"of the Sovereign")>0 && $result['source']=="other") || (strpos($result['name'],"of the Defender")>0 && $result['source']=="other") || (strpos($result['name'],"of the Stalwart")>0 && $result['source']=="other") || (strpos($result['name'],"of Valor")>0 && $result['source']=="other") || (strpos($result['name'],"of Fortune")>0 && $result['source']=="other") || (strpos($result['name'],"of the Warfront")>0 && $result['source']=="other") || (strpos($result['name'],"of the Tenacious")>0 && $result['source']=="other") || (strpos($result['name'],"of the Sinister")>0 && $result['source']=="other") || (strpos($result['name'],"of the Mythical")>0 && $result['source']=="other") )) $filtered = true; // skip items which are filtered out by source, note that first character is left out for start-of-string matches, because a position of 0 would be returned which equals false.. elseif($_POST['filter_quest'] && $result["source"]=="quest") $filtered = true; elseif($_POST['filter_vendor'] && $result["source"]=="vendor") $filtered = true; elseif($_POST['filter_crafting'] && $result["source"]=="crafting") $filtered = true; elseif($_POST['filter_unknown'] && ($result["sourcename"]=="Unknown"||$result["sourcename"]=="Unknown (Let us know!)")) $filtered = true; elseif($_POST['filter_expertrift'] && strpos($result["sourcelocation"],"xpert Rift")) $filtered = true; elseif($_POST['filter_raidrift'] && strpos($result["sourcelocation"],"aid Rift")) $filtered = true; elseif($_POST['filter_pvp'] && (strpos($result["sourcename"],"vP R") || strpos($result["sourcename"],"Favor") || strpos($result["sourcelocation"],"ort Scion") )) $filtered = true; elseif($_POST['filter_zonedrop'] && in_array($result["sourcelocation"],$zones)) $filtered = true; elseif($_POST['filter_t1normal'] && in_array($result["sourcelocation"],$t1normals)) $filtered = true; elseif($_POST['filter_t1expert'] && in_array($result["sourcelocation"],$t1experts)) $filtered = true; elseif($_POST['filter_t2normal'] && in_array($result["sourcelocation"],$t2normals)) $filtered = true; elseif($_POST['filter_t2expert'] && in_array($result["sourcelocation"],$t2experts)) $filtered = true; // hide plaque of achievement gear when both T1 & T2 experts are filtered elseif($_POST['filter_t1expert'] && $_POST['filter_t2expert'] && strpos($result["sourcename"],"Plaques of Achievement")) $filtered = true; elseif($_POST['filter_t1raid'] && in_array($result["sourcelocation"],$t1raids)) $filtered = true; elseif($_POST['filter_t2raid'] && in_array($result["sourcelocation"],$t2raids)) $filtered = true; // hide mark of ascension gear when T1 raids are filtered and greater mark of ascension when T2 raids are filtered elseif($_POST['filter_t1raid'] && strpos($result["sourcename"],"0 Marks of Ascension")) $filtered = true; elseif($_POST['filter_t2raid'] && strpos($result["sourcename"],"0 Greater Marks of Ascension")) $filtered = true; else $filtered = false; // skip items which can't be equipped due to unique item restrictions if($_POST['check_uniqconflict']){ if($slot=="lesser"||$slot=="greater"||$slot=="ring"||$slot=="offhand"||$slot=="mainhand") $uniqconflict = checkuniqueconflicts($result['name'],$slot,$spec); } else $uniqconflict = false; if(!$uniqconflict&&!$filtered) { $count++; $upgradescore = $newscore - $oldscore; if($result['source']=="mob") $source = "Dropped by ".stripslashes($result['sourcename'])." in ".stripslashes($result['sourcelocation']); else if($result['source']=="quest") $source = "Quest: ".stripslashes($result['sourcename']); else if($result['source']=="zone") $source = stripslashes($result['sourcelocation'])." (Zone Drop)"; else if($result['source']=="vendor") $source = stripslashes($result['sourcename']); else if($result['source']=="crafting") $source = "Crafted Item +".stripslashes($result['sourcename']); else if($result['source']=="other") $source = stripslashes($result['sourcename']); else $source = "Unknown"; if($result['quality']=="relic") $color = "orange"; else if($result['quality']=="epic") $color = "purple"; else if($result['quality']=="rare") $color = "blue"; else if($result['quality']=="uncommon") $color = "green"; else $color = "black"; $itemname = stripslashes($result["name"]); $plainitemname = $itemname; $zamurl = "http://rift.zam.com/en/item/".$result['itemid']."/"; $itemname = '<a href="'.$zamurl.'" style="color:'.$color.';" target="new">'.$itemname.'</a>'; ?><tr> <td><? // display a span element that on click will replace the current item // with the upgrade suggestion in the form. does not work with rings/essences at the moment. if($slot<>"ring"&&$slot<>"lesser"&&$slot<>"greater") { ?><span title="Equip item" onclick="fill('<? echo addslashes($plainitemname); ?>')">←</span> <? } echo $itemname; ?></td> <td><? echo round($upgradescore,2); ?></td> <td><? echo $source; ?></td><? foreach($stats as $stat) { // make sure displayed stats also account for talents/buffs $stats = talents_calculate($stats); $stats = buffs_calculate($stats); $stats = stats_derive($stats); $stats = talents_calculate_derived($stats); $stats = buffs_calculate_derived($stats); // if a stat has a threshold and should be displayed in the suggestion list, // format the cell in red when the stat value is below the threshold if($stat[4]&&$stat[5]) { $threshold = $_POST[$stat[1].'target']; if($stats[$stat[1]][0]<$threshold&&$threshold>0) { ?><td style="background-color:#F66"><? echo floor($stats[$stat[1]][0])."</td>"; } else echo "<td>".floor($stats[$stat[1]][0])."</td>"; } // if a stat has no threshold but should still be displayed in the list, just display it else if($stat[4]) echo "<td>".floor($stats[$stat[1]][0])."</td>"; // remove talents/buffs $stats = modifications_undo($stats); } ?></tr><? } } // set values back to original ones before next record foreach($stats as $stat) { $stats[$stat[1]][0] = $oldstats[$stat[1]]; } } // display message when no items were found with newscore > oldscore if($count==0) { ?></tbody> </table><p>No upgrades found!</p> </div> <? } else { ?> </tbody> </table> </div> <script type="text/javascript"> function fill(itemname) { itemname=itemname.replace(/\\'/g,'\''); document.forms["form<? echo $spec; ?>"].elements["<? echo $slot; ?>suggest"].value = itemname; } </script> <? } // show stats totals if($_POST['showstats']) { ?> <div class="stats"> <table class="outputtable" border="0" cellpadding="0" cellspacing="1"> <thead> <tr><? foreach($stats as $stat) { if($stat[3]) echo "<th>".$stat[2]."</th>"; }?><th>Score</th> </tr> </thead> <tbody> <tr><? foreach($stats as $stat) { if($stat[3]) echo "<td>".floor($stat[0])."</td>"; } ?><td><? echo round($oldscorewithoutdps,0); ?></td> </tr> </tbody> </table> </div> <? } }
$lastname = array_pop($parts); $firstname = implode(" ", $parts); $score = strlen($lastname) * stripos($name, 'a') / str_word_count($name); return $score; } // Add a couple extra names to the $names array array_push($names, "Derek Wall", "Seth Handy", "Brian"); // Without writing a loop, use an array function to filter our list // of names down to only those who pass the score test. $names = array_filter($names, function (&$name) { $score = score($name); return $score > 5; }); usort($names, function ($a, $b) { $score_a = score($a); $score_b = score($b); if ($score_a == $score_b) { return 0; } if ($score_a < $score_b) { return 1; } else { return -1; } }); echo implode(",", $names); // Without writing a loop, print out the winners separated by a comma and a space function dd($arg) { die(var_dump($arg)); }
for ($i = 0; $i < 10000; $i++) { $tmp_array = array_map('intval', $array); } score('intval'); # TEST 2 $array = array('1', '2', '3', 'a', 'b', 'c'); for ($i = 0; $i < 10000; $i++) { $tmp_array = array_map(function ($val) { return (int) $val; }, $array); } score('function() { (int) }'); # TEST 3 $int = function ($val) { return (int) $val; }; $array = array('1', '2', '3', 'a', 'b', 'c'); for ($i = 0; $i < 10000; $i++) { $tmp_array = array_map($int, $array); } score('$var = function() { (int) }'); # TEST 4 $int = function ($val) { return intval($val); }; $array = array('1', '2', '3', 'a', 'b', 'c'); for ($i = 0; $i < 10000; $i++) { $tmp_array = array_map($int, $array); } score('$var = function() { intval() }');
} if ($count > 0 && $last === $type) { $rtn[] = $count; } return $rtn; } function unit_to($arr, $to, $from = "U") { return array_map(function ($item) use($to, $from) { return $item === $from ? $to : $item; }, $arr); } function sqrt_of_sums($arr) { return sqrt(array_sum(array_map(function ($item) { return $item * $item; }, $arr))); } function normalize_array($arr) { $total = array_sum($arr); return array_map(function ($row) use($total) { return $row / $total; }, $arr); } $arr = array(array("E", "E", "E", "E"), array("E", "U", "F", "E"), array("U", "U", "F", "E")); while ($line = trim(fgets(STDIN))) { $map = json_decode($line, TRUE); print_r($map); print score($map) . "\n"; }
$lenLast = strlen($last); //gets the length of the last name string $numWords = str_word_count($name); //str_word_count counts number of words in $name string (2) $score = $posA * $lenLast / $numWords; //sets $score to an equation using previously stated variables return $score; //or if($score > 5) { //return true; //} } $passedNames = array_filter($names, function ($name) { // uses closure to call custom function score on a $name return score($name) > 5; }); // Without writing a loop, print out the winners separated by a comma and a space print implode(', ', $passedNames); usort($passedNames, function ($a, $b) { //uses usort to sort names by their score $a = score($a); $b = score($b); if ($a == $b) { return 0; } return $a > $b ? -1 : 1; }); ?> </p> </body> </html>
<?php function score($string, $unique, $length, $charset, $pretty = '') { $chars = str_split($string, 2); $common = str_split($charset); foreach ($unique as $char) { $occur[$char] = substr_count($string, $char); } arsort($occur); $occur = array_keys(array_slice($occur, 0, $length, true)); foreach ($common as $test_char) { foreach ($occur as $occur_char) { $key_chars[] = hex2bin($occur_char) ^ $test_char; } } $key_chars = array_unique($key_chars); printf("Number of possible key-chars: %d\n\n", count($key_chars)); foreach ($key_chars as $key_char) { printf("[Char = '%s' (0x%02x)]\t", $key_char, ord($key_char)); foreach ($chars as $char) { echo $pretty ? $pretty(hex2bin($char) ^ $key_char) : hex2bin($char) ^ $key_char; } echo PHP_EOL; } } $enc = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'; $unique = array_unique(str_split($enc, 2)); score($enc, $unique, 1, ' eta');