text:
<?php

namespace Composer\Package\Loader;

use Composer\Package\BasePackage;
use Composer\Package\AliasPackage;
use Composer\Config;
use Composer\Factory;
use Composer\Package\Version\VersionParser;
use Composer\Repository\RepositoryManager;
use Composer\Repository\Vcs\HgDriver;
use Composer\IO\NullIO;
use Composer\Util\ProcessExecutor;
use Composer\Util\Git as GitUtil;
use Composer\Util\Svn as SvnUtil;

/**
 * ArrayLoader built for the sole purpose of loading the root package
 *
 * Sets additional defaults and loads repositories
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class RootPackageLoader extends ArrayLoader
{
    private $manager;
    private $config;
    private $process;

    public function __construct(RepositoryManager $manager, Config $config, VersionParser $parser = null, ProcessExecutor $process = null)
    {
        $this->manager = $manager;
        $this->config = $config;
        $this->process = $process ?: new ProcessExecutor();
        parent::__construct($parser);
    }

    public function load(array $config, $class = 'Composer\Package\RootPackage')
    {
        if (!isset($config['name'])) {
            $config['name'] = '__root__';
        }
        if (!isset($config['version'])) {
            // override with env var if available
            if (getenv('COMPOSER_ROOT_VERSION')) {
                $version = getenv('COMPOSER_ROOT_VERSION');
            } else {
                $version = $this->guessVersion($config);
            }

            if (!$version) {
                $version = '1.0.0';
            }

            $config['version'] = $version;
        }

        $realPackage = $package = parent::load($config, $class);

        if ($realPackage instanceof AliasPackage) {
            $realPackage = $package->getAliasOf();
        }

        if (isset($config['minimum-stability'])) {
            $realPackage->setMinimumStability(VersionParser::normalizeStability($config['minimum-stability']));
        }

        $aliases = array();
        $stabilityFlags = array();
        $references = array();
        foreach (array('require', 'require-dev') as $linkType) {
            if (isset($config[$linkType])) {
                $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
                $method = 'get'.ucfirst($linkInfo['method']);
                $links = array();
                foreach ($realPackage->$method() as $link) {
                    $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
                }
                $aliases = $this->extractAliases($links, $aliases);
                $stabilityFlags = $this->extractStabilityFlags($links, $stabilityFlags, $realPackage->getMinimumStability());
                $references = $this->extractReferences($links, $references);
            }
        }

        $realPackage->setAliases($aliases);
        $realPackage->setStabilityFlags($stabilityFlags);
        $realPackage->setReferences($references);

        if (isset($config['prefer-stable'])) {
            $realPackage->setPreferStable((bool) $config['prefer-stable']);
        }

        $repos = Factory::createDefaultRepositories(null, $this->config, $this->manager);
        foreach ($repos as $repo) {
            $this->manager->addRepository($repo);
        }
        $realPackage->setRepositories($this->config->getRepositories());

        return $package;
    }

    private function extractAliases(array $requires, array $aliases)
    {
        foreach ($requires as $reqName => $reqVersion) {
            if (preg_match('{^([^,\s#]+)(?:#[^ ]+)? +as +([^,\s]+)$}', $reqVersion, $match)) {
                $aliases[] = array(
                    'package' => strtolower($reqName),
                    'version' => $this->versionParser->normalize($match[1], $reqVersion),
                    'alias' => $match[2],
                    'alias_normalized' => $this->versionParser->normalize($match[2], $reqVersion),
                );
            }
        }

        return $aliases;
    }

    private function extractStabilityFlags(array $requires, array $stabilityFlags, $minimumStability)
    {
        $stabilities = BasePackage::$stabilities;
        $minimumStability = $stabilities[$minimumStability];
        foreach ($requires as $reqName => $reqVersion) {
            // parse explicit stability flags to the most unstable
            if (preg_match('{^[^,\s]*?@('.implode('|', array_keys($stabilities)).')$}i', $reqVersion, $match)) {
                $name = strtolower($reqName);
                $stability = $stabilities[VersionParser::normalizeStability($match[1])];

                if (isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) {
                    continue;
                }
                $stabilityFlags[$name] = $stability;

                continue;
            }

            // infer flags for requirements that have an explicit -dev or -beta version specified but only
            // for those that are more unstable than the minimumStability or existing flags
            $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
            if (preg_match('{^[^,\s@]+$}', $reqVersion) && 'stable' !== ($stabilityName = VersionParser::parseStability($reqVersion))) {
                $name = strtolower($reqName);
                $stability = $stabilities[$stabilityName];
                if ((isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) || ($minimumStability > $stability)) {
                    continue;
                }
                $stabilityFlags[$name] = $stability;
            }
        }

        return $stabilityFlags;
    }

    private function extractReferences(array $requires, array $references)
    {
        foreach ($requires as $reqName => $reqVersion) {
            $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
            if (preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) && 'dev' === ($stabilityName = VersionParser::parseStability($reqVersion))) {
                $name = strtolower($reqName);
                $references[$name] = $match[1];
            }
        }

        return $references;
    }

    private function guessVersion(array $config)
    {
        if (function_exists('proc_open')) {
            $version = $this->guessGitVersion($config);
            if (null !== $version) {
                return $version;
            }

            $version = $this->guessHgVersion($config);
            if (null !== $version) {
                return $version;
            }

            return $this->guessSvnVersion($config);
        }
    }

    private function guessGitVersion(array $config)
    {
        $util = new GitUtil;
        $util->cleanEnv();

        // try to fetch current version from git tags
        if (0 === $this->process->execute('git describe --exact-match --tags', $output)) {
            try {
                return $this->versionParser->normalize(trim($output));
            } catch (\Exception $e) {
            }
        }

        // try to fetch current version from git branch
        if (0 === $this->process->execute('git branch --no-color --no-abbrev -v', $output)) {
            $branches = array();
            $isFeatureBranch = false;
            $version = null;

            // find current branch and collect all branch names
            foreach ($this->process->splitLines($output) as $branch) {
                if ($branch && preg_match('{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
                    if ($match[1] === '(no branch)' || substr($match[1], 0, 10) === '(detached ') {
                        $version = 'dev-'.$match[2];
                        $isFeatureBranch = true;
                    } else {
                        $version = $this->versionParser->normalizeBranch($match[1]);
                        $isFeatureBranch = 0 === strpos($version, 'dev-');
                        if ('9999999-dev' === $version) {
                            $version = 'dev-'.$match[1];
                        }
                    }
                }

                if ($branch && !preg_match('{^ *[^/]+/HEAD }', $branch)) {
                    if (preg_match('{^(?:\* )? *(\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
                        $branches[] = $match[1];
                    }
                }
            }

            if (!$isFeatureBranch) {
                return $version;
            }

            // try to find the best (nearest) version branch to assume this feature's version
            $version = $this->guessFeatureVersion($config, $version, $branches, 'git rev-list %candidate%..%branch%');

            return $version;
        }
    }

    private function guessHgVersion(array $config)
    {
        // try to fetch current version from hg branch
        if (0 === $this->process->execute('hg branch', $output)) {
            $branch = trim($output);
            $version = $this->versionParser->normalizeBranch($branch);
            $isFeatureBranch = 0 === strpos($version, 'dev-');

            if ('9999999-dev' === $version) {
                $version = 'dev-'.$branch;
            }

            if (!$isFeatureBranch) {
                return $version;
            }

            // re-use the HgDriver to fetch branches (this properly includes bookmarks)
            $config = array('url' => getcwd());
            $driver = new HgDriver($config, new NullIO(), $this->config, $this->process);
            $branches = array_keys($driver->getBranches());

            // try to find the best (nearest) version branch to assume this feature's version
            $version = $this->guessFeatureVersion($config, $version, $branches, 'hg log -r "not ancestors(\'%candidate%\') and ancestors(\'%branch%\')" --template "{node}\\n"');

            return $version;
        }
    }

    private function guessFeatureVersion(array $config, $version, array $branches, $scmCmdline)
    {
        // ignore feature branches if they have no branch-alias or self.version is used
        // and find the branch they came from to use as a version instead
        if ((isset($config['extra']['branch-alias']) && !isset($config['extra']['branch-alias'][$version]))
            || strpos(json_encode($config), '"self.version"')
        ) {
            $branch = preg_replace('{^dev-}', '', $version);
            $length = PHP_INT_MAX;
            foreach ($branches as $candidate) {
                // do not compare against other feature branches
                if ($candidate === $branch || !preg_match('{^(master|trunk|default|develop|\d+\..+)$}', $candidate, $match)) {
                    continue;
                }

                $cmdLine = str_replace(array('%candidate%', '%branch%'), array($candidate, $branch), $scmCmdline);
                if (0 !== $this->process->execute($cmdLine, $output)) {
                    continue;
                }

                if (strlen($output) < $length) {
                    $length = strlen($output);
                    $version = $this->versionParser->normalizeBranch($candidate);
                    if ('9999999-dev' === $version) {
                        $version = 'dev-'.$match[1];
                    }
                }
            }
        }

        return $version;
    }

    private function guessSvnVersion(array $config)
    {
        SvnUtil::cleanEnv();

        // try to fetch current version from svn
        if (0 === $this->process->execute('svn info --xml', $output)) {
            $trunkPath = isset($config['trunk-path']) ? preg_quote($config['trunk-path'], '#') : 'trunk';
            $branchesPath = isset($config['branches-path']) ? preg_quote($config['branches-path'], '#') : 'branches';
            $tagsPath = isset($config['tags-path']) ? preg_quote($config['tags-path'], '#') : 'tags';

            $urlPattern = '#<url>.*/('.$trunkPath.'|('.$branchesPath.'|'. $tagsPath .')/(.*))</url>#';

            if (preg_match($urlPattern, $output, $matches)) {
                if (isset($matches[2]) && ($branchesPath === $matches[2] || $tagsPath === $matches[2])) {
                    // we are in a branches path
                    $version = $this->versionParser->normalizeBranch($matches[3]);
                    if ('9999999-dev' === $version) {
                        $version = 'dev-'.$matches[3];
                    }
                    return $version;
                }

                return $this->versionParser->normalize(trim($matches[1]));
            }
        }
    }
}


text:
<?php

namespace backend\controllers;

use Yii;
use common\models\Categories;
use common\models\Articles;
use backend\models\ArticlesSearch;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;

/**
 * ArticlesController implements the CRUD actions for Articles model.
 */
class ArticlesController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Articles of a category.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = $this->getSearchModel();
        $request = \Yii::$app->request;

        $currentCategory = Categories::findOne(['uri' => $request->get('uri')]);
        $dataProvider = $searchModel->search($request->queryParams, $currentCategory->id);

        return $this->render('index', [
            'currentCategoryName' => $currentCategory->name,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Articles model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Articles model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = $this->getModel();

        $date = date('Y-m-d');
        $model->created = $date;
        $model->updated = $date;

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->setMainImage($model);
            return $this->redirect(['view', 'uri' => $model->category->uri,'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
            'items' => $this->getItems(),
        ]);
    }

    /**
     * Updates an existing Articles model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $model->updated = date('Y-m-d');

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $this->setMainImage($model);
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
            'items' => $this->getItems(),
        ]);
    }

    /**
     * Deletes an existing Articles model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $uri = $model->category->uri;

        $msg = ($model->delete())
            ? ['name' => 'deleteArticleSuccessful', 'type' => 'success']
            : ['name' => 'deleteArticleFailure', 'type' => 'error'];

        \Yii::$app->session->setFlash($msg['name'], $msg['type']);

        return $this->redirect(['/articles?uri=' . $uri]);
    }

    /**
     * Set main image for an article
     * @param mixed $model
     * @return mixed
     */
    private function setMainImage($model)
    {
        if (!$model->image = UploadedFile::getInstance($model, 'image')) return false;

        $path = \Yii::getAlias('@images') . $model->image->baseName . '.' . $model->image->extension;
        $model->image->saveAs($path);

        return $model->attachImage($path, true);
    }

    /**
     * Group data for Html::activeDropDownList method
     * @return array
     */
    private function getItems()
    {
        return [
            'categories' => ArrayHelper::map(Categories::find()->all(), 'id', 'name'),
            'article_status' => [10 => 'Опубліковано', 0 => 'Прихована стаття'],
            'comments_status' => [10 => 'Дозволені', 0 => 'Заборонені'],
        ];
    }

    /**
     * Finds the CommentsSearch model.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @return ArticlesSearch the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function getSearchModel()
    {
        if (($model = new ArticlesSearch()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('Сторінки, яку Ви шукаєте не існує.');
        }
    }

    /**
     * Finds the Comments model.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @return Articles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function getModel()
    {
        if (($model = new Articles()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('Сторінки, яку Ви шукаєте не існує.');
        }
    }

    /**
     * Finds the Articles model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Articles the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Articles::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('Сторінки, яку Ви шукаєте не існує.');
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>C++ command line parameters parser: User's guide</title>
<link href="own.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Related Pages

Namespaces

Data Structures

Files

User's guide
Contents:

Introduction

Value or not value?

Necessity

Default value

Error reports

Common usage

Preparing

Defining command line parameter

Register of functions-members

Parsing

Supported types of user's function argument

Advanced usage

Define parameter's necessity

Define parameter's default value

Parameter's value type check

Parameter's value semantic check

Combine of settings

Another 'name-value' separator

Unnamed parameters

Introduction

Factually, using CLPP library add up to only two tasks:

registration set of parameters, with definition all required checkings and characteristics,

parsing inputed parameter(s), with defined check(s) and calls of corresponding functions.

Value or not value?

Command line parameter can be with or without value.

Example of parameter without value:

 # ./program --help

 Parameter '--help' is useful of its own accord, it not need any value.

Example of parameter with value:

 # ./program --log-dir=/some/path

 Parameter '--log-dir', in contrast, useless without value.

Necessity

Command line parameter can be necessary or optionally.

In examples above parameter '--help' is optionally, because it may missing (only in cases where user want to see help info, he input '--help').

But parameter '--log-dir' may be necessary, in this case user must input it.

Default value

Command line parameter can have default value, in this case not required input it. This option can be useful for parameters with predefined default values.

In example above parameter '--log-dir' may have default value of path, so user can skip it.

Error reports

All reports about errors begins with [CLPP] prefix, for example:

 [CLPP] You inputs 3 parameters, but only 2 registered!

Common usage

This section describes common usage of CLPP.

Preparing

Copy 'clpp' folder in some place where your compiler is looking for header files and add:

 #include <clpp/parser.hpp>

in your program.

For simplicity, you can also add:

 using namespace clpp;

Note: In old versions of library used namespace clp_parser, but backward compatibility is maintained.

Defining command line parameter

Registration of new parameter included three tasks:

define parameter's name (short and full names, or single name),

define function that will be called if corresponding parameter will be inputed,

define checks and default value for parameter (optionally).

Use clpp::command_line_parameters_parser::add_parameter() function for it.

 void help() { /* some info */ }
 void config() { /* some config info */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     // Register parameter with two names (in Unix-style) and 'help()' function.
     parser.add_parameter( "-h", "--help", help );
     // Register parameter with single name and 'config()' function.
     parser.add_parameter( "--config", config );
     // ...
 }

Register of functions-members

You can register not only global functions, but also functions-members.

 struct some_parameters_storage {
     void some_path( const std::string& path ) { /* Some work with path... */ }
     void some_num( double number ) { /* Some work with number... */ }
 }

 int main( int argc, char* argv[] ) {
     some_parameters_storage storage;

     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-f", "--file", &storage, &some_parameters_storage::some_path );
     parser.add_parameter( "-n", "--number", &storage, &some_parameters_storage::some_num );
     // ...
 }

Parsing

For parsing use clpp::command_line_parameters_parser::parse() function.

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     // ...
     try {
         parser.parse( argc, argv );
     } catch ( const std::exception& exc ) {
         std::cerr << exc.what() << std::endl;
     }
     // ...
 }

This function parse all inputed command line parameters, checks correctness and calls corresponding functions.

Supported types of user's function argument

When you register parameter with value, you can use follow types of function's argument:

almost all standard C++-types (see below),

std::string.

You CANNOT use const char* and wchar_t argument. But this limitation, in my humble opinion, is not the real problem.

You can pass argument by value, like this:

 void f( int i ) { /* some work... */ }

 or by const reference:

 void f( const std::string& path ) { /* some work... */ }

Passing by non-const reference is NOT supported (I think this is completely unnecessary).

Advanced usage

This section describes advanced usage of CLPP.

Define parameter's necessity

For define parameter's necessity use clpp::parameter::necessary() function:

 void config( const std::string& path ) { /* some config info */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-c", "--config", config )
           .necessary();
     // ...
 }

 After that user must inputs this parameter in command line.

Define parameter's default value

For set parameter's default value use clpp::parameter::default_value() function:

 void config( const std::string& path ) { /* some config info */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-c", "--config", config )
           .default_value( "/some/default/path" );
     // ...
 }

 After that user can skip this parameter in command line.

Parameter's value type check

Since 1.0rc version value's type checks automatically. If you register callback function

 void some_num( double num ) { /* some work... */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-n", "--number", some_num );
     // ...
 }

 so number's value must be 'double' type.

Note: if you want use function with 'float' argument, like this:

 void some_num( float num ) { /* some work... */ }

 AND use 'default_value()' function, you must indicate exactly 'float' type, like this:

     // ...
     parser.add_parameter( "-n", "--number", some_num )
           .default_value( 12.56f )
           ;
     // ...

 or like this:

     // ...
     parser.add_parameter( "-n", "--number", some_num )
           .default_value( float( 12.56 ) )
           ;
     // ...

Parameter's value semantic check

Use clpp::parameter::check_semantic() function.

 void log_dir( const std::string& path_to_log ) { /* some work... */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-l", "--log-dir", log_dir )
           .check_semantic( clpp::path );
     // ...
 }

In this case, value of '--log-dir' must be valid path in current filesystem.

Supported value's semantic:

path (check of path correctness, in current filesystem),

ipv4 (check of IP-address validity, exactly IPv4),

ipv6 (check of IP-address validity, exactly IPv6),

ip (check of IP-address validity, IPv4 or IPv6).

email (check of E-mail validity).

Combine of settings

Of course, you can combine settings for one parameter, like this:

 void log_dir( const std::string& path_to_log ) { /* some work... */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-l", "--log-dir", log_dir )
           .default_value( "/some/default/path" )
           .check_semantic( clpp::path )
           ;
     // ...
 }

Note: You cannot combine contradictory settings. For example, if you write like this:

 void log_dir( const std::string& path_to_log ) { /* some work... */ }

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-l", "--log-dir", log_dir )
           .default_value( "/some/default/path" )
           .check_semantic( clpp::path )
           .necessary() // Necessary parameter with defined default value?? Hmm...
           ;
     // ...
 }

exception will throw.

Another 'name-value' separator

You can define another 'name-value' separator, instead default '='.

Use clpp::command_line_parameters_parser::set_value_separator() function.

 int main( int argc, char* argv[] ) {
     clpp::command_line_parameters_parser parser;
     parser.set_value_separator( ':' );
     // ...
 }

In this case, parameters with value must be input in command line like this:

 # ./program --log-dir:/some/path

Note: You CANNOT use characters with ASCII-code less than 0x21. They are unsuitable candidates for the separator role. :-)

Unnamed parameters

Sometimes you may want to use some parameters without explicitly inputed names.

For example, if you develop network program with console-defined host and port, you can use it like this:

 # ./program --host=127.0.0.1 --port=80

but you probably want to use it easier:

 # ./program 127.0.0.1 80

Use clpp::parameter::order() function.

This function sets order number for parameter, so in our example 'host' has order number 1, and 'port' has order number 2. Note that order number begins with 1, because it is not index, but exactly number.

Of course, order number cannot be negative.

So you must register these parameters like this:

 struct my_server {
     void host( const std::string& address ) { /* some work... */ }
     void port( unsigned int some_port ) { /* some work... */ }
 };

 int main( int argc, char* argv[] ) {
     my_server server;

     clpp::command_line_parameters_parser parser;
     parser.add_parameter( "-h", "--host", &server, &my_server::host )
           .order( 1 )
           ;
     parser.add_parameter( "-p", "--port", &server, &my_server::port )
           .order( 2 )
           ;
     // ...
 }

Now you can use it like this:

 # ./program 127.0.0.1 80

but not vice versa:

 # ./program 80 127.0.0.1

because in this case my_server::port() function get string-argument, and exception will throw.

Remember that order numbers must be unique:

     // ...
     parser.add_parameter( "-h", "--host", &server, &my_server::host )
           .order( 1 )
           ;
     parser.add_parameter( "-p", "--port", &server, &my_server::port )
           .order( 1 ) // You inputed already used order?? Hmm...
           ;
     // ...

Of course, you can use "ordered" parameters with names, in any combination:

 # ./program -h=127.0.0.1 --port=80

 # ./program 127.0.0.1 -p=80

<address style="text-align: right;">Generated on Thu Oct 28 17:45:49 2010 for C++ command line parameters parser by

 1.5.6 </address>


text:
title:  InfoBlox
thumbnail: infoblox-logo.jpeg
comments: true
project-link: https://github.com/devblackops/InfoBlox
short-description: PowerShell module for interacting with InfoBlox IPAM via the REST API.
long-description:
---


text:
/**
 * Generic base class for CE views.
 *
 * @abstract
 * @extends OO.ui.Element
 * @mixins OO.EventEmitter
 *
 * @constructor
 * @param {ve.dm.Model} model Model to observe
 * @param {Object} [config] Configuration options
 */
ve.ce.View = function VeCeView( model, config ) {
	// Setting this property before calling the parent constructor allows overriden #getTagName
	// methods in view classes to have access to the model when they are called for the first time
	// inside of OO.ui.Element
	this.model = model;

	// Parent constructor
	OO.ui.Element.call( this, config );

	// Mixin constructors
	OO.EventEmitter.call( this );

	// Properties
	this.live = false;

	// Events
	this.connect( this, {
		setup: 'onSetup',
		teardown: 'onTeardown'
	} );

	// Initialization
	this.renderAttributes();
};

/* Inheritance */

OO.inheritClass( ve.ce.View, OO.ui.Element );

OO.mixinClass( ve.ce.View, OO.EventEmitter );

/* Events */

/**
 * @event setup
 */

/**
 * @event teardown
 */

/* Static members */

/**
 * Allowed attributes for DOM elements, in the same format as ve.dm.Model#storeHtmlAttributes
 *
 * This list includes attributes that are generally safe to include in HTML loaded from a
 * foreign source and displaying it inside the browser. It doesn't include any event attributes,
 * for instance, which would allow arbitrary JavaScript execution. This alone is not enough to
 * make HTML safe to display, but it helps.
 *
 * TODO: Rather than use a single global list, set these on a per-view basis to something that makes
 * sense for that view in particular.
 *
 * @static
 * @property {boolean|string|RegExp|Array|Object}
 * @inheritable
 */
ve.ce.View.static.renderHtmlAttributes = [
	'abbr', 'about', 'align', 'alt', 'axis', 'bgcolor', 'border', 'cellpadding', 'cellspacing',
	'char', 'charoff', 'cite', 'class', 'clear', 'color', 'colspan', 'datatype', 'datetime',
	'dir', 'face', 'frame', 'headers', 'height', 'href', 'id', 'itemid', 'itemprop', 'itemref',
	'itemscope', 'itemtype', 'lang', 'noshade', 'nowrap', 'property', 'rbspan', 'rel',
	'resource', 'rev', 'rowspan', 'rules', 'scope', 'size', 'span', 'src', 'start', 'style',
	'summary', 'title', 'type', 'typeof', 'valign', 'value', 'width'
];

/* Methods */

/**
 * Get an HTML document from the model, to use for URL resolution.
 *
 * The default implementation returns null; subclasses should override this if they can provide
 * a resolution document.
 *
 * @see #getResolvedAttribute
 * @returns {HTMLDocument|null} HTML document to use for resolution, or null if not available
 */
ve.ce.View.prototype.getModelHtmlDocument = function () {
	return null;
};

/**
 * Handle setup event.
 *
 * @method
 */
ve.ce.View.prototype.onSetup = function () {
	this.$element.data( 'view', this );
};

/**
 * Handle teardown event.
 *
 * @method
 */
ve.ce.View.prototype.onTeardown = function () {
	this.$element.removeData( 'view' );
};

/**
 * Get the model the view observes.
 *
 * @method
 * @returns {ve.dm.Model} Model the view observes
 */
ve.ce.View.prototype.getModel = function () {
	return this.model;
};

/**
 * Check if the view is attached to the live DOM.
 *
 * @method
 * @returns {boolean} View is attached to the live DOM
 */
ve.ce.View.prototype.isLive = function () {
	return this.live;
};

/**
 * Set live state.
 *
 * @method
 * @param {boolean} live The view has been attached to the live DOM (use false on detach)
 * @fires setup
 * @fires teardown
 */
ve.ce.View.prototype.setLive = function ( live ) {
	this.live = live;
	if ( this.live ) {
		this.emit( 'setup' );
	} else {
		this.emit( 'teardown' );
	}
};

/**
 * Render an HTML attribute list onto this.$element
 *
 * If no attributeList is given, the attribute list stored in the linear model will be used.
 *
 * @param {Object[]} [attributeList] HTML attribute list, see ve.dm.Converter#buildHtmlAttributeList
 */
ve.ce.View.prototype.renderAttributes = function ( attributeList ) {
	ve.dm.Converter.renderHtmlAttributeList(
		attributeList || this.model.getHtmlAttributes(),
		this.$element,
		this.constructor.static.renderHtmlAttributes,
		true // computed attributes
	);
};

/**
 * Get a resolved URL from a model attribute.
 *
 * @abstract
 * @method
 * @param {string} key Attribute name whose value is a URL
 * @returns {string} URL resolved according to the document's base
 */
ve.ce.View.prototype.getResolvedAttribute = function ( key ) {
	var plainValue = this.model.getAttribute( key ),
		doc = this.getModelHtmlDocument();
	return doc && typeof plainValue === 'string' ? ve.resolveUrl( plainValue, doc ) : plainValue;
};


text:
package org.fusesource.camel.component.sap.model.rfc;

import java.util.Map;
import org.eclipse.emf.common.util.EMap;
import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Repository Data'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.fusesource.camel.component.sap.model.rfc.RepositoryData#getEntries Entries}

 *
{@link org.fusesource.camel.component.sap.model.rfc.RepositoryData#getFunctionTemplates Function Templates}

 *

 *

 *
 * @see org.fusesource.camel.component.sap.model.rfc.RfcPackage#getRepositoryData()
 * @model
 * @generated
 */
public interface RepositoryData extends EObject {
	/**
	 * Returns the value of the 'Entries' map.
	 * The key is of type {@link java.lang.String},
	 * and the value is of type {@link org.fusesource.camel.component.sap.model.rfc.FunctionTemplate},
	 *
	 *

	 * If the meaning of the 'Entries' reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Entries' map.
	 * @see org.fusesource.camel.component.sap.model.rfc.RfcPackage#getRepositoryData_Entries()
	 * @model mapType="org.fusesource.camel.component.sap.model.rfc.RespositoryDataEntry<org.eclipse.emf.ecore.EString, org.fusesource.camel.component.sap.model.rfc.FunctionTemplate>"
	 * @generated
	 */
	EMap<String, FunctionTemplate> getEntries();

	/**
	 * Returns the value of the 'Function Templates' attribute.
	 *
	 *

	 * If the meaning of the 'Function Templates' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Function Templates' attribute.
	 * @see #setFunctionTemplates(Map)
	 * @see org.fusesource.camel.component.sap.model.rfc.RfcPackage#getRepositoryData_FunctionTemplates()
	 * @model dataType="org.fusesource.camel.component.sap.model.rfc.FunctionTemplateMap" transient="true" volatile="true" derived="true"
	 * @generated
	 */
	Map<String, FunctionTemplate> getFunctionTemplates();

	/**
	 * Sets the value of the '{@link org.fusesource.camel.component.sap.model.rfc.RepositoryData#getFunctionTemplates Function Templates}' attribute.
	 *
	 *
	 * @param value the new value of the 'Function Templates' attribute.
	 * @see #getFunctionTemplates()
	 * @generated
	 */
	void setFunctionTemplates(Map<String, FunctionTemplate> value);

} // RepositoryData


text:
package com.gs.collections.impl.multimap.bag.strategy;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import com.gs.collections.api.bag.MutableBag;
import com.gs.collections.api.block.HashingStrategy;
import com.gs.collections.api.block.function.Function;
import com.gs.collections.api.block.predicate.Predicate2;
import com.gs.collections.api.map.MutableMap;
import com.gs.collections.api.multimap.Multimap;
import com.gs.collections.api.multimap.bag.MutableBagMultimap;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.bag.mutable.HashBag;
import com.gs.collections.impl.map.strategy.mutable.UnifiedMapWithHashingStrategy;
import com.gs.collections.impl.multimap.bag.AbstractMutableBagMultimap;
import com.gs.collections.impl.utility.Iterate;

public final class HashBagMultimapWithHashingStrategy<K, V>
        extends AbstractMutableBagMultimap<K, V> implements Externalizable
{
    private static final long serialVersionUID = 1L;
    private HashingStrategy<? super K> hashingStrategy;

    /**
     * @deprecated Empty default constructor used for serialization. Instantiating an HashBagMultimapWithHashingStrategy with
     * this constructor will have a null multimapHashingStrategy, and throw NullPointerException when used.
     */
    @SuppressWarnings("UnusedDeclaration")
    @Deprecated
    public HashBagMultimapWithHashingStrategy()
    {
        // For Externalizable use only
    }

    public HashBagMultimapWithHashingStrategy(HashingStrategy<? super K> hashingStrategy)
    {
        this.hashingStrategy = hashingStrategy;
        this.map = this.createMap();
    }

    public HashBagMultimapWithHashingStrategy(HashBagMultimapWithHashingStrategy<K, V> multimap)
    {
        this(multimap.hashingStrategy, multimap);
    }

    public HashBagMultimapWithHashingStrategy(HashingStrategy<? super K> hashingStrategy, Multimap<? extends K, ? extends V> multimap)
    {
        this.hashingStrategy = hashingStrategy;
        this.map = this.createMapWithKeyCount(Math.max(multimap.sizeDistinct() * 2, 16));
        this.putAll(multimap);
    }

    public HashBagMultimapWithHashingStrategy(HashingStrategy<? super K> hashingStrategy, Pair<K, V>... pairs)
    {
        this(hashingStrategy);
        this.putAllPairs(pairs);
    }

    public HashBagMultimapWithHashingStrategy(HashingStrategy<? super K> hashingStrategy, Iterable<Pair<K, V>> inputIterable)
    {
        this(hashingStrategy);
        for (Pair<K, V> single : inputIterable)
        {
            this.add(single);
        }
    }

    public static <K, V> HashBagMultimapWithHashingStrategy<K, V> newMultimap(HashBagMultimapWithHashingStrategy<K, V> multimap)
    {
        return new HashBagMultimapWithHashingStrategy<K, V>(multimap);
    }

    public static <K, V> HashBagMultimapWithHashingStrategy<K, V> newMultimap(HashingStrategy<? super K> multimapHashingStrategy, Multimap<? extends K, ? extends V> multimap)
    {
        return new HashBagMultimapWithHashingStrategy<K, V>(multimapHashingStrategy, multimap);
    }

    public static <K, V> HashBagMultimapWithHashingStrategy<K, V> newMultimap(HashingStrategy<? super K> multimapHashingStrategy)
    {
        return new HashBagMultimapWithHashingStrategy<K, V>(multimapHashingStrategy);
    }

    @SafeVarargs
    public static <K, V> HashBagMultimapWithHashingStrategy<K, V> newMultimap(HashingStrategy<? super K> multimapHashingStrategy, Pair<K, V>... pairs)
    {
        return new HashBagMultimapWithHashingStrategy<K, V>(multimapHashingStrategy, pairs);
    }

    public static <K, V> HashBagMultimapWithHashingStrategy<K, V> newMultimap(HashingStrategy<? super K> multimapHashingStrategy, Iterable<Pair<K, V>> inputIterable)
    {
        return new HashBagMultimapWithHashingStrategy<K, V>(multimapHashingStrategy, inputIterable);
    }

    @Override
    protected MutableMap<K, MutableBag<V>> createMap()
    {
        return UnifiedMapWithHashingStrategy.newMap(this.hashingStrategy);
    }

    @Override
    protected MutableMap<K, MutableBag<V>> createMapWithKeyCount(int keyCount)
    {
        return UnifiedMapWithHashingStrategy.newMap(this.hashingStrategy, keyCount);
    }

    @Override
    protected MutableBag<V> createCollection()
    {
        return HashBag.newBag();
    }

    public HashingStrategy<? super K> getKeyHashingStrategy()
    {
        return this.hashingStrategy;
    }

    public HashBagMultimapWithHashingStrategy<K, V> newEmpty()
    {
        return new HashBagMultimapWithHashingStrategy<K, V>(this.hashingStrategy);
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeObject(this.hashingStrategy);
        super.writeExternal(out);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {
        this.hashingStrategy = (HashingStrategy<? super K>) in.readObject();
        super.readExternal(in);
    }

    // Currently this returns a HashBagMultimap.
    // On a future release, it will return HashBagWithHashingStrategyMultimap, where the HashBag collection hashing strategy
    // will be the hashing strategy of this multimap
    public MutableBagMultimap<V, K> flip()
    {
        return Iterate.flip(this);
    }

    public <V2> HashBagMultimapWithHashingStrategy<K, V2> collectValues(Function<? super V, ? extends V2> function)
    {
        return this.collectValues(function, HashBagMultimapWithHashingStrategy.<K, V2>newMultimap(this.hashingStrategy));
    }

    public HashBagMultimapWithHashingStrategy<K, V> selectKeysValues(Predicate2<? super K, ? super V> predicate)
    {
        return this.selectKeysValues(predicate, this.newEmpty());
    }

    public HashBagMultimapWithHashingStrategy<K, V> rejectKeysValues(Predicate2<? super K, ? super V> predicate)
    {
        return this.rejectKeysValues(predicate, this.newEmpty());
    }

    public HashBagMultimapWithHashingStrategy<K, V> selectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate)
    {
        return this.selectKeysMultiValues(predicate, this.newEmpty());
    }

    public HashBagMultimapWithHashingStrategy<K, V> rejectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate)
    {
        return this.rejectKeysMultiValues(predicate, this.newEmpty());
    }
}


text:
<?php

namespace Magento\ProductAlert\Controller\Unsubscribe;

use Magento\ProductAlert\Controller\Unsubscribe as UnsubscribeController;
use Magento\Framework\Controller\ResultFactory;

class PriceAll extends UnsubscribeController
{
    /**
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        try {
            $this->_objectManager->create('Magento\ProductAlert\Model\Price')
                ->deleteCustomer(
                    $this->customerSession->getCustomerId(),
                    $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')
                        ->getStore()
                        ->getWebsiteId()
                );
            $this->messageManager->addSuccess(__('You will no longer receive price alerts for this product.'));
        } catch (\Exception $e) {
            $this->messageManager->addException($e, __('Unable to update the alert subscription.'));
        }

        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        return $resultRedirect->setPath('customer/account/');
    }
}


text:
.. index:: Curvilinear array

.. include:: ScanConvertCurvilinearArray.rst

.. figure:: ScanConvertCurvilinearArray.png
  :alt: Curvilinear array scan conversion screenshot

  Screenshot of the ScanConvertCurvilinearArray module output. If there
  are multiple frames in the volume's third dimension, each frame is scan
  converted.

  This output can be reproduced by running the ``ScanConvertCurvilinearArrayTest``
  test in the project repository. Example input data can be found `here
  <http://slicer.kitware.com/midas3/folder/3646>`_.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/All-Tasks.iml" filepath="$PROJECT_DIR$/.idea/All-Tasks.iml" />
    </modules>
  </component>
</project>


text:
<component name="libraryTable">
  <library name="animated-vector-drawable-26.0.0-alpha1">
    <CLASSES>
      <root url="jar://$USER_HOME$/.android/build-cache/e7aa18d363d0541bb2de7db58f5421c7ba433aed/output/jars/classes.jar!/" />
      <root url="file://$USER_HOME$/.android/build-cache/e7aa18d363d0541bb2de7db58f5421c7ba433aed/output/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/AppData/Local/Android/sdk/extras/android/m2repository/com/android/support/animated-vector-drawable/26.0.0-alpha1/animated-vector-drawable-26.0.0-alpha1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
CCriticalSection cs_alphanodes;
// keep track of the scanning errors I've seen
map<uint256, int> mapSeenAlphanodeScanningErrors;
// cache block hashes as we calculate them
std::map<int64_t, uint256> mapCacheBlockHashes;

struct CompareValueOnly
{
    bool operator()(const pair<int64_t, CTxIn>& t1,
                    const pair<int64_t, CTxIn>& t2) const
    {
        return t1.first < t2.first;
    }
};

//Get the last hash that matches the modulus given. Processed in reverse order
bool GetBlockHash(uint256& hash, int nBlockHeight)
{
    if (pindexBest == NULL) return false;

    if(nBlockHeight == 0)
        nBlockHeight = pindexBest->nHeight;

    if(mapCacheBlockHashes.count(nBlockHeight)){
        hash = mapCacheBlockHashes[nBlockHeight];
        return true;
    }

    const CBlockIndex *BlockLastSolved = pindexBest;
    const CBlockIndex *BlockReading = pindexBest;

    if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || pindexBest->nHeight+1 < nBlockHeight) return false;

    int nBlocksAgo = 0;
    if(nBlockHeight > 0) nBlocksAgo = (pindexBest->nHeight+1)-nBlockHeight;
    assert(nBlocksAgo >= 0);

    int n = 0;
    for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
        if(n >= nBlocksAgo){
            hash = BlockReading->GetBlockHash();
            mapCacheBlockHashes[nBlockHeight] = hash;
            return true;
        }
        n++;

        if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
        BlockReading = BlockReading->pprev;
    }

    return false;
}

CAlphanode::CAlphanode()
{
    LOCK(cs);
    vin = CTxIn();
    addr = CService();
    pubkey = CPubKey();
    pubkey2 = CPubKey();
    sig = std::vector<unsigned char>();
    activeState = ALPHANODE_ENABLED;
    sigTime = GetAdjustedTime();
    lastDseep = 0;
    lastTimeSeen = 0;
    cacheInputAge = 0;
    cacheInputAgeBlock = 0;
    unitTest = false;
    allowFreeTx = true;
    protocolVersion = MIN_PEER_PROTO_VERSION;
    nLastDsq = 0;
    donationAddress = CScript();
    donationPercentage = 0;
    nVote = 0;
    lastVote = 0;
    nScanningErrorCount = 0;
    nLastScanningErrorBlockHeight = 0;
    //mark last paid as current for new entries
    nLastPaid = GetAdjustedTime();
}

CAlphanode::CAlphanode(const CAlphanode& other)
{
    LOCK(cs);
    vin = other.vin;
    addr = other.addr;
    pubkey = other.pubkey;
    pubkey2 = other.pubkey2;
    sig = other.sig;
    activeState = other.activeState;
    sigTime = other.sigTime;
    lastDseep = other.lastDseep;
    lastTimeSeen = other.lastTimeSeen;
    cacheInputAge = other.cacheInputAge;
    cacheInputAgeBlock = other.cacheInputAgeBlock;
    unitTest = other.unitTest;
    allowFreeTx = other.allowFreeTx;
    protocolVersion = other.protocolVersion;
    nLastDsq = other.nLastDsq;
    donationAddress = other.donationAddress;
    donationPercentage = other.donationPercentage;
    nVote = other.nVote;
    lastVote = other.lastVote;
    nScanningErrorCount = other.nScanningErrorCount;
    nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight;
    nLastPaid = other.nLastPaid;
    nLastPaid = GetAdjustedTime();
}

CAlphanode::CAlphanode(CService newAddr, CTxIn newVin, CPubKey newPubkey, std::vector<unsigned char> newSig, int64_t newSigTime, CPubKey newPubkey2, int protocolVersionIn, CScript newDonationAddress, int newDonationPercentage)
{
    LOCK(cs);
    vin = newVin;
    addr = newAddr;
    pubkey = newPubkey;
    pubkey2 = newPubkey2;
    sig = newSig;
    activeState = ALPHANODE_ENABLED;
    sigTime = newSigTime;
    lastDseep = 0;
    lastTimeSeen = 0;
    cacheInputAge = 0;
    cacheInputAgeBlock = 0;
    unitTest = false;
    allowFreeTx = true;
    protocolVersion = protocolVersionIn;
    nLastDsq = 0;
    donationAddress = newDonationAddress;
    donationPercentage = newDonationPercentage;
    nVote = 0;
    lastVote = 0;
    nScanningErrorCount = 0;
    nLastScanningErrorBlockHeight = 0;
}

//
// Deterministically calculate a given "score" for a alphanode depending on how close it's hash is to
// the proof of work for that block. The further away they are the better, the furthest will win the election
// and get paid this block
//
uint256 CAlphanode::CalculateScore(int mod, int64_t nBlockHeight)
{
    if(pindexBest == NULL) return 0;

    uint256 hash = 0;
    uint256 aux = vin.prevout.hash + vin.prevout.n;

    if(!GetBlockHash(hash, nBlockHeight)) return 0;

    uint256 hash2 = Hash(BEGIN(hash), END(hash));
    uint256 hash3 = Hash(BEGIN(hash), END(hash), BEGIN(aux), END(aux));

    uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3);

    return r;
}

void CAlphanode::Check()
{
    if(ShutdownRequested()) return;

    //TODO: Random segfault with this line removed
    TRY_LOCK(cs_main, lockRecv);
    if(!lockRecv) return;

    //once spent, stop doing the checks
    if(activeState == ALPHANODE_VIN_SPENT) return;

    if(!UpdatedWithin(ALPHANODE_REMOVAL_SECONDS)){
        activeState = ALPHANODE_REMOVE;
        return;
    }

    if(!UpdatedWithin(ALPHANODE_EXPIRATION_SECONDS)){
        activeState = ALPHANODE_EXPIRED;
        return;
    }

    if(!unitTest){
        CValidationState state;
        CTransaction tx = CTransaction();
        CTxOut vout = CTxOut(Params().DarkSendPoolMax(), darkSendPool.collateralPubKey);
        tx.vin.push_back(vin);
        tx.vout.push_back(vout);

	if(!AcceptableInputs(mempool, tx, false, NULL)){
            activeState = ALPHANODE_VIN_SPENT;
            return;
        }
    }

    activeState = ALPHANODE_ENABLED; // OK
}


text:
require "benchmark"

module Sassy
  class SSSBuilder

    def initialize(options={})
      @options = options

      raise ArgumentError, "Required option missing: variables" if options[:variables].nil?
      raise ArgumentError, "Required option missing: answers" if options[:answers].nil?
    end

    def write_to_file!
      create_definition_file
      create_answers_file
    end

    def write_variables(io)
      Sassy::DefinitionBuilder.new(@options).write(io)
    end

    def write_answers(io)
      Sassy::AnswerBuilder.new(@options[:answers]).write(io)
    end

    def write_zip(io=nil, def_file_name='definition_file.xml', answer_file_name='data_file.dat')
      buffer = ::ZipRuby::Archive.open_buffer(ZipRuby::CREATE) do |ar|
        def_io = StringIO.new
        dat_io = StringIO.new
        Sassy::DefinitionBuilder.new(@options).write(def_io)
        Sassy::AnswerBuilder.new(@options[:answers]).write(dat_io)
        def_io.rewind
        dat_io.rewind
        ar.add_io(def_file_name, def_io);
        ar.add_io(answer_file_name, dat_io);
      end

      if io
        # remember io position
        pos = io.pos
        io << buffer
        io.pos = pos
        return io
      else
        return buffer
      end
    end

    private

    def create_answers_file(file_name = "definition_file.xml")
      Sassy::AnswerBuilder.new(@options[:answers]).write_to_file(file_name)
    end

    def create_definition_file(file_name = "data_file.dat")
      xml = Sassy::DefinitionBuilder.new(@options).write_to_file
      File.open(file_name, "w") { |file| file.write(xml) }
    end
  end
end


text:
package gov.usda.nrcs.wcc.awdbWebService;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for forecastPeriod complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="forecastPeriod">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="forecastPeriod" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "forecastPeriod", propOrder = {
    "description",
    "forecastPeriod"
})
public class ForecastPeriod {

    protected String description;
    protected String forecastPeriod;

    /**
     * Gets the value of the description property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDescription(String value) {
        this.description = value;
    }

    /**
     * Gets the value of the forecastPeriod property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getForecastPeriod() {
        return forecastPeriod;
    }

    /**
     * Sets the value of the forecastPeriod property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setForecastPeriod(String value) {
        this.forecastPeriod = value;
    }

}


text:
/*! simple-sidebar v2.2.0 (https://dcdeiv.github.io/simple-sidebar)
** Davide Di Criscito <davide.dicriscito@gmail.com> (http://github.com/dcdeiv)
** (c) 2014-2015 Licensed under GPLv2
*/
(function($) {
    $.fn.simpleSidebar = function(options) {
        var opts = $.extend(true, $.fn.simpleSidebar.settings, options);

        return this.each(function() {
            var pAlign, sAlign, ssbCSS, ssbStyle, maskCSS, maskStyle, sbw,
                attr = opts.attr,
                $sidebar = $(this),
                $btn = $(opts.opener),
                $wrapper = $(opts.wrapper),
                $ignore = $(opts.ignore),
                $add = $(opts.add),
                $links = opts.sidebar.closingLinks,

                sbMaxW = opts.sidebar.width,
                gap = opts.sidebar.gap,
                winMaxW = sbMaxW + gap,

                w = $(window).width(),

                duration = opts.animation.duration,

                animationStart = {},
                animationReset = {},
                sidebarStart = {},
                sidebarReset = {},

                hiddenFlow = function() {
                    $('body, html').css('overflow', 'hidden');
                },
                autoFlow = function() {
                    $('body, html').css('overflow', 'auto');
                },

                activate = {
                    duration: duration,
                    easing: opts.animation.easing,
                    complete: hiddenFlow
                },
                deactivate = {
                    duration: duration,
                    easing: opts.animation.easing,
                    complete: autoFlow
                },

                animateOpen = function() {
                    $elements.animate(animationStart, activate);

                    $sidebar.animate(sidebarStart, activate)
                        .attr('data-' + attr, 'active');

                    $mask.fadeIn(duration);
                },
                animateClose = function() {
                    $elements.animate(animationReset, deactivate);

                    $sidebar.animate(sidebarReset, deactivate)
                        .attr('data-' + attr, 'disabled');

                    $mask.fadeOut(duration);
                },
                closeSidebar = function() {
                    var isWhat = $sidebar.attr('data-' + attr),
                        csbw = $sidebar.width();

                    //Redefining animationReset
                    animationReset[pAlign] = '-=' + csbw;
                    animationReset[sAlign] = '+=' + csbw;
                    sidebarReset[pAlign] = -csbw;

                    if (isWhat === 'active') {

                        $elements.not($sidebar)
                            .animate(animationReset, deactivate);

                        $sidebar.animate(sidebarReset, deactivate)
                            .attr('data-' + attr, 'disabled');

                        $mask.fadeOut(duration);
                    }
                },

                $sbWrapper = $('<div>').attr('data-' + attr, 'sbwrapper')
                    .css(opts.sbWrapper.css),

                $mask = $('<div>').attr('data-' + attr, 'mask'),

                //defining elements to move
                $siblings = $wrapper.siblings().not('script noscript'),
                $elements = $wrapper.add($siblings)
                    .not($ignore)
                    .not($sidebar)
                    .not($mask)
                    .not('script')
                    .not('noscript')
                    .add($add);

            //Checking sidebar align
            if (opts.sidebar.align === undefined || opts.sidebar.align === 'right') {
                pAlign = 'right';
                sAlign = 'left';
            } else if (opts.sidebar.align === 'left') {
                pAlign = 'left';
                sAlign = 'right';
            }

            //Mask plugin style
            maskCSS = {
                position: 'fixed',
                top: 0,
                right: 0,
                bottom: 0,
                left: 0,
                zIndex: opts.sidebar.css.zIndex - 1,
                display: 'none'
            };
            maskStyle = $.extend(true, maskCSS, opts.mask.css);

            //Appending Mask if mask.display is true
            if (true === opts.mask.display) {
                $mask.appendTo('body')
                    .css(maskStyle);
            }

            //Defining initial Sidebar width
            if (w < winMaxW) {
                sbw = w - gap;
            } else {
                sbw = sbMaxW;
            }

            //Sidebar plugin style
            ssbCSS = {
                position: 'fixed',
                top: 0,
                bottom: 0,
                width: sbw
            };

            //Opening sidebar
            sidebarStart[pAlign] = 0;

            //pushing align to ssbCSS
            ssbCSS[pAlign] = -sbw;

            //Overriding user style
            ssbStyle = $.extend(true, ssbCSS, opts.sidebar.css);

            //Sidebar initial status
            $sidebar.css(ssbStyle)
                .attr('data-' + attr, 'disabled');

            //Wrapping sidebar inner content if wrapInner.display is TRUE
            if (true === opts.sbWrapper.display) {
                $sidebar.wrapInner($sbWrapper);
            }

            //Animating the sidebar
            $btn.click(function() {
                //Checking if sidebar is active or disabled
                var isWhat = $sidebar.attr('data-' + attr),
                    csbw = $sidebar.width();

                //Defining animations
                animationStart[pAlign] = '+=' + csbw;
                animationStart[sAlign] = '-=' + csbw;
                animationReset[pAlign] = '-=' + csbw;
                animationReset[sAlign] = '+=' + csbw;
                sidebarReset[pAlign] = -csbw;

                if ('disabled' === isWhat) {
                    animateOpen();
                } else if ('active' === isWhat) {
                    animateClose();
                }
            });

            //Closing Sidebar
            $mask.click(closeSidebar);

            //closing sidebar when a link is clicked
            $sidebar.on('click', $links, closeSidebar);

            //Adjusting width and resetting sidebar on window resize
            $(window).resize(function() {
                var rsbw,
                    isWhat = $sidebar.attr('data-' + attr),
                    nw = $(window).width(),
                    reset = {};

                if (nw < winMaxW) {
                    rsbw = nw - gap;
                } else {
                    rsbw = sbMaxW;
                }

                //Redefining animations ad CSS
                animationReset[pAlign] = '-=' + rsbw;
                animationReset[sAlign] = '+=' + rsbw;
                reset[pAlign] = -rsbw;
                reset[sAlign] = '';
                reset.width = rsbw;

                $sidebar.css(reset)
                    .attr('data-' + attr, 'disabled');

                if (isWhat === 'active') {

                    $elements.not($sidebar)
                        .animate(animationReset, deactivate);

                    $mask.fadeOut(duration);
                }
            });
        });
    };

    //options
    $.fn.simpleSidebar.settings = {
        attr: 'simplesidebar',
        animation: {
            duration: 500,
            easing: 'swing'
        },
        sidebar: {
            width: 300,
            gap: 64,
            closingLinks: 'a',
            css: {
                zIndex: 3000
            }
        },
        sbWrapper: {
            display: true,
            css: {
                position: 'relative',
                height: '100%',
                overflowY: 'auto',
                overflowX: 'hidden'
            }
        },
        mask: {
            display: true,
            css: {
                backgroundColor: 'black',
                opacity: 0.5,
                filter: 'Alpha(opacity=50)'
            }
        },
    };
})(jQuery);


text:
<!DOCTYPE html>

  <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Doing the setup for the package convexjlr — convex_setup • convexjlr</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.7/cerulean/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous" />

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha256-eZrrJcwDc/3uDhsdt61sL2oOBY362qM3lon1gyExkL0=" crossorigin="anonymous" />

<link href="../pkgdown.css" rel="stylesheet">

<meta property="og:title" content="Doing the setup for the package convexjlr — convex_setup" />

<meta property="og:description" content="This function does the setup for the package convexjlr.
Firstly it will try to establish the connect to Julia via the XRJulia interface,
or try to embed julia in R through JuliaCall.
Secondly it will check for the Julia packages Convex and SCS,
if the packages are not found, it tries to install them into Julia.
Finally, it will try to load the Julia packages and do the necessary initial setup." />
<meta name="twitter:card" content="summary" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
        Toggle navigation

      </button>

        convexjlr
        0.8.1

  Reference

    Articles

      Convex Optimization by convexjlr

  Changelog

Doing the setup for the package convexjlr

    Source: R/first.R

convex_setup.Rd

This function does the setup for the package convexjlr.
Firstly it will try to establish the connect to Julia via the XRJulia interface,
or try to embed julia in R through JuliaCall.
Secondly it will check for the Julia packages Convex and SCS,
if the packages are not found, it tries to install them into Julia.
Finally, it will try to load the Julia packages and do the necessary initial setup.

convex_setup(backend = c("JuliaCall"), JULIA_HOME = NULL)

Arguments

    <colgroup><col class="name" /><col class="desc" /></colgroup>

      backend

the backend to use, only JuliaCall is supported currently.

      JULIA_HOME

the path to julia binary,
if not set, convexjlr will try to use the julia in path.

Examples

# NOT RUN {
convex_setup()
# }

Contents

Arguments

Examples

Developed by Changcheng Li.

Site built with pkgdown 1.3.0.


text:
""" BVT tests for CM Deployment Planner
"""
# Import Local Modules
from marvin.cloudstackAPI import (deployVirtualMachine, destroyVirtualMachine)
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (Account,
                             ServiceOffering,
                             Host, Pod, Cluster)
from marvin.lib.common import (get_domain,
                               get_zone,
                               get_template)
from marvin.lib.utils import cleanup_resources
from nose.plugins.attrib import attr

class TestVMDeploymentPlanner(cloudstackTestCase):

    @classmethod
    def setUpClass(cls):

        testClient = super(TestVMDeploymentPlanner, cls).getClsTestClient()
        cls.apiclient = testClient.getApiClient()
        cls.services = testClient.getParsedTestDataConfig()

        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.apiclient)
        cls.zone = get_zone(cls.apiclient, testClient.getZoneForTests())
        cls.hypervisor = testClient.getHypervisorInfo()
        cls.services['mode'] = cls.zone.networktype

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id

        # Create an account, network, VM and IP addresses
        cls.account = Account.create(
            cls.apiclient,
            cls.services["account"],
            domainid=cls.domain.id
        )
        cls.service_offering = ServiceOffering.create(
            cls.apiclient,
            cls.services["service_offerings"]["tiny"]
        )

        cls.cleanup = [
            cls.account,
            cls.service_offering
        ]

    @classmethod
    def tearDownClass(cls):
        try:
            cls.apiclient = super(
                TestVMDeploymentPlanner,
                cls
            ).getClsTestClient().getApiClient()
            # Clean up, terminate the created templates
            cleanup_resources(cls.apiclient, cls.cleanup)

        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)

    def deploy_vm(self, destination_id):
        cmd = deployVirtualMachine.deployVirtualMachineCmd()
        template = get_template(
            self.apiclient,
            self.zone.id,
            hypervisor=self.hypervisor
        )
        cmd.zoneid = self.zone.id
        cmd.templateid = template.id
        cmd.serviceofferingid = self.service_offering.id
        cmd.hostid = destination_id
        return self.apiclient.deployVirtualMachine(cmd)

    def destroy_vm(self, vm_id):
        cmd = destroyVirtualMachine.destroyVirtualMachineCmd()
        cmd.expunge = True
        cmd.id = vm_id
        return self.apiclient.destroyVirtualMachine(cmd)

    @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="false")
    def test_01_deploy_vm_on_specific_host(self):
        hosts = Host.list(
            self.apiclient,
            zoneid=self.zone.id,
            type='Routing'
        )
        target_id = hosts[0].id

        vm = self.deploy_vm(target_id)

        self.assertEqual(
            target_id,
            vm.hostid,
            "VM instance was not deployed on target host ID")

        self.destroy_vm(vm.id)

    @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="false")
    def test_02_deploy_vm_on_specific_cluster(self):

        # Select deployment cluster
        clusters = Cluster.list(
            self.apiclient,
        )
        target_cluster = clusters[0]
        target_id = target_cluster.id
        cluster_hypervisor = target_cluster.hypervisortype

        template = get_template(
            self.apiclient,
            hypervisor=cluster_hypervisor
        )

        # deploy vm on cluster
        cmd = deployVirtualMachine.deployVirtualMachineCmd()
        cmd.zoneid = target_cluster.zoneid
        cmd.serviceofferingid = self.service_offering.id
        cmd.templateid = template.id
        cmd.clusterid = target_id
        vm = self.apiclient.deployVirtualMachine(cmd)

        vm_host = Host.list(self.apiclient,
                            id=vm.hostid
                            )

        self.assertEqual(
            target_id,
            vm_host[0].clusterid,
            "VM was not deployed on the provided cluster"
        )
        self.destroy_vm(vm.id)

    @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="false")
    def test_03_deploy_vm_on_specific_pod(self):
        pods = Pod.list(
            self.apiclient,
        )
        target_pod = pods[0]

        # Get host by Pod ID
        host = Host.list(
            self.apiclient,
            podid=target_pod.id)

        # deploy vm on pod
        cmd = deployVirtualMachine.deployVirtualMachineCmd()
        cmd.zoneid = target_pod.zoneid
        cmd.serviceofferingid = self.service_offering.id

        template = get_template(
            self.apiclient,
            hypervisor=host[0].hypervisortype
        )

        cmd.templateid = template.id
        cmd.podid = target_pod.id
        vm = self.apiclient.deployVirtualMachine(cmd)

        vm_host = Host.list(self.apiclient,
                            id=vm.hostid
                            )

        self.assertEqual(
            target_pod.id,
            vm_host[0].podid,
            "VM was not deployed on the target pod"
        )
        self.destroy_vm(vm.id)

    @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="false")
    def test_04_deploy_vm_on_host_override_pod_and_cluster(self):

        # Optional parameters pod, cluster and host
        pod = Pod.list(self.apiclient, zoneid=self.zone.id)[0]
        clusters = Cluster.list(self.apiclient, zoneid=self.zone.id, podid=pod.id)

        self.assertEqual(
            isinstance(clusters, list),
            True,
            "Check list response returns a valid list"
        )

        host = Host.list(self.apiclient, zoneid=self.zone.id, clusterid=clusters[0].id, type='Routing')[0]

        cmd = deployVirtualMachine.deployVirtualMachineCmd()

        # Required parameters
        cmd.zoneid = self.zone.id
        cmd.serviceofferingid = self.service_offering.id
        template = get_template(self.apiclient, zone_id=self.zone.id, hypervisor=host.hypervisor)
        cmd.templateid = template.id

        # Add optional deployment params
        cmd.podid = pod.id
        cmd.clusterid = clusters[1].id if len(clusters) > 1 else clusters[0].id
        cmd.hostid = host.id

        vm = self.apiclient.deployVirtualMachine(cmd)

        self.assertEqual(
            vm.hostid,
            host.id,
            "VM was not deployed on the target host ID"
        )

        self.destroy_vm(vm.id)

    @attr(tags=["advanced", "advancedns", "ssh", "smoke"], required_hardware="false")
    def test_05_deploy_vm_on_cluster_override_pod(self):

        # Optional parameters pod, cluster and host
        pod = Pod.list(self.apiclient, zoneid=self.zone.id)[0]
        clusters = Cluster.list(self.apiclient, zoneid=self.zone.id, podid=pod.id)

        self.assertEqual(
            isinstance(clusters, list),
            True,
            "Check list response returns a valid list"
        )

        cmd = deployVirtualMachine.deployVirtualMachineCmd()

        # Required parameters
        cmd.zoneid = self.zone.id
        cmd.serviceofferingid = self.service_offering.id
        template = get_template(self.apiclient, zone_id=self.zone.id, hypervisor=clusters[0].hypervisortype)
        cmd.templateid = template.id

        # Add optional deployment params
        cmd.podid = pod.id
        cmd.clusterid = clusters[0].id

        vm = self.apiclient.deployVirtualMachine(cmd)

        vm_host = Host.list(self.apiclient,
                            id=vm.hostid
                            )

        self.assertEqual(
            vm_host[0].clusterid,
            clusters[0].id,
            "VM was not deployed on the target cluster"
        )

        self.destroy_vm(vm.id)


text:
import { actions } from "common/actions";
import { User } from "common/butlerd/messages";
import { Dispatch } from "common/types";
import { ambientWind } from "common/util/navigation";
import React from "react";
import Filler from "renderer/basics/Filler";
import { hook } from "renderer/hocs/hook";
import styled, * as styles from "renderer/styles";
import { getUserCoverURL } from "common/constants/get-user-cover-url";

const UserMenuDiv = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;

  padding: 8px;
  margin-right: 8px;

  transition: background 0.2s;
  &:hover {
    background: rgba(0, 0, 0, 0.2);
    cursor: pointer;
  }

  animation: ${styles.animations.enterTop} 0.2s;

  .icon {
    margin: 0;
    transition: all 0.2s;
  }

  img {
    height: 24px;
    width: 24px;
    margin-right: 8px;
    border-radius: 2px;
    flex-shrink: 0;
  }

  span {
    flex-shrink: 1;
    ${styles.singleLine};
  }
`;

class UserMenu extends React.PureComponent<Props> {
  render() {
    if (!this.props.me) {
      return null; // cf. #1405
    }

    return this.me();
  }

  me() {
    const { me } = this.props;
    const { username, displayName } = me;
    const coverUrl = getUserCoverURL(me);

    return (
      <UserMenuDiv className="user-menu" onMouseDown={this.openMenu}>

        {displayName || username}
        <Filler />
      </UserMenuDiv>
    );
  }

  openMenu = (e: React.MouseEvent<any>) => {
    if (e.button === 0) {
      const { dispatch } = this.props;
      dispatch(
        actions.openUserMenu({
          wind: ambientWind(),
          clientX: e.clientX,
          clientY: e.clientY,
        })
      );
    }
  };
}

interface Props {
  dispatch: Dispatch;
  me: User;
}

export default hook((map) => ({
  me: map((rs) => rs.profile.profile.user),
}))(UserMenu);


text:
/*
 * Run_Integrator.h
 *
 *  Created on: 20 Oct 2017
 *      Author: detlevcm
 */

#ifndef HEADERS_RUN_INTEGRATOR_H_
#define HEADERS_RUN_INTEGRATOR_H_

// Function to pick the right integration routine
void Choose_Integrator(
		Filenames,
		Reaction_Mechanism ,
		Initial_Data,
		vector< double >&,
		PressureVesselCalc,
		vector< vector < str_RatesAnalysis > > &
);

int Prepare_Integrator_Settings(
		Initial_Data ,
		size_t ,
		Settings_LSODA& ,
		Settings_Intel&
);

// solve based on concentrations in the liquid phase
void Integrate_Liquid_Phase(
		Filenames,
		vector< double >,
		Reaction_Mechanism ,
		Initial_Data,
		vector< double >&,
		vector< vector < str_RatesAnalysis > > &
);

void Integrate_Gas_Phase_Odepack_LSODA(
		Filenames,
		vector< double >,
		Reaction_Mechanism ,
		Initial_Data,
		vector< double >&,
		vector< vector < str_RatesAnalysis > > &
);

// solve based on concentrations in the liquid phase and consider headspace gas
void Integrate_Pressure_Vessel_Liquid_Phase(
		Filenames,
		vector< double >,
		Reaction_Mechanism ,
		Initial_Data,
		vector< double >&,
		PressureVesselCalc,
		vector< vector < str_RatesAnalysis > > &
);

#endif /* HEADERS_RUN_INTEGRATOR_H_ */


text:
'use strict';

import app from '../..';
import User from './user.model';
var user;
var genUser = function() {
  user = new User({
    provider: 'local',
    name: 'Fake User',
    email: 'test@example.com',
    password: 'password',
    avatar: '//www.gravatar.com/avatar/00000000000000000000000000000000?d=monsterid'

  });
  return user;
};

describe('User Model', function() {
  before(function() {
    // Clear users before testing
    return User.removeAsync();
  });

  beforeEach(function() {
    genUser();
  });

  afterEach(function() {
    return User.removeAsync();
  });

  it('should begin with no users', function() {
    return expect(User.findAsync({})).to
      .eventually.have.length(0);
  });

  it('should fail when saving a duplicate user', function() {
    return expect(user.saveAsync()
      .then(function() {
        var userDup = genUser();
        return userDup.saveAsync();
      })).to.be.rejected;
  });

  describe('#email', function() {
    it('should fail when saving without an email', function() {
      user.email = '';
      return expect(user.saveAsync()).to.be.rejected;
    });
  });

  describe('#password', function() {
    beforeEach(function() {
      return user.saveAsync();
    });

    it('should authenticate user if valid', function() {
      expect(user.authenticate('password')).to.be.true;
    });

    it('should not authenticate user if invalid', function() {
      expect(user.authenticate('blah')).to.not.be.true;
    });

    it('should remain the same hash unless the password is updated', function() {
      user.name = 'Test User';
      return expect(user.saveAsync()
        .spread(function(u) {
          return u.authenticate('password');
        })).to.eventually.be.true;
    });
  });

});


text:
package com.nucleus.scene;

/**
 * An error in a {@linkplain Node}
 *
 * @author Richard Sahlin
 *
 */
public class NodeException extends Exception {

    /**
     *
     */
    private static final long serialVersionUID = 7279916623645807204L;

    public NodeException(String message) {
        super(message);
    }

    public NodeException(Throwable cause) {
        super(cause);
    }
}


text:
package org.apache.felix.service.command;

import java.util.List;

/**
 * A Function is a a block of code that can be executed with a set of arguments,
 * it returns the result object of executing the script.
 */
public interface Function
{
    /**
     * Execute this function and return the result.
     *
     * @return the result from the execution.
     * @throws Exception if anything goes terribly wrong
     */
    Object execute(CommandSession session, List<Object> arguments) throws Exception;
}


text:
/**
 * Module dependencies
 */

var Heroku = require('heroku-client');

module.exports = function(opts) {
  opts = opts || {};
  var client = new Heroku({token: opts.token});
  var router = opts.router;

  function route(task) {
    function error(err) {
      console.log(err.stack || err);
      task.emit('error', err);
    }

    return function() {
      // TODO handle race conditions
      var config = client.apps(router).configVars();
      config.info(function(err, ENV) {
        if (err) error(err);

        var name = task.info.name;
        var NAME = format(name);
        var branch = task.info.branch;
        var BRANCH = format(branch);
        var id = +(new Date);

        ENV['APPS'] = add(name, ENV['APPS']);

        ENV[NAME + '_MOUNT'] = task.info.mount || '/' + name;
        ENV[NAME + '_BRANCHES'] = add(branch, ENV[NAME + '_BRANCHES']);
        ENV[NAME + '_BRANCH_' + BRANCH] = id + ':1';
        ENV[NAME + '_URL_' + id] = 'http://' + task.info.deployment;

        config.update(ENV, function(err) {
          if (err) error(err);
          garbageCollect(client, ENV, name, NAME, branch, BRANCH);
        });
      });
    };
  }

  return function(app) {
    app.on('task', function(task) {
      task.on('success', route(task));
    });
  };
};

function format(name) {
  return name
    .replace(/-/g, '_')
    .toUpperCase();
}

function add(item, list) {
  if (!list) return item;
  var arr = list.split(',');
  if (~arr.indexOf(item)) return list;
  return list + ',' + item;
}

function garbageCollect(ENV, name, NAME, branch, BRANCH, fn) {
  // TODO
}


text:
package org.amote.client;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;

import org.amote.client.android.ScreenInfo;
import org.amote.utils.DatagramUtils;
import org.amote.utils.SensorHub;
import org.gmote.common.MotionEventStruct;
import org.gmote.common.MotionEventStruct.PointerCoordsT;
import org.gmote.common.Protocol.Command;
import org.gmote.common.Protocol.RemoteEvent;
import org.gmote.common.Protocol.UdpPacketTypes;
import org.gmote.common.packet.AbstractPacket;
import org.gmote.common.packet.RemoteEventPacket;
import org.gmote.common.packet.SimplePacket;
import org.gmote.common.packet.TextPacket;

/**
 * Remote Page Acitvity. Simple Remote function, eg: up, down, left, right, home,
 * menu, search, back, volume up, volume down, etc.
 * @author aisino
 *
 */
public class HomeActivity extends Activity implements BaseActivity, OnClickListener
{

	private final String TAG = "HomeActivity";
	private final static int NUM_FLING_POINTS = 9;

	ActivityUtil mUtil = null;
	ImageButton centerBtn = null;
	ImageButton upBtn = null;
	ImageButton downBtn = null;
	ImageButton leftBtn = null;
	ImageButton rightBtn = null;

	ImageButton volupBtn = null;
	ImageButton voldownBtn = null;
//	ImageButton volmuteBtn = null;

	ImageButton homeBtn = null;
	ImageButton menuBtn = null;
	ImageButton backBtn = null;
	ImageButton searchBtn = null;
//	ImageButton shutdownBtn = null;

	ImageButton keyBtn = null;
	ImageButton CloseBtn = null;

	private ImageButton mHomeSwitchButton;
	private ImageButton mRemoteSwitchButton;
	private ImageButton mTouchSwitchButton;
	private ImageButton mGameSwitchButton;

	View viewtempTop = null;
	View viewtempBottom = null;
	View viewtempLeft = null;
	View viewtempRight = null;

	private long startTime = 0;
	ListView mList;
	PopupWindow popupWindow;
	EditText editText;
	int iPopupHeight;
	private int index = 0;
	private KeyInputPopupWindow keyInputPopupWindow;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Remote.getInstance();
		mUtil = new ActivityUtil();
		mUtil.onCreate(savedInstanceState, this);

		setContentView(R.layout.remote_act);

		// need to decouping to Sensor, Now this statement must be invoke, touch event could enable.
		if(SensorHub.getInstance() == null) {
			SensorHub.getInstance(getApplicationContext());
		}
		SensorHub.getInstance().startOrStopSendData(true);

		Display display = getWindowManager().getDefaultDisplay();
		float mScreenWidth = (float) display.getWidth();
		float mScreenHeight = (float) display.getHeight();
		mScreenHeight = mScreenHeight * 400 / 528;
		float vert = 0.0f;
		viewtempTop = (View) findViewById(R.id.vtcl_top);
		viewtempBottom = (View) findViewById(R.id.vtcl_bottom);
		viewtempLeft = (View) findViewById(R.id.hrztl_left);
		viewtempRight = (View) findViewById(R.id.hrztl_right);

		if (mScreenHeight / mScreenWidth > (float)3/(float)2 ) {
			vert = (mScreenHeight * 100 / (mScreenWidth * 3 / 2) - 100) / 2;
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, 0);
			params.weight = vert;
			viewtempTop.setLayoutParams(params);
			viewtempBottom.setLayoutParams(params);
		} else {
			vert = (mScreenWidth * 100 / (mScreenHeight * 2 / 3) - 100) / 2;
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					0, LayoutParams.FILL_PARENT);
			params.weight = vert;
			viewtempLeft.setLayoutParams(params);
			viewtempRight.setLayoutParams(params);
		}

		keyInputPopupWindow = new KeyInputPopupWindow(HomeActivity.this, mUtil);
		centerBtn = (ImageButton) findViewById(R.id.new_media_enter);
		centerBtn.setOnClickListener(this);

		upBtn = (ImageButton) findViewById(R.id.new_media_up);
		upBtn.setOnClickListener(this);
		downBtn = (ImageButton) findViewById(R.id.new_media_down);
		downBtn.setOnClickListener(this);
		leftBtn = (ImageButton) findViewById(R.id.new_media_left);
		leftBtn.setOnClickListener(this);
		rightBtn = (ImageButton) findViewById(R.id.new_media_right);
		rightBtn.setOnClickListener(this);

		volupBtn = (ImageButton) findViewById(R.id.new_media_volup);
		volupBtn.setOnClickListener(this);
		voldownBtn = (ImageButton) findViewById(R.id.new_media_voldown);
		voldownBtn.setOnClickListener(this);

		homeBtn = (ImageButton) findViewById(R.id.new_media_home);
		homeBtn.setOnClickListener(this);
		menuBtn = (ImageButton) findViewById(R.id.new_media_menu);
		menuBtn.setOnClickListener(this);
		backBtn = (ImageButton) findViewById(R.id.new_media_back);
		backBtn.setOnClickListener(this);
		searchBtn = (ImageButton) findViewById(R.id.new_media_search);
		searchBtn.setOnClickListener(this);

		// for send text to server
		keyBtn = (ImageButton) findViewById(R.id.new_media_switch);
		keyBtn.setOnClickListener(this);

		CloseBtn = (ImageButton) findViewById(R.id.new_media_close);
		CloseBtn.setOnClickListener(this);

	    mHomeSwitchButton = (ImageButton) findViewById(R.id.home_switch);
		mHomeSwitchButton.setOnClickListener(this);
		mRemoteSwitchButton = (ImageButton) findViewById(R.id.main_control_switch);
		mRemoteSwitchButton.setOnClickListener(this);
		mRemoteSwitchButton.setBackgroundResource(R.drawable.remote_click_switch);
		mTouchSwitchButton = (ImageButton) findViewById(R.id.touch_pad_switch);
		mTouchSwitchButton.setOnClickListener(this);
		mGameSwitchButton = (ImageButton) findViewById(R.id.game_control_switch);
		mGameSwitchButton.setOnClickListener(this);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		keyInputPopupWindow.onActivityResult(requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void handleReceivedPacket(AbstractPacket reply) {
		if(reply.getCommand() == Command.KEYBOARD) {
			keyInputPopupWindow.startPopupWindow();
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		return mUtil.onCreateDialog(id);
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.new_media_up:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_UP));
			break;
		case R.id.new_media_down:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_DOWN));
			break;
		case R.id.new_media_left:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_LEFT));
			break;
		case R.id.new_media_right:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_RIGHT));
			break;
		case R.id.new_media_enter:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_ENTER));
			break;
		case R.id.new_media_home:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_HOME));
			break;
		case R.id.new_media_menu:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_MENU));
			break;
		case R.id.new_media_back:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_BACK));
			break;
		case R.id.new_media_search:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_SEARCH));
			break;
		case R.id.new_media_voldown:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_VOLDOWN));
			break;
		case R.id.new_media_volup:
			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_VOLUP));
			break;
		case R.id.home_switch:
			this.finish();
			break;
		case R.id.main_control_switch:
			break;
		case R.id.touch_pad_switch:
			intent = new Intent(this,Touchpad.class);
			this.startActivity(intent);
			this.finish();
			break;
		case R.id.game_control_switch:
			intent = new Intent(this,ScreenShowActivity.class);
			this.startActivity(intent);
			this.finish();
			break;

//		case R.id.new_media_power:
//			// test for sensor Activity
////			Intent intent = new Intent();
////			intent.setClass(this, SensorActivity.class);
////			startActivity(intent);
//			this.finish();
//			// end test, need remove
//			break;
//		case R.id.new_media_mute:
//			mUtil.send(new RemoteEventPacket(RemoteEvent.REMOTE_VOLMUTE));
//			break;
		case R.id.new_media_switch:
			keyInputPopupWindow.startPopupWindow();
			break;
		case R.id.new_media_close:
			this.finish();
			break;
		default:
			Log.i(TAG, "default onClick");
			break;
		}
	}

}


text:
package org.apache.camel.dataformat.bindy.model.fix.sorted.header;

import org.apache.camel.dataformat.bindy.annotation.KeyValuePairField;
import org.apache.camel.dataformat.bindy.annotation.Link;
import org.apache.camel.dataformat.bindy.annotation.Section;

@Link
@Section(number = 1)
public class Header {

    @KeyValuePairField(tag = 8, position = 1)
    // Message Header
    private String beginString;

    @KeyValuePairField(tag = 9, position = 2)
    // Checksum
    private int bodyLength;

    @KeyValuePairField(tag = 34, position = 4)
    // Sequence number
    private int msgSeqNum;

    @KeyValuePairField(tag = 35, position = 3)
    // Message Type
    private String msgType;

    @KeyValuePairField(tag = 49, position = 5)
    // Company sender Id
    private String sendCompId;

    @KeyValuePairField(tag = 56, position = 6)
    // target company id
    private String targetCompId;

    public String getBeginString() {
        return beginString;
    }

    public void setBeginString(String beginString) {
        this.beginString = beginString;
    }

    public int getBodyLength() {
        return bodyLength;
    }

    public void setBodyLength(int bodyLength) {
        this.bodyLength = bodyLength;
    }

    public int getMsgSeqNum() {
        return msgSeqNum;
    }

    public void setMsgSeqNum(int msgSeqNum) {
        this.msgSeqNum = msgSeqNum;
    }

    public String getMsgType() {
        return msgType;
    }

    public void setMsgType(String msgType) {
        this.msgType = msgType;
    }

    public String getSendCompId() {
        return sendCompId;
    }

    public void setSendCompId(String sendCompId) {
        this.sendCompId = sendCompId;
    }

    public String getTargetCompId() {
        return targetCompId;
    }

    public void setTargetCompId(String targetCompId) {
        this.targetCompId = targetCompId;
    }

    @Override
    public String toString() {
        return Header.class.getName() + " --> 8: " + this.beginString + ", 9: " + this.bodyLength + ", 34: " + this.msgSeqNum
               + " , 35: " + this.msgType + ", 49: "
               + this.sendCompId + ", 56: " + this.targetCompId;
    }

}


text:
package com.jjinterna.pbxevents.routes.logfile;

import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class LogfileWatcher implements Runnable {

	Path path;
	private static final Logger log = LoggerFactory.getLogger(LogfileWatcher.class);

	public LogfileWatcher(String fileName) {
		path = Paths.get(fileName);
	}

	public abstract void onEntryCreate() throws Exception;
	public abstract void onEntryDelete() throws Exception;

	@Override
	public void run() {
		Path dir = path.getParent();
		log.info("Start");

		try {
			WatchService watcher = dir.getFileSystem().newWatchService();
			WatchKey key = dir.register(watcher,
					ENTRY_CREATE,
					ENTRY_DELETE);
			for (;;) {
				try {
					key = watcher.take();
				} catch (InterruptedException e) {
					log.error("Interrupted");
					return;
				}
				for (WatchEvent<?> event : key.pollEvents()) {
					WatchEvent.Kind<?> kind = event.kind();
					if (kind == OVERFLOW) {
						continue;
					}
					WatchEvent<Path> ev = (WatchEvent<Path>)event;
					Path filename = ev.context();

					Path child = dir.resolve(filename);

					if (child.equals(path)) {
						log.info("Received " + kind.toString());
						try {
							if (kind == ENTRY_CREATE) {
								onEntryCreate();
							} else if (kind == ENTRY_DELETE) {
								onEntryDelete();
							}
						}
						catch (Exception e) {}
					}
				}

				boolean valid = key.reset();
				if (!valid) {
					break;
				}
			}
		} catch (IOException e) {
			log.error(e.getClass().getSimpleName(), e);
		}

		log.info("Stop");
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright 2012 Artur Dryomov
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:auto="http://schemas.android.com/apk/res-auto"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<LinearLayout
		android:orientation="vertical"
		android:padding="16dp"
		android:layout_width="match_parent"
		android:layout_height="wrap_content">

		<com.rengwuxian.materialedittext.MaterialEditText
			android:id="@+id/edit_front_side_text"
			android:singleLine="true"
			android:inputType="text"
			android:imeOptions="flagNoExtractUi"
			android:hint="@string/hint_card_front_text"
			auto:floatingLabel="highlight"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"/>

		<Space
			android:layout_width="match_parent"
			android:layout_height="16dp"/>

		<com.rengwuxian.materialedittext.MaterialEditText
			android:id="@+id/edit_back_side_text"
			android:singleLine="true"
			android:inputType="text"
			android:hint="@string/hint_card_back_text"
			android:imeOptions="actionDone|flagNoExtractUi"
			auto:floatingLabel="highlight"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"/>

	</LinearLayout>

</ScrollView>


text:
"use strict";
import assert from "assert";
import chai from "chai";

chai.should();

describe("kinect-gestures", function () {

  it("should have unit test!", function () {
    assert(true, true);
  });

  it("you will need to get up and move in front of your kinect !", function() {
    assert(true, true);
  });

});


text:
import cssutils
import threading
from operator import itemgetter
try:
    from collections import OrderedDict
except ImportError:  # pragma: no cover
    # some old python 2.6 thing then, eh?
    from ordereddict import OrderedDict

def format_value(prop):
    if prop.priority == "important":
        return prop.propertyValue.cssText.strip() + ' !important'
    else:
        return prop.propertyValue.cssText.strip()

def csstext_to_pairs(csstext):
    """
    csstext_to_pairs takes css text and make it to list of
    tuple of key,value.
    """
    # The lock is required to avoid ``cssutils`` concurrency
    # issues documented in issue #65
    with csstext_to_pairs._lock:
        return sorted(
            [
                (prop.name.strip(), format_value(prop))
                for prop in cssutils.parseStyle(csstext)
            ],
            key=itemgetter(0)
        )

csstext_to_pairs._lock = threading.RLock()

def merge_styles(
        inline_style,
        new_styles,
        classes,
        remove_unset_properties=False
):
    """
        This will merge all new styles where the order is important
        The last one will override the first
        When that is done it will apply old inline style again
        The old inline style is always important and override
        all new ones. The inline style must be valid.

        Args:
            inline_style(str): the old inline style of the element if there
                is one
            new_styles: a list of new styles, each element should be
                a list of tuple
            classes: a list of classes which maps new_styles, important!
            remove_unset_properties(bool): Allow us to remove certain CSS
                properties with rules that set their value to 'unset'

        Returns:
            str: the final style
    """
    # building classes
    styles = OrderedDict([('', OrderedDict())])
    for pc in set(classes):
        styles[pc] = OrderedDict()

    for i, style in enumerate(new_styles):
        for k, v in style:
            styles[classes[i]][k] = v

    # keep always the old inline style
    if inline_style:
        # inline should be a declaration list as I understand
        # ie property-name:property-value;...
        for k, v in csstext_to_pairs(inline_style):
            styles[''][k] = v

    normal_styles = []
    pseudo_styles = []
    for pseudoclass, kv in styles.items():
        if remove_unset_properties:
            # Remove rules that we were going to have value 'unset' because
            # they effectively are the same as not saying anything about the
            # property when inlined
            kv = OrderedDict(
                (k, v) for (k, v) in kv.items() if not v.lower() == 'unset'
            )
        if not kv:
            continue
        if pseudoclass:
            pseudo_styles.append(
                '%s{%s}' % (
                    pseudoclass,
                    '; '.join('%s:%s' % (k, v) for k, v in kv.items())
                )
            )
        else:
            normal_styles.append('; '.join(
                '%s:%s' % (k, v) for k, v in kv.items()
            ))

    if pseudo_styles:
        # if we do or code thing correct this should not happen
        # inline style definition: declarations without braces
        all_styles = (
            (['{%s}' % ''.join(normal_styles)] + pseudo_styles)
            if normal_styles else pseudo_styles
        )
    else:
        all_styles = normal_styles

    return ' '.join(all_styles).strip()