Salsa20/8 http://en.wikipedia.org/wiki/Salsa20
552242
def salsa20_8(B, x, src, s_start, dest, d_start):
    """"""

    # Merged blockxor for speed
    for i in xrange(16):
        x[i] = B[i] = B[i] ^ src[s_start + i]

    # This is the actual Salsa 20/8: four identical double rounds
    for i in xrange(4):
        R(x, 4, 0,12, 7);R(x, 8, 4, 0, 9);R(x,12, 8, 4,13);R(x, 0,12, 8,18)
        R(x, 9, 5, 1, 7);R(x,13, 9, 5, 9);R(x, 1,13, 9,13);R(x, 5, 1,13,18)
        R(x,14,10, 6, 7);R(x, 2,14,10, 9);R(x, 6, 2,14,13);R(x,10, 6, 2,18)
        R(x, 3,15,11, 7);R(x, 7, 3,15, 9);R(x,11, 7, 3,13);R(x,15,11, 7,18)
        R(x, 1, 0, 3, 7);R(x, 2, 1, 0, 9);R(x, 3, 2, 1,13);R(x, 0, 3, 2,18)
        R(x, 6, 5, 4, 7);R(x, 7, 6, 5, 9);R(x, 4, 7, 6,13);R(x, 5, 4, 7,18)
        R(x,11,10, 9, 7);R(x, 8,11,10, 9);R(x, 9, 8,11,13);R(x,10, 9, 8,18)
        R(x,12,15,14, 7);R(x,13,12,15, 9);R(x,14,13,12,13);R(x,15,14,13,18)

    # While we are handling the data, write it to the correct dest.
    # The latter half is still part of salsa20
    for i in xrange(16):
        dest[d_start + i] = B[i] = (x[i] + B[i]) & 0xffffffff
970090
def tblCites
      @headers = %w{TaxonNameID SeqNum RefID NomenclatorID LastUpdate ModifiedBy NewNameStatus CitePages Note TypeClarification CurrentConcept ConceptChange InfoFlags InfoFlagStatus PolynomialStatus}
      sql = []

      @name_collection.citations.keys.each do |name_id|
        seq_num = 1 
        @name_collection.citations[name_id].each do |ref_id, nomenclator_index, properties|
          cols = {
            TaxonNameID:       name_id,
            SeqNum:            seq_num,
            RefID:             ref_id,
            NomenclatorID:     nomenclator_index,
            LastUpdate:        @time, 
            ModifiedBy:        @authorized_user_id,
            CitePages:         (properties[:cite_pages] ? properties[:cite_pages] : @empty_quotes),
            NewNameStatus:     0,
            Note:              (properties[:note] ? properties[:note] : @empty_quotes),
            TypeClarification: 0,     # We might derive more data from this
            CurrentConcept:    (properties[:current_concept] == true ? 1 : 0),     # Boolean, right?
            ConceptChange:     0,     # Unspecified
            InfoFlags:         0,     # 
            InfoFlagStatus:    1,     # 1 => needs review
            PolynomialStatus:  0
          }
          sql << sql_insert_statement('tblCites', cols) 
          seq_num += 1
        end
      end
      sql.join("\n")
    end
447920
public function index(){

        $test = new \core_kernel_classes_Resource($this->getRequestParameter('uri'));
        
        $model = $this->getServiceManager()->get(TestModel::SERVICE_ID);

        $itemSequence = array();
        $itemUris = array();
        $counter = 1;
        foreach($model->getItems($test) as $item){
            $itemUris[] = $item->getUri();
            $itemSequence[$counter] = array(
                'uri' 	=> tao_helpers_Uri::encode($item->getUri()),
                'label' => $item->getLabel()
            );
            $counter++;
        }
        
		// data for item sequence, terrible solution
		// @todo implement an ajax request for labels or pass from tree to sequence
		$allItems = array();
		foreach(\taoTests_models_classes_TestsService::singleton()->getAllItems() as $itemUri => $itemLabel){
			$allItems['item_'.tao_helpers_Uri::encode($itemUri)] = $itemLabel;
		}


        $config = $model->getConfig($test);
        $checked = (isset($config['previous']))? $config['previous'] : false;
        $testConfig['previous'] = array('label' => __('Allow test-taker to go back in test'), 'checked' => $checked);

		$this->setData('uri', $test->getUri());
    	$this->setData('allItems', json_encode($allItems));
		$this->setData('itemSequence', $itemSequence);
		$this->setData('testConfig', $testConfig);

		// data for generis tree form
		$this->setData('relatedItems', json_encode(tao_helpers_Uri::encodeArray($itemUris)));

		$openNodes = TreeHelper::getNodesToOpen($itemUris, new core_kernel_classes_Class(TaoOntology::ITEM_CLASS_URI));
		$this->setData('itemRootNode', TaoOntology::ITEM_CLASS_URI);
		$this->setData('itemOpenNodes', $openNodes);
		$this->setData('saveUrl', _url('saveItems', 'Authoring', 'taoTestLinear'));
        $this->setView('Authoring/index.tpl');
    }
164694
function blockmix_salsa8(BY, Yi, r, x, _X) {
        var i;

        arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16);
        for (i = 0; i < 2 * r; i++) {
            blockxor(BY, i * 16, _X, 16);
            salsa20_8(_X, x);
            arraycopy(_X, 0, BY, Yi + (i * 16), 16);
        }

        for (i = 0; i < r; i++) {
            arraycopy(BY, Yi + (i * 2) * 16, BY, (i * 16), 16);
        }

        for (i = 0; i < r; i++) {
            arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16);
        }
    }
1191346
function fetchGroupList()
    {
        $this->InGroups = eZContentClassClassGroup::fetchGroupList( $this->attribute( "id" ),
                                                                     $this->attribute( "version" ),
                                                                     true );
        return $this->InGroups;
    }
493060
def smix(B, Bi, r, N, V, X):
    """"""

    X[0:(0)+(32 * r)] = B[Bi:(Bi)+(32 * r)]

    for i in xrange(N):                                # ROMix - 2
        V[i * (32 * r):(i * (32 * r))+(32 * r)] = X[0:(0)+(32 * r)]
        blockmix_salsa8(X, 32 * r, r)                  # ROMix - 4

    for i in xrange(N):                                # ROMix - 6
        j = integerify(X, r) & (N - 1)                 # ROMix - 7
        blockxor(V, j * (32 * r), X, 0, 32 * r)        # ROMix - 8(inner)
        blockmix_salsa8(X, 32 * r, r)                  # ROMix - 9(outer)

    B[Bi:(Bi)+(32 * r)] = X[0:(0)+(32 * r)]
548357
public function listSitesAction()
    {
        $contextManager = $this->get('open_orchestra_backoffice.context_backoffice_manager');
        $currentSiteId = $contextManager->getSiteId();

        $siteIdsAllowedShare = array($currentSiteId);

        $mediaLibrariesSharing = $this->get('open_orchestra_media.repository.media_library_sharing')->findAllowedSites($currentSiteId);
        foreach ($mediaLibrariesSharing as $mediaLibrarySharing) {
            $siteIdsAllowedShare[] = $mediaLibrarySharing->getSiteId();
        }
        $siteAllowedShare = $this->get('open_orchestra_model.repository.site')->findBySiteIds($siteIdsAllowedShare);

        $facade = $this->get('open_orchestra_api.transformer_manager')->transform('site_collection', $siteAllowedShare);

        return $facade;
    }
1294829
private function wizardSteps()
    {
        $checkLocale = function ($localeId) {
            $result = false;
            $chunks = \Punic\Data::explodeLocale($localeId);
            // Check that $localeId is well formatted
            if ($chunks !== null) {
                $normalizedLocaleId = ($chunks['territory'] === '') ? $chunks['language'] : "{$chunks['language']}_{$chunks['territory']}";
                // We don't support custom Scripts, check that the separator is "_", check language/territory lower/upper case
                if ($localeId === $normalizedLocaleId) {
                    // Check that the language ID is valid
                    if (\Punic\Language::getName($chunks['language']) !== $chunks['language']) {
                        // Check that the territory ID is valid (or absent)
                        if ($chunks['territory'] === '' || \Punic\Territory::getName($chunks['territory']) !== $chunks['territory']) {
                            $result = true;
                        }
                    }
                }
            }

            return $result;
        };

        return [
            ['db-server', '127.0.0.1'],
            'db-database',
            function (InputInterface $input, OutputInterface $output) {
                if (!trim($input->getOption('db-database'))) {
                    $output->writeln(sprintf('<error>%s</error>', 'A database name is required.'));

                    return 'db-database';
                }

                return true;
            },
            'db-username',
            [
                'db-password',
                function (Question $question, InputInterface $input) {
                    return $question->setHidden(true);
                },
            ],
            'timezone',
            function (InputInterface $input, OutputInterface $output) {
                $timezone = trim($input->getOption('timezone'));
                if ($timezone === '') {
                    $output->writeln(sprintf('<error>%s</error>', 'A time zone identifier is required.'));

                    return 'timezone';
                }
                try {
                    new DateTimeZone($timezone);
                } catch (Exception $x) {
                    $output->writeln(sprintf('<error>%s</error>', 'Invalid time zone identifier.'));

                    return 'timezone';
                }

                return true;
            },
            ['site', 'concrete5'],
            'canonical-url',
            'canonical-url-alternative',
            [
                'starting-point',
                'elemental_blank',
                function (Question $question, InputInterface $input) {
                    return new ChoiceQuestion($question->getQuestion(), ['elemental_blank', 'elemental_full'],
                        $question->getDefault());
                },
            ],
            'admin-email',
            [
                'admin-password',
                function (Question $question, InputInterface $input) {
                    return $question->setHidden(true);
                },
            ],
            // Test the password
            function (InputInterface $input, OutputInterface $output) {
                $answer = $input->getOption('admin-password');
                $error = new \ArrayObject();
                Application::getFacadeApplication()->make('validator/password')->isValid($answer, $error);

                if (count($error)) {
                    foreach ($error->getIterator() as $message) {
                        $output->writeln(sprintf('<error>%s</error>', $message));
                    }

                    // Set the option to an empty string so that we don't output the password
                    $input->setOption('admin-password', '');

                    return 'admin-password';
                }

                return true;
            },
            'demo-username',
            'demo-email',
            [
                'demo-password',
                function (Question $question, InputInterface $input) {
                    return $question->setHidden(true);
                },
            ],
            ['language', Localization::BASE_LOCALE],
            // Test the language
            function (InputInterface $input, OutputInterface $output) use ($checkLocale) {
                $code = $input->getOption('language');
                if ($checkLocale($code) !== true) {
                    $output->writeln(sprintf('<error>%s</error>', sprintf("The language code '%s' is not valid.", $code)));

                    return 'language';
                }

                return true;
            },
            [
                'site-locale',
                function (Question $question, InputInterface $input, InputOption $option) {
                    return $question;
                },
                function (InputInterface $input) {
                    return $input->getOption('site-locale') ?: $input->getOption('language') ?: Localization::BASE_LOCALE;
                },
            ],
            // Test the site locale
            function (InputInterface $input, OutputInterface $output) use ($checkLocale) {
                $code = $input->getOption('site-locale');
                if ($checkLocale($code) !== true) {
                    $output->writeln(sprintf('<error>%s</error>', sprintf("The language code '%s' is not valid.", $code)));

                    return 'site-locale';
                }

                return true;
            },
            ['config', 'none'],
        ];
    }
713100
public static function collectAllInformation()
    {
        /**
         * @var Container $container
         * @var Collector $collector
         * @var Profiler  $profiler
         */
        $container = Ioc::factory();
        $collector = $container->get('debugger.collector');
        $profiler  = $container->get('profiler');

        // Packages
        $packages = PackageHelper::getPackages();
        $pkgs     = [];

        foreach ($packages as $package) {
            $pkgs[$package->getName()] = $package->getDir();
        }

        // Windwalker Information
        $collector['windwalker.version.framework'] = ComposerInformation::getInstalledVersion('windwalker/framework');
        $collector['windwalker.version.core']      = ComposerInformation::getInstalledVersion('windwalker/core');
        $collector['windwalker.config']            = Ioc::getConfig()->toArray();

        // PHP
        $collector['system.php.version']    = PHP_VERSION;
        $collector['system.php.extensions'] = get_loaded_extensions();

        // Load all inputs
        $collector['request'] = Ioc::getInput()->dumpAllInputs();

        // SQL Explain
        if (Ioc::exists('database')) {
            $queries = $collector['database.queries'];
            $db      = Ioc::getDatabase();

            if ($db->getName() === 'mysql') {
                foreach ($queries as $k => $data) {
                    if (stripos(trim($data['query']), 'SELECT') !== 0) {
                        continue;
                    }

                    $query = $db->getQuery(true);
                    $query->setQuery('EXPLAIN ' . $data['query']);

                    if (!empty($data['bounded'])) {
                        foreach ((array) $data['bounded'] as $key => $bind) {
                            $bind = (object) $bind;
                            $query->bind($key, $bind->value, $bind->dataType, $bind->length, $bind->driverOptions);
                        }
                    }

                    $collector['database.queries.' . $k . '.explain'] = $db->prepare($query)->loadAll();
                }
            }

            // Database Information
            $collector['database.driver.name']  = $db->getName();
            $collector['database.driver.class'] = get_class($db);
            $collector['database.info']         = $db->getOptions();

            if ($queries instanceof DataSet) {
                $collector['database.queries'] = iterator_to_array($queries);
            }
        }

        // Events
        /** @var EventDispatcher $dispatcher */
        $dispatcher = $container->get('dispatcher');

        $collector['event.executed'] = $dispatcher->getCollector();

        $listenersMapping = [];

        foreach ($dispatcher->getListeners() as $eventName => $listeners) {
            $listenersMapping[$eventName] = [];

            foreach ($listeners as $listener) {
                if ($listener instanceof \Closure) {
                    continue;
                }

                if (is_object($listener)) {
                    $listener = [get_class($listener), $eventName];
                }

                $listenersMapping[$eventName][] = $listener;
            }
        }

        $collector['event.listeners'] = $listenersMapping;

        // Headers
        $collector['system.http.status']  = $collector['exception'] ? $collector['exception']['code'] : http_response_code();
        $collector['system.http.headers'] = headers_list();
    }
316517
def blockmix_salsa8(BY, Yi, r):
    """"""

    start = (2 * r - 1) * 16
    X = BY[start:start+16]                             # BlockMix - 1
    tmp = [0]*16

    for i in xrange(2 * r):                            # BlockMix - 2
        #blockxor(BY, i * 16, X, 0, 16)                # BlockMix - 3(inner)
        salsa20_8(X, tmp, BY, i * 16, BY, Yi + i*16)   # BlockMix - 3(outer)
        #array_overwrite(X, 0, BY, Yi + (i * 16), 16)  # BlockMix - 4

    for i in xrange(r):                                # BlockMix - 6
        BY[i * 16:(i * 16)+(16)] = BY[Yi + (i * 2) * 16:(Yi + (i * 2) * 16)+(16)]
        BY[(i + r) * 16:((i + r) * 16)+(16)] = BY[Yi + (i*2 + 1) * 16:(Yi + (i*2 + 1) * 16)+(16)]
448543
public function getKkTrixionarySkillVersions()
    {
        if (null === $this->kk_trixionary_skill_versions_unserialized) {
            $this->kk_trixionary_skill_versions_unserialized = array();
        }
        if (!$this->kk_trixionary_skill_versions_unserialized && null !== $this->kk_trixionary_skill_versions) {
            $kk_trixionary_skill_versions_unserialized = substr($this->kk_trixionary_skill_versions, 2, -2);
            $this->kk_trixionary_skill_versions_unserialized = $kk_trixionary_skill_versions_unserialized ? explode(' | ', $kk_trixionary_skill_versions_unserialized) : array();
        }

        return $this->kk_trixionary_skill_versions_unserialized;
    }
457862
public function index() {
        $controllers = App::objects('Controller');
        $sitemap = array();

        // Fetch sitemap data
        foreach ($controllers as $controller) {
            App::uses($controller, 'Controller');

            // Don't load AppController's, SitemapController or Controller's who can't be found
            if (strpos($controller, 'AppController') !== false || $controller === 'SitemapController' || !App::load($controller)) {
                continue;
            }

            $instance = new $controller($this->request, $this->response);
            $instance->constructClasses();

            if (method_exists($instance, '_generateSitemap')) {
                if ($data = $instance->_generateSitemap()) {
                    $sitemap = array_merge($sitemap, $data);
                }
            }
        }

        // Cleanup sitemap
        if ($sitemap) {
            foreach ($sitemap as &$item) {
                if (is_array($item['loc'])) {
                    if (!isset($item['loc']['plugin'])) {
                        $item['loc']['plugin'] = false;
                    }

                    $item['loc'] = h(Router::url($item['loc'], true));
                }

                if (array_key_exists('lastmod', $item)) {
                    if (!$item['lastmod']) {
                        unset($item['lastmod']);
                    } else {
                        $item['lastmod'] = CakeTime::format(DateTime::W3C, $item['lastmod']);
                    }
                }
            }
        }

        // Disable direct linking
        if (empty($this->request->params['ext'])) {
            throw new NotFoundException();
        }

        // Render view and don't use specific view engines
        $this->RequestHandler->respondAs($this->request->params['ext']);

        $this->set('sitemap', $sitemap);
    }
616597
public static function create($key, $iv)
	{
		if (strlen($key) != self::KEY_LEN || strlen($iv) != self::IV_LEN)
			return null;
		return new Salsa20Stream($key, $iv);
	}
1225541
public function getAPI()
    {
        if (!isset($this->_api)) {
            $session = AnRequest::get('session.oauth', 'raw', array());
            $session = new AnConfig($session);
            $api = pick($this->getRequest()->server, $session->api);

            if (!$api) {
                return;
            }

            //get the api server from the request
            $this->_api = $this->getService('com:connect.oauth.service.'.$api);

            if (!$this->_consumer) {
                $name = $this->_api->getName();
                $key = get_config_value('com_connect.'.$name.'_key');
                $secret = get_config_value('com_connect.'.$name.'_secret');
                $query = array(
                    'option=com_'.$this->_mixer->getIdentifier()->package,
                     'view='.$this->_mixer->getIdentifier()->name,
                     'server='.$this->server,
                     'get=accesstoken',
                );

                // if ($this->oid) {
                //    $query[] = 'oid='.$this->oid;
                // }

                $callback = route(implode($query, '&'), true);

                $this->_consumer = new ComConnectOauthConsumer(new AnConfig(array(
                    'key' => $key,
                    'secret' => $secret,
                    'callback_url' => (string) $callback,
                )));
            }

            //set the consumer
            $this->_api->setConsumer($this->_consumer);
            $this->_api->setToken($session->token);
        }

        return $this->_api;
    }
528166
private function step0()
    {
        // Search for the longest among the following suffixes
        if ( ($position = $this->search(array(
            'gliela', 'gliele', 'glieli', 'glielo', 'gliene',
            'sene', 'mela', 'mele', 'meli', 'melo', 'mene', 'tela', 'tele', 'teli', 'telo', 'tene', 'cela',
            'cele', 'celi', 'celo', 'cene', 'vela', 'vele', 'veli', 'velo', 'vene',
            'gli', 'la', 'le', 'li', 'lo', 'mi', 'ne', 'si', 'ti', 'vi', 'ci'))) !== false) {

            $suffixe = Utf8::substr($this->word, $position);

            // following one of (in RV)
             // a
            $a = array('ando', 'endo');
            $a = array_map(function($item) use ($suffixe) {
                return $item . $suffixe;
            }, $a);
            // In case of (a) the suffix is deleted
            if ($this->searchIfInRv($a) !== false) {
                $this->word = Utf8::substr($this->word, 0, $position);
            }

            //b
            $b = array('ar', 'er', 'ir');
            $b = array_map(function($item) use ($suffixe) {
                return $item . $suffixe;
            }, $b);
            // in case (b) it is replace by e
            if ($this->searchIfInRv($b) !== false) {
                $this->word = preg_replace('#('.$suffixe.')$#u', 'e', $this->word);
            }

            return true;
        }

        return false;
    }
687065
public function main()
    {
        $options = (array)$this->params;
        $options['bundle'] = empty($options['bundle']) ? null : $options['bundle'];

        if (empty($options['use'])) {
            $this->err(__d('eav', 'You must indicate a table alias name using the "--use" option. Example: "Articles.Users"'));

            return false;
        }

        try {
            $table = TableRegistry::get($options['use']);
        } catch (\Exception $ex) {
            $table = false;
        }

        if (!$table) {
            $this->err(__d('eav', 'The specified table does not exists.'));

            return false;
        } elseif (!$table->behaviors()->has('Eav')) {
            $this->err(__d('eav', 'The specified table is not using EAV behavior.'));

            return false;
        }

        $columns = $table->listColumns($options['bundle']);
        ksort($columns, SORT_LOCALE_STRING);
        $rows = [
            [
                __d('eav', 'Column Name'),
                __d('eav', 'Data Type'),
                __d('eav', 'Bundle'),
                __d('eav', 'Searchable'),
            ]
        ];

        foreach ($columns as $name => $info) {
            $rows[] = [
                $name,
                $info['type'],
                (!empty($info['bundle']) ? $info['bundle'] : '---'),
                (!empty($info['searchable']) ? 'no' : 'yes'),
            ];
        }

        $this->out();
        $this->out(__d('eav', 'EAV information for table "{0}":', $options['use']));
        $this->out();
        $this->helper('table')->output($rows);

        return true;
    }
317091
public function index() {
		
		if (!Auth::check()) return LoginController::getIndex();

		# Trail
		Trail::clear();
		
		$tables = array_where(config('center.tables'), function($key, $value) {
		    return !$value->hidden;
		});
		$groups = $objects = [];
		foreach ($tables as $table) {
			$latest = DB::table($table->name)
				->leftJoin(config('center.db.users') . ' as u2', $table->name . '.updated_by', '=', 'u2.id')
				->select('u2.name as updated_name', $table->name . '.updated_at')
				->orderBy($table->name . '.updated_at', 'desc')
				->first();
			if (!isset($groups[$table->list_grouping])) $groups[$table->list_grouping] = [];
			$groups[$table->list_grouping][] = (object) [
				'title' => $table->title,
				'list_grouping' => $table->list_grouping,
				'link' => action('\LeftRight\Center\Controllers\RowController@index', $table->name),
				'updated_name' => isset($latest->updated_name) ? $latest->updated_name : '',
				'updated_at' => isset($latest->updated_at) ? $latest->updated_at : '',
				'count' => number_format(DB::table($table->name)->count()),
			];
		}
		foreach ($groups as $group) $objects = array_merge($objects, $group);
		
		$table = new Table;
		$table->rows($objects);
		$table->column('title', 'string', trans('center::site.table'));
		$table->column('count', 'integer', trans('center::site.count'));
		$table->column('updated_name', 'updated_name', trans('center::site.updated_name'));
		$table->column('updated_at', 'updated_at', trans('center::site.updated_at'));
		$table->groupBy('list_grouping');
		$table = $table->draw('tables');
		
		
		return view('center::tables.index', compact('table'));
	}