Beispiel #1
0
 function test()
 {
     $input = [3 => 1, 1 => 3, 2 => 2];
     $expect = [3, 1, 2];
     $actual = iterator_to_array(keys($input), false);
     $this->assertEquals($expect, $actual);
 }
function remove_keys($gid)
{
    if (tep_not_null($gid)) {
        tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_group_id = '" . (int) $gid . "'");
    } else {
        tep_db_query("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", keys()) . "')");
    }
}
Beispiel #3
0
/**
 * Gets the type of the given argument.
 * ```php
 * type(null); // 'Null'
 * type(true); // 'Boolean'
 * type(false); // 'Boolean'
 * type('Hello World'); // 'String'
 * type(1234); // 'Number'
 * type('123'); // 'String'
 * type(function($x) {return $x;}); // 'Function'
 * type(new \stdClass); // 'Object'
 * type(['name' => 'Foo', 'age' => 21]); // 'Array'
 * type(['Hello', 'World', 123, true]); // 'List'
 * type(['name' => 'Foo', 'Hello', 'Mixed']); // 'Array'
 * type(fopen('php://temp')); // 'Resource'
 * type(Error::of('Ooops !')); // 'Error'
 * // Anything else is 'Unknown'
 * ```
 *
 * @signature * -> String
 * @param  mixed $data
 * @return string
 */
function type()
{
    $type = function ($data) {
        if ($data instanceof Error) {
            return 'Error';
        }
        if ($data instanceof Stream) {
            return "Stream({$data->type})";
        }
        if (is_callable($data)) {
            return 'Function';
        }
        switch (gettype($data)) {
            case 'boolean':
                return 'Boolean';
            case 'NULL':
                return 'Null';
            case 'integer':
            case 'double':
                return 'Number';
            case 'string':
                return 'String';
            case 'resource':
                return 'Resource';
            case 'array':
                if (allSatisfies('is_numeric', keys($data))) {
                    return 'List';
                }
                return 'Array';
            case 'object':
                return 'Object';
            default:
                return 'Unknown';
        }
    };
    return apply(curry($type), func_get_args());
}
Beispiel #4
0
 private function assertKeysValues(array $keys, array $values, callable $fn)
 {
     $this->assertSame($keys, toArray(keys($fn())));
     $this->assertSame($values, toArray(values($fn())));
 }
 function onAfterDispatch()
 {
     global $mainframe;
     $option = JRequest::getCmd('option', '');
     $document =& JFactory::getDocument();
     $docType = $document->getType();
     if (!$mainframe->isSite() || $docType != 'html') {
         return;
     }
     if ($option != 'com_ninjaboard') {
         return;
     }
     if ($option == 'com_ninjaboard') {
         $plugin =& JPluginHelper::getPlugin('system', 'NinjaboardMeta');
         $pluginParams = new JParameter($plugin->params);
         $ninjaboardtitle = $pluginParams->def('maintitle', $mainframe->getCfg('sitename'));
         $ninjaboarddesc = $pluginParams->def('maindescription', $mainframe->getCfg('MetaDesc'));
         $ninjaboardkeywords = $pluginParams->def('mainkeywords', $mainframe->getCfg('MetaKeys'));
         $length = $pluginParams->def('desclength', '200');
         $sep = str_replace('\\', '', $pluginParams->def('separator', '|'));
         //Sets and removes Joomla escape char bug.
         // added pluginParams for toggling Topic/Forum/etc in title
         // jdc
         $showCategory = $pluginParams->def('showcategory', '0');
         $showTopicForum = $pluginParams->def('showtopicforum', '0');
         $showTopicCategory = $pluginParams->def('showtopiccategory', '0');
         //get Ninjaboard variables from URL
         $task = JRequest::getCmd('task', '');
         $view = JRequest::getCmd('view', '');
         // get integer to not escape $id in queries
         $id = JRequest::getInt('id', 0);
         $fid = JRequest::getInt('forum', 0);
         $topic = JRequest::getInt('topic', 0);
         $cat = JRequest::getInt('category', 0);
         //get database config
         $database =& JFactory::getDBO();
         //Title and desc for Ninjaboard board main page.
         //Skip from no forum or topic because for now only use for main page, categories, forums and topics.
         if ($task == '' && $view == 'board' && !$id && !$cat && !$fid && !$topic) {
             $pageTitle = $ninjaboardtitle;
             $metadesc = $ninjaboarddesc;
             $keywords = $ninjaboardkeywords;
         }
         //Category
         if ($task == '' && $view == 'board' && $cat) {
             //get Category's name
             $query = "SELECT `name` FROM #__ninjaboard_categories WHERE id ='{$cat}' AND published='1'";
             $database->SetQuery($query);
             $cattitle = $database->loadResult();
             // ignore 'show' settings here
             $pageTitle = $cattitle . ' ' . $sep . ' ' . $ninjaboardtitle;
             //get categories descriptions from plugin params
             $categories = $pluginParams->def('categories', '');
             if ($categories != '') {
                 $categories = explode("\n", $categories);
                 foreach ($categories as $category) {
                     // get the user-entered categories
                     list($catid, $catdesc) = explode("|", $category);
                     if ($catid == $cat) {
                         $metadesc = $catdesc;
                     }
                 }
             } else {
                 $metadesc = $ninjaboarddesc;
             }
             //get categories keywords
             $categorieskw = $pluginParams->def('categorieskw', '');
             if ($categorieskw != '') {
                 $categorieskw = explode("\n", $categorieskw);
                 foreach ($categorieskw as $category) {
                     // get the user-entered categories
                     list($catid, $catkey) = explode("|", $category);
                     if ($catid == $cat) {
                         $keywords = $catkey;
                     }
                 }
             } else {
                 $keywords = $ninjaboardkeywords;
             }
         }
         //Forum
         if ($view == 'forum' && $fid) {
             //get forum name
             $query = "SELECT f.`name`, f.`description`, c.`name` FROM #__ninjaboard_forums f, #__ninjaboard_categories c WHERE f.id ='{$fid}' AND c.id=f.id_cat";
             $database->SetQuery($query);
             list($forumtitle, $forumdesc, $catname) = $database->loadRow();
             // instead of concat i'm imploding
             $pageTitleParts = array();
             $pageTitleParts[] = $forumtitle;
             if ($showCategory) {
                 $pageTitleParts[] = $catname;
             }
             $pageTitleParts[] = $ninjaboardtitle;
             $pageTitle = implode(' ' . $sep . ' ', $pageTitleParts);
             //$pageTitle = $forumtitle.' '.$sep.' '.$catname.' '.$sep.' '.$ninjaboardtitle;
             //get categories descriptions from plugin params
             $forums = $pluginParams->def('forums', '');
             if ($forums != '') {
                 $forums = explode("\n", $forums);
                 foreach ($forums as $forum) {
                     // get the user-entered categories
                     list($forid, $fordesc) = explode("|", $forum);
                     if ($forid == $fid) {
                         $metadesc = $forumdesc;
                     }
                 }
             } else {
                 $metadesc = $ninjaboarddesc;
             }
             //get categories keywords
             $forumskw = $pluginParams->def('forumskw', '');
             if ($forumskw != '') {
                 $forumskw = explode("\n", $forumskw);
                 foreach ($forumskw as $forums) {
                     // get the user-entered categories
                     list($forid, $forkey) = explode("|", $forums);
                     if ($forid == $fid) {
                         $keywords = $forkey;
                     }
                 }
             } else {
                 $keywords = $ninjaboardkeywords;
             }
         }
         //Topic
         if ($view == 'topic' && $topic) {
             //get topic subject
             $query = "SELECT " . "p.`subject`, p.`text`, f.`name`, c.`name` " . "FROM #__ninjaboard_posts p, #__ninjaboard_forums f, #__ninjaboard_categories c " . "WHERE p.`id_topic`='{$topic}' AND p.`id_forum`=f.`id` AND c.`id`=f.`id_cat` " . "ORDER BY p.`id` ASC LIMIT 1";
             $database->SetQuery($query);
             list($topictitle, $topicdesc, $forumtitle, $catname) = $database->loadRow();
             // instead of concat i'm imploding
             $pageTitleParts = array();
             $pageTitleParts[] = $topictitle;
             if ($showTopicForum) {
                 $pageTitleParts[] = $forumtitle;
             }
             if ($showTopicCategory) {
                 $pageTitleParts[] = $catname;
             }
             $pageTitleParts[] = $ninjaboardtitle;
             $pageTitle = implode(' ' . $sep . ' ', $pageTitleParts);
             //$pageTitle = $topictitle.' '.$sep.' '.$ninjaboardtitle;
             // commented out the rest - nb doesn't have topicdesc :/
             // just use the post text
             //get topic description
             //if ($topicdesc!=''){
             $metadesc = $topicdesc;
             /*}
             		else {
             			//if there is no topic description, get first post to set as metadesc
             			$query = "SELECT message FROM #__ninjaboard_posts WHERE topic_id ='$id' ORDER BY id ASC LIMIT 1";
             			$database->SetQuery ($query);
             			$topicdesc = $database->loadResult();
             			$metadesc = $topicdesc;
             		}*/
             //TODO: get topic keywords.
             $text = $topictitle;
             $text .= $topicdesc;
             // killed this, just use $query above
             //$query = "SELECT message FROM #__ninjaboard_posts WHERE topic_id ='$id' ORDER BY id ASC LIMIT 1";
             $text .= $database->loadRow();
             $listexclude = $pluginParams->def('listexclude', '');
             $listgoldwords = $pluginParams->def('goldwords', '');
             $mindensity = $pluginParams->def('mindensity', '2');
             $minlength = $pluginParams->def('minlength', '5');
             $maxwords = $pluginParams->def('maxwords', '20');
             $keywords = keys($text, $listexclude, $listgoldwords, $mindensity, $minlength, $maxwords);
         }
         //Profile
         if (in_array($view, array('profile', 'userposts')) && $id || $view == 'editprofile') {
             // if editprofile, we need the user id
             if ($view == 'editprofile') {
                 $user =& JFactory::getUser();
                 $id = $user->get('id');
             }
             //get all forms of user name and signature
             $query = "SELECT u.`name`, u.`username`, p.`p_firstname`, p.`p_lastname`, nu.`signature` " . "FROM #__users u, #__ninjaboard_profiles p, #__ninjaboard_users nu " . "WHERE u.id ='{$id}' AND p.id = u.id AND p.id = nu.id LIMIT 1";
             $database->SetQuery($query);
             list($fname, $uname, $pfname, $plname, $psig) = $database->loadRow();
             // start an array for first & last name
             $pname = array();
             // if either are 0 length, don't add
             if (strlen($pfname) > 0) {
                 $pname[] = $pfname;
             }
             if (strlen($plname) > 0) {
                 $pname[] = $plname;
             }
             // set page title by precedence: profile names, name, username
             $pname = count($pname) > 0 ? $pname = implode(' ', $pname) : (strlen($fname) ? $fname : $uname);
             $pageTitle = 'Ninjaboard profile for ' . $pname . ' ' . $sep . ' ' . $ninjaboardtitle;
             // meta is the signature
             $metadesc = strlen($psig) > 0 ? htmlentities($psig) : $ninjaboarddesc;
             // get user keywords: either use first & last name
             $keywords = preg_replace('/\\s/', ',', $pname);
         }
         /*
         this would be better if done in a loop, I know - 
         but it's done this way namely for 2 reasons:
         1) it's the set convention already :P
         2) maybe sometime in the future some of these views will have different keywords & meta descriptions
         */
         // Latest Posts
         if ($view == 'latestposts') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_LATESTPOSTS') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // Who's Online
         if ($view == 'whosonline') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_WHOSONLINE') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // user list
         if ($view == 'userlist') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_USERLIST') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // terms
         if ($view == 'terms') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_TERMS') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // edittopic
         if ($view == 'edittopic') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_EDITTOPIC') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // editpost
         if ($view == 'editpost') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_EDITPOST') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // search
         if ($view == 'search') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_SEARCH') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // login
         if ($view == 'login') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_LOGIN') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // reportpost
         if ($view == 'reportpost') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_REPORTPOST') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // requestlogin
         if ($view == 'requestlogin') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_REQUESTLOGIN') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // resetlogin
         if ($view == 'resetlogin') {
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_RESETLOGIN') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // information
         if ($view == 'information') {
             // this would be a cool one to customize!
             $keywords = $ninjaboardkeywords;
             $metadesc = $ninjaboarddesc;
             $pageTitle = JText::_('NB_INFORMATION') . ' ' . $sep . ' ' . $ninjaboardtitle;
         }
         // Set Metatags
         $document->setTitle($pageTitle);
         // Clean things up and prepare Meta Description tag.
         $metadesc = $this->cutText($metadesc);
         $metadesc = $metadesc . ' ';
         $metadesc = substr($metadesc, 0, $length);
         $metadesc = substr($metadesc, 0, strrpos($metadesc, ' '));
         $document->setDescription($metadesc);
         $document->setMetaData('keywords', $keywords);
     }
 }
 function get_dependencies($entity)
 {
     // Get the classes that we depend on
     $pre_depends = $this->entities[$entity]->get_ilinks();
     $entities_depends = keys($pre_depends);
     foreach ($entities_depends as $entity_depend) {
         if (array_key_exists($entity_depend, $this->entities)) {
             //We depend in entity that is in array
             $this->get_dependencies($entity_depend);
             $this->set_insert_dependency($entity, $entity_depend);
         }
     }
     $this->add_insert_array($entity);
 }
Beispiel #7
0
 public function testKeyValue()
 {
     $array = ['a' => 'b', 'c' => 'd', 'e' => 'f'];
     $this->assertSame(['b', 'd', 'f'], toArrayWithKeys(values($array)));
     $this->assertSame(['a', 'c', 'e'], toArrayWithKeys(keys($array)));
 }
Beispiel #8
0
    $obj->set('a', true);
    $obj->set('b', false);
    $keys = keys($obj);
    sort($keys, SORT_STRING);
    Test::assert('basic keys', join(',', $keys) === 'a,b');
    $child = $Object->callMethod('create', $obj);
    $child->set('c', 'foo');
    $keys = keys($child);
    sort($keys, SORT_STRING);
    Test::assert('inherited keys', join(',', $keys) === 'a,b,c');
});
Test::suite('Object', function () use($Object) {
    $o = new Object("a", 1.0, "b", 2.0);
    Test::assert('for..in helper', join(',', keys($o)) === 'a,b');
    $o = new Object("a", 1.0, "b", 2.0);
    Test::assert('for..in helper', join(',', keys($o)) === 'a,b');
});
Test::suite('Array.prototype', function () use($Object, $Array) {
    Test::assert('should be distinct from Object.prototype', $Array->get('prototype') !== $Object->get('prototype'));
    Test::assert('should be that of Arr', $Array->get('prototype') === Arr::$protoObject);
});
Test::suite('Array: init, push and join', function () use($Array) {
    $arr = $Array->construct(1);
    Test::assert('proto exists', $arr->proto instanceof Object);
    Test::assert('proto is set correctly', $arr->proto === $Array->get('prototype'));
    Test::assert('proto chain', $arr->proto->proto === Object::$protoObject);
    Test::assert('length', $arr->get('length') === 1.0);
    Test::assert('get', $arr->get(0) === null);
    Test::assert('push', call_method($arr, 'push', 9.0) === 2.0);
    Test::assert('length 2', $arr->get('length') === 2.0);
    Test::assert('join', call_method($arr, 'join', ';') === ';9');
Beispiel #9
0
}, 'vector?' => function ($a) {
    return _vector_Q($a);
}, 'hash-map' => function () {
    return call_user_func_array('_hash_map', func_get_args());
}, 'map?' => function ($a) {
    return _hash_map_Q($a);
}, 'assoc' => function () {
    return call_user_func_array('assoc', func_get_args());
}, 'dissoc' => function () {
    return call_user_func_array('dissoc', func_get_args());
}, 'get' => function ($a, $b) {
    return get($a, $b);
}, 'contains?' => function ($a, $b) {
    return contains_Q($a, $b);
}, 'keys' => function ($a) {
    return keys($a);
}, 'vals' => function ($a) {
    return vals($a);
}, 'sequential?' => function ($a) {
    return _sequential_Q($a);
}, 'cons' => function ($a, $b) {
    return cons($a, $b);
}, 'concat' => function () {
    return call_user_func_array('concat', func_get_args());
}, 'nth' => function ($a, $b) {
    return nth($a, $b);
}, 'first' => function ($a) {
    return first($a);
}, 'rest' => function ($a) {
    return rest($a);
}, 'empty?' => function ($a) {
Beispiel #10
0
/**
 * Returns `true` if the two elements have the same type and are deeply equivalent.
 * ```php
 * $a = (object) ['a' => 1, 'b' => (object) ['c' => 'Hello'], 'd' => false];
 * $b = (object) ['a' => 1, 'b' => (object) ['c' => 'Hi'], 'd' => false];
 * $c = (object) ['a' => 1, 'b' => ['c' => 'Hello'], 'd' => false];
 * equals(5, '5'); // false (should have the same type)
 * equals([1, 2, 3], [1, 2, 3]); // true
 * equals([1, 3, 2], [1, 2, 3]); // false (should have the same order)
 * equals($a, $b); // false
 * equals($a, $c); // false
 * $b->b->c = 'Hello';
 * equals($a, $b); // true
 * ```
 *
 * @signature * -> * -> Boolean
 * @param  mixed $a
 * @param  mixed $b
 * @return bool
 */
function equals()
{
    $equals = function ($a, $b) {
        $type = type($a);
        if ($type != type($b)) {
            return false;
        }
        switch ($type) {
            case 'Null':
            case 'Boolean':
            case 'String':
            case 'Number':
            case 'Unknown':
            case 'Function':
            case 'Resource':
            case 'Error':
            case 'Stream':
                return $a == $b;
            case 'List':
                $length = length($a);
                return length($b) != $length ? false : 0 == $length ? true : equals(head($a), head($b)) && equals(tail($a), tail($b));
            case 'Array':
            case 'ArrayObject':
            case 'Object':
                return equals(keys($a), keys($b)) && equals(values($a), values($b));
        }
    };
    return apply(curry($equals), func_get_args());
}
 function getTypes()
 {
     return keys($this->messages);
 }
Beispiel #12
0
/**
 * Converts an object or associative array to an array of [key, value] pairs.
 * ```php
 * $list = ['key' => 'value', 'number' => 53, 'foo', 'bar'];
 * toPairs($list); // [['key', 'value'], ['number', 53], [0, 'foo'], [1, 'bar']]
 * ```
 *
 * @signature {k: v} -> [(k,v)]
 * @param  array $object
 * @return array
 */
function toPairs($object)
{
    $object = attributes($object);
    return map(function ($key) use($object) {
        return [$key, $object[$key]];
    }, keys($object));
}
Beispiel #13
0
 protected function yhteensaAnalyysi($pvm)
 {
     $return = array();
     $criteria = new CDbCriteria();
     $criteria->with = array('viivakoodi');
     $criteria->condition = " \n\t\t\tuser_id = '" . Yii::app()->user->id . "' \n\t\t\tAND pvm='" . $pvm . "'\n\t\t";
     $m = KayttajanSisalto::model()->findAll($criteria);
     $criteria = new CDbCriteria();
     $criteria->select = " SUM(gramm) as gramm ";
     $criteria->condition = " \n\t\t\tuser_id = '" . Yii::app()->user->id . "' \n\t\t\tAND pvm='" . $pvm . "'\n\t\t";
     $m2 = KayttajanSisalto::model()->find($criteria);
     // 27.03.2016
     $energiankulutus = 0;
     $pvmE = date("Y-m-d", strtotime($pvm));
     $criteria = new CDbCriteria();
     $criteria->condition = " user_id='" . Yii::app()->user->id . "' AND pvm='" . $pvmE . "' ";
     $li = LiikuntaUser::model()->findAll($criteria);
     if (isset($li[0])) {
         foreach ($li as $data) {
             $energiankulutus += (double) $data->energiankulutus;
         }
     }
     // 27.03.2016
     $tavoite = $this->tavoite($energiankulutus);
     $attr = Viivakoodi::model()->getAttributes();
     //$attributes = $this->unsetViivakoodista($attr);
     $attributes = array('energia_kcal', 'proteiini', 'hiilihydraatti', 'rasva', 'vesi_tai_vettavastaava', 'tyydyttyneet_rasvat', 'kuitu', 'suola', 'sokerit', 'kalsium', 'magnesium', 'rauta', 'sinkki', 'c_vitamiini', 'd_vitamiini');
     function keys($key, $annoskoko, $gramm, $raja)
     {
         return round((double) ($key / $annoskoko * $gramm), 1) / $raja * 100;
     }
     $magnesium = 0;
     $rauta = 0;
     $sinkki = 0;
     $c_vitamiini = 0;
     $d_vitamiini = 0;
     $hiilihydraatti = 0;
     $paino = 0;
     $proteiini = 0;
     $alkoholi = 0;
     $pr = Profile::model()->find(" user_id = '" . Yii::app()->user->id . "' ");
     if (isset($pr->user_id)) {
         /*if($pr->paino > 0)
         		$hiilihydraatti = $pr->paino*5;
         		*/
         if ($pr->sukupuoli == 1) {
             //nainen
             $magnesium = 280;
             $rauta = 15;
             $sinkki = 7;
             $c_vitamiini = 75;
             $d_vitamiini = 10;
             $alkoholi = 15;
         } elseif ($pr->sukupuoli == 2) {
             //mies
             $magnesium = 350;
             $rauta = 9;
             $sinkki = 9;
             $c_vitamiini = 75;
             $d_vitamiini = 10;
             $alkoholi = 20;
         }
         /*
         		    if($pr->ruokavalio == 0 and $pr->muokkaa_ruokavalio_suositusta == 0){
         
         			$proteiini = 1.2*$pr->paino;
         
         		    } elseif($pr->ruokavalio == 1 and $pr->muokkaa_ruokavalio_suositusta == 0) {
         
         		  	if($pr->proteiini == 0) $proteiini = 1*$pr->paino;
         		  	if($pr->proteiini == 1) $proteiini = 1.3*$pr->paino;
         		  	if($pr->proteiini == 2) $proteiini = 1.5*$pr->paino;
         		  	if($pr->proteiini == 3) $proteiini = 2*$pr->paino;
         
         			  } elseif($pr->ruokavalio == 1 and $pr->muokkaa_ruokavalio_suositusta == 1) {
         	
         			$proteiini = 1.2*$pr->paino; // tassa vaihessa epaselkea
         		    } 
         */
     }
     if (isset($m[0])) {
         foreach ($attributes as $key) {
             $u = 0;
             $return[$key] = '';
             foreach ($m as $model) {
                 $v = Viivakoodi::model()->findbypk($model->tuote);
                 $annoskoko = 100;
                 if (!empty($v->annoskoko)) {
                     $annoskoko = (double) $v->annoskoko;
                 }
                 if ($key == 'energia_kcal' and $tavoite > 0) {
                     $energia_kcal = round((double) ($v->{$key} / $annoskoko * $model->gramm), 1);
                     $v->{$key} = $energia_kcal / $tavoite * 100;
                     $return[$key] += $v->{$key};
                 } elseif ($key == 'kuitu' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, 30);
                 } elseif ($key == 'suola' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, 5);
                 } elseif ($key == 'kalsium' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, 800);
                 } elseif ($key == 'magnesium' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, $magnesium);
                 } elseif ($key == 'rauta' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, $rauta);
                 } elseif ($key == 'sinkki' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, $sinkki);
                 } elseif ($key == 'c_vitamiini' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, $c_vitamiini);
                 } elseif ($key == 'd_vitamiini' and $v->{$key} > 0) {
                     $return[$key] += keys($v->{$key}, $annoskoko, $model->gramm, $d_vitamiini);
                 } elseif (($key == 'tyydyttyneet_rasvat' or $key == 'hiilihydraatti' or $key == 'rasva' or $key == 'vesi_tai_vettavastaava' or $key == 'proteiini' or $key == 'sokerit') and $v->{$key} > 0) {
                     $return[$key] += round((double) ($v->{$key} / $annoskoko * $model->gramm), 1);
                 } else {
                     $return[$key] += (double) ($v->{$key} / 100 * $model->gramm);
                 }
             }
         }
         $return['proteiini'] = $return['proteiini'] / ($tavoite / 4 * ($this->ympyra('proteiini') / 100)) * 100;
         $return['rasva'] = $return['rasva'] / ($tavoite / 9 * ($this->ympyra('rasva') / 100)) * 100;
         $return['vesi_tai_vettavastaava'] = $return['vesi_tai_vettavastaava'] * 100 / 1500 * 100;
         $return['tyydyttyneet_rasvat'] = $return['tyydyttyneet_rasvat'] / ($tavoite / 9 * 0.05) * 100;
         //$return['transrasvahapot'] = $return['transrasvahapot']/(($tavoite/9)*0.05)*100;
         //$return['yksityistyydyttymattomat_rasvat'] = $return['yksityistyydyttymattomat_rasvat']/(($tavoite/9)*0.15)*100;
         //$return['monityydyttymattomat_rasvat'] = $return['monityydyttymattomat_rasvat']/(($tavoite/9)*0.10)*100;
         $return['hiilihydraatti'] = $return['hiilihydraatti'] / ($tavoite / 4 * (100 - (int) $this->ympyra('proteiini') - (int) $this->ympyra('rasva')) / 100) * 100;
         $return['sokerit'] = $return['sokerit'] / ($tavoite / 4 * 0.1) * 100;
     } else {
         $return['ei tietoja'] = 0;
     }
     return $return;
 }
Beispiel #14
0
/**
 * Splits a string into chunks without spliting any group surrounded with some
 * specified characters. `$surrounders` is a string where each pair of characters
 * specifies the starting and ending characters of a group that should not be split.
 * ```php
 * $groups = chunks('(){}', ',');
 * $groups('1,2,(3,4,5),{6,(7,8)},9'); // ['1', '2', '(3,4,5)', '{6,(7,8)}', '9']
 *
 * $names = chunks('()""', ' ');
 * $names('Foo "Bar Baz" (Some other name)'); // ['Foo', 'Bar Baz', 'Some other name']
 * ```
 *
 * @signature String -> String -> String -> [String]
 * @param  string $surrounders
 * @param  string $separator
 * @param  sring $text
 * @return array
 */
function chunks()
{
    $chunks = function ($surrounders, $separator, $text) {
        // Let's assume some values to understand how this function works
        // surrounders = '""{}()'
        // separator = ' '
        // $text = 'foo ("bar baz" alpha) beta'
        $surrounders = map(slices(1), slices(2, $surrounders));
        // [['"'. '"'], ['{'. '}'], ['(', ')']]
        $openings = map(get(0), $surrounders);
        // ['"', '{', '(']
        $closings = map(get(1), $surrounders);
        // ['"', '}', ')']
        $numOfSurrounders = length($surrounders);
        // 3
        $indexes = keys($surrounders);
        // [0, 1, 2]
        $items = split($separator, $text);
        // ['foo', '("bar', 'baz"', 'alpha)', 'beta']
        // The initial state
        $state = (object) ['chunks' => [], 'counts' => array_fill(0, $numOfSurrounders, 0), 'total' => 0];
        // We will iterate over $items and update the $state while adding them
        // For each item we need to update counts and chunks
        // Updates count for a single surrender (the surrender at $index)
        // $item : the item we are adding
        // $counts : the previous counts
        $updateCountAt = curry(function ($item, $counts, $index) use($openings, $closings) {
            $count = occurences(__(), $item);
            return $openings[$index] == $closings[$index] ? ($counts[$index] + $count($openings[$index])) % 2 : $counts[$index] + $count($openings[$index]) - $count($closings[$index]);
        });
        // Updates counts for all surrenders
        $updateCounts = curry(function ($item, $counts) use($indexes, $updateCountAt) {
            return map($updateCountAt($item, $counts), $indexes);
        });
        // Adds an item to the state and returns a new state
        $addItem = function ($state, $item) use($separator, $updateCounts) {
            $counts = $updateCounts($item, get('counts', $state));
            $newChunks = 0 == $state->total ? append($item, $state->chunks) : append(last($state->chunks) . $separator . $item, init($state->chunks));
            return (object) ['chunks' => $newChunks, 'counts' => $counts, 'total' => sum($counts)];
        };
        // Returns the chunks of the resulting state after adding all items
        return get('chunks', reduce($addItem, $state, $items));
    };
    return apply(curry($chunks), func_get_args());
}
Beispiel #15
0
/**
 * Return true if an array is an associative array, false if sequential or empty
 */
function is_assoc(array $arr)
{
    return keys($arr) !== range(0, count($arr) - 1);
}
Beispiel #16
0
function zalohuj($db, $soubor = "")
{
    global $dbusr;
    function keys($prefix, $array)
    {
        if (empty($array)) {
            $pocet = 0;
        } else {
            $pocet = count($array);
        }
        if (!isset($radky)) {
            $radky = '';
        }
        if ($pocet == 0) {
            return;
        }
        for ($i = 0; $i < $pocet; $i++) {
            $radky .= "`" . $array[$i] . "`" . ($i != $pocet - 1 ? "," : "");
        }
        return ",\n" . $prefix . "(" . $radky . ")";
    }
    $sql = mysql_query("SHOW table status  FROM " . $db);
    while ($data = mysql_fetch_row($sql)) {
        if (!isset($text)) {
            $text = '';
        }
        $text .= (empty($text) ? "" : "\n\n") . "--\n-- Struktura tabulky " . $data[0] . "\n--\n\n\n";
        $text .= "CREATE TABLE `" . $data[0] . "`(\n";
        $sqll = mysql_query("SHOW columns  FROM " . $data[0]);
        $e = true;
        while ($dataa = mysql_fetch_row($sqll)) {
            if ($e) {
                $e = false;
            } else {
                $text .= ",\n";
            }
            $null = $dataa[2] == "NO" ? "NOT NULL" : "NULL";
            $default = !empty($dataa[4]) ? " DEFAULT '" . $dataa[4] . "'" : "";
            if ($default == " DEFAULT 'CURRENT_TIMESTAMP'") {
                $default = " DEFAULT CURRENT_TIMESTAMP";
            }
            if ($dataa[3] == "PRI") {
                $PRI[] = $dataa[0];
            }
            if ($dataa[3] == "UNI") {
                $UNI[] = $dataa[0];
            }
            if ($dataa[3] == "MUL") {
                $MUL[] = $dataa[0];
            }
            $extra = !empty($dataa[5]) ? " " . $dataa[5] : "";
            $text .= "`{$dataa['0']}` {$dataa['1']} {$null}{$default}{$extra}";
        }
        if (!isset($UNI)) {
            $UNI = '';
        }
        if (!isset($PRI)) {
            $PRI = '';
        }
        if (!isset($MUL)) {
            $MUL = '';
        }
        $primary = keys("PRIMARY KEY", $PRI);
        $unique = keys("UNIQUE KEY", $UNI);
        $mul = keys("INDEX", $MUL);
        $text .= $primary . $unique . $mul . "\n) ENGINE=" . $data[1] . " COLLATE=" . $data[14] . ";\n\n";
        unset($PRI, $UNI, $MUL);
        $text .= "--\n-- Data tabulky " . $data[0] . "\n--\n\n";
        $query = mysql_query("SELECT  * FROM " . $data[0] . "");
        while ($fetch = mysql_fetch_row($query)) {
            $pocet_sloupcu = count($fetch);
            for ($i = 0; $i < $pocet_sloupcu; $i++) {
                @($values .= "'" . mysql_escape_string($fetch[$i]) . "'" . ($i < $pocet_sloupcu - 1 ? "," : ""));
            }
            $text .= "\nINSERT INTO `" . $data[0] . "` VALUES(" . $values . ");";
            unset($values);
        }
    }
    if (!empty($soubor)) {
        $fp = @fopen($soubor, "w+");
        $fw = @fwrite($fp, $text);
        @fclose($fp);
    }
    return $text;
}
Beispiel #17
0
}, 'snoc' => function ($x, $y) {
    return merge($y, [$x]);
}, 'echo_' => function ($x) {
    echo $x;
    return $x;
}, 'id' => function ($x) {
    return $x;
}, 'chain' => function ($x, $y, $z) {
    return $x($z, $y($z));
}, 'zip' => function ($arr1, $arr2) {
    return foldr(function ($acc, $val) use($arr1, $arr2) {
        $lookup = subscript($val);
        $el1 = $lookup($arr1);
        $el2 = $lookup($arr2);
        return merge($acc, [[$el1, $el2]]);
    }, [], keys($arr1));
}, 'dup' => function ($x) {
    return [$x, $x];
}, 'swap' => function ($arr) {
    return merge([$arr[1], $arr[0]], array_slice($arr, 2));
}, 'first' => function ($f, $arr) {
    return cons($f(subscript(0, $arr)), array_slice($arr, 1));
}, 'second' => function ($f) {
    return compose('swap', first($f), 'swap');
}, 'head' => function ($arr) {
    return $arr[0];
}, 'delay' => function ($f, $args, $_) {
    return call_user_func_array($f, $args);
}]);
defun('format', function ($x) {
    return is_float($x) ? number_format($x, 6) : (is_array($x) ? map('format', $x) : $x);
Beispiel #18
0
<br>
<?php 
include "blowfish.php";
include "sudoku_seb.php";
$text = "6,5,,7,8,,,2,,3,,,,,,7,,9,9,,,1,2,,4,5,6,2,1,9,3,4,5,6,7,8,5,,,6,7,8,9,1,,8,7,6,9,1,2,3,4,5,7,6,,8,9,1,,3,4,4,3,2,,6,7,8,,1,1,9,8,,,,5,6,";
echo "</br>Sudoku reading:";
$sudoku = initSudoku($text);
echo $sudoku;
echo "</br>Sudoku solving:";
$sudoku = resolutionSimple($sudoku);
echo $sudoku;
echo "</br>Sudoku parsing:";
$result = sudokuToString($sudoku);
echo $result;
echo "</br>Sha1:";
$result = sha1($result);
echo $result;
echo "</br>Blowfish key generation:";
keys($result);
//Schlüssel Definieren
echo "</br>key:";
echo $key;
echo "</br>Blowfish key generation:";
//$text = blowfish_crypt($text); //Verschlüsseln
$encrypted = "Vm6c7wAK15IeEvUBshqV2g==";
echo "</br>Verschlüsseln Text:";
echo $encrypted;
$decrypted = blowfish_decrypt($encrypted);
//Entschlüsseln
echo "</br>Unverschlüsselter Text:";
echo $decrypted;
Beispiel #19
0
<meta name="author" content="Jakob Michalka">
<style type="text/css">
<!--
body, table {
 font-family: Verdana;
}
-->
</style>
</head>
<body text="#000000" bgcolor="#FFFFFF" link="#0000FF" alink="#0000FF" vlink="#0000FF">
<?php 
$key = $_POST['key'];
include "blowfish.php";
$text = trim($_POST['text']);
if (isset($_POST['key'])) {
    keys($_POST['key']);
}
//Schlüssel Definieren
if (isset($_POST["crypt"])) {
    $text = blowfish_crypt($text);
    //Verschlüsseln
    $s = "Verschl&uuml;sselt";
} elseif (isset($_POST["decrypt"])) {
    $text = blowfish_decrypt($text);
    //Entschlüsseln
    $s = "Entschl&uuml;sselt";
}
?>
<br>
<h1 align="center">blowfish demo 1</h1>
<br>