text:
using System;

namespace RazorMailer.Core
{
    public class MissingInformationException : Exception
    {
        public MissingInformationException(string message) : base(message)
        {
        }
    }
}


text:
import unittest
from django.conf import settings
from django_inlines.inlines import Registry, parse_inline, InlineUnparsableError
from core.tests.test_inlines import DoubleInline, QuineInline, KeyErrorInline

class ParserTestCase(unittest.TestCase):

    def testParser(self):
        OUT = ('simple', '', {})
        self.assertEqual(parse_inline('simple'), OUT)
        OUT = ('with', 'a value', {})
        self.assertEqual(parse_inline('with a value'), OUT)
        OUT = ('with', 'a value', {'and': 'args'})
        self.assertEqual(parse_inline('with a value and=args'), OUT)
        OUT = ('with', '', {'just': 'args'})
        self.assertEqual(parse_inline('with just=args'), OUT)
        OUT = ('with', 'complex value http://www.youtube.com/watch?v=nsBAj6eopzc&hd=1&feature=hd#top', {})
        self.assertEqual(parse_inline('with complex value http://www.youtube.com/watch?v=nsBAj6eopzc&hd=1&feature=hd#top'), OUT)
        OUT = ('with', 'complex value http://www.youtube.com/watch?v=nsBAj6eopzc&hd=1&feature=hd#top', {'and': 'args'})
        self.assertEqual(parse_inline('with complex value http://www.youtube.com/watch?v=nsBAj6eopzc&hd=1&feature=hd#top and=args'), OUT)
        OUT = (u'with', u'complex value http://www.youtube.com/watch?v=nsBAj6eopzc', {'and': 'args'})
        self.assertEqual(parse_inline(u'with complex value http://www.youtube.com/watch?v=nsBAj6eopzc and=args'), OUT)
        OUT = ('with', 'a value', {'variant': 'variant', 'and': 'args', 'more': 'arg'})
        self.assertEqual(parse_inline('with:variant a value and=args more=arg'), OUT)
        OUT = ('with', '', {'variant': 'avariant'})
        self.assertEqual(parse_inline('with:avariant'), OUT)

class RegistrySartEndTestCase(unittest.TestCase):

    def setUp(self):
        inlines = Registry()
        inlines.register('double', DoubleInline)
        inlines.START_TAG = '<<'
        inlines.END_TAG = '>>'
        self.inlines = inlines

    def testDifferentSartEnds(self):
        # self.assertEqual(self.inlines.START_TAG, "<<")
        IN = """<< double makes more  >>"""
        OUT = """makes moremakes more"""
        self.assertEqual(self.inlines.process(IN), OUT)
        IN = """<< double 2 >> / << double 2 multiplier=3 >>"""
        OUT = """4 / 6"""
        self.assertEqual(self.inlines.process(IN), OUT)

class InlineTestCase(unittest.TestCase):

    def setUp(self):
        inlines = Registry()
        inlines.register('quine', QuineInline)
        inlines.register('double', DoubleInline)
        self.inlines = inlines

    def tearDown(self):
        settings.INLINE_DEBUG = False

    def testQuineInline(self):
        IN = """{{ quine should be the same }}"""
        OUT = """{{ quine should be the same }}"""
        self.assertEqual(self.inlines.process(IN), OUT)
        IN = """the {{ quine }}"""
        OUT = """the {{ quine }}"""
        self.assertEqual(self.inlines.process(IN), OUT)
        IN = """the {{ quine with value }}
        {{ quine with=args }}
        {{ quine:with_variant }}
        {{ quine:with everything even=args }}
        """
        OUT = """the {{ quine with value }}
        {{ quine with=args }}
        {{ quine:with_variant }}
        {{ quine:with everything even=args }}
        """
        self.assertEqual(self.inlines.process(IN), OUT)

    def testDoubleInline(self):
        IN = """{{ double makes more  }}"""
        OUT = """makes moremakes more"""
        self.assertEqual(self.inlines.process(IN), OUT)
        IN = """{{ double 2 }} / {{ double 2 multiplier=3 }}"""
        OUT = """4 / 6"""
        self.assertEqual(self.inlines.process(IN), OUT)

    def testMultipleInlines(self):
        IN = """{{ quine }} and {{ nothing }}"""
        OUT = """{{ quine }} and """
        self.assertEqual(self.inlines.process(IN), OUT)

    def testRemovalOfUnassignedInline(self):
        IN = """this {{ should }} be removed"""
        OUT = """this  be removed"""
        self.assertEqual(self.inlines.process(IN), OUT)

    def test_empty_inline(self):
        IN = """this {{ 234 }} be removed"""
        OUT = """this  be removed"""
        self.assertEqual(self.inlines.process(IN), OUT)
        settings.INLINE_DEBUG = True
        self.assertRaises(InlineUnparsableError, self.inlines.process, IN)

    def test_keyerrors(self):
        """
        A regression test to make sure KeyErrors thrown by inlines
        aren't silenced in render anymore.
        """
        self.inlines.register('keyerror', KeyErrorInline)
        IN = "{{ keyerror fail! }}"
        self.assertRaises(KeyError, self.inlines.process, IN)

redpajama_set_name: RedPajamaGithub


text:
Troubleshooting
===============

Psycopg2 gives "can't adapt" errors
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The version of Psycopg2 that was installed by default was not compatible.

Try uninstalling the default version and installing a specific version. The version referenced below had been found to work well with Postgres 8.4.10.

::

  $ sudo apt-get remove python-psycopg2
  $ mkdir ~/install
  $ cd ~/install
  $ wget http://initd.org/psycopg/tarballs/PSYCOPG-2-4/psycopg2-2.4.2.tar.gz
  $ tar xzf psycopg2-2.4.2.tar.gz
  $ cd psycopg2-2.4.2
  $ sudo python setup.py install

Another option is to try to install Psycopg2 via easy_install::

  $ sudo easy_install -m psycopg2

To remove a version of Psycopg2 that was installed with easy_install::

  $ sudo rm -rf /usr/lib/python3.6/dist-packages/psycopg2

SSLError(SSLError(1, '[SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca (_ssl.c:2273)'),


text:
#include <stdarg.h>

int vasprintf(char **ptr, const char *format_string, va_list vargs);

int asprintf(char **ptr, const char *fmt, ...)
{
  va_list vargs;
  int retval;

  va_start(vargs, fmt);
  retval = vasprintf(ptr, fmt, vargs);
  va_end(vargs);

  return retval;
}


text:
<?php

namespace backend\controllers;

use backend\models\MultipleUploadForm;
use common\models\Category;
use common\models\Product;
use common\models\UpdateImages;
use Yii;
use common\models\ProductImage;
use backend\models\ProductImageSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

/**
 * ProductImageController implements the CRUD actions for ProductImage model.
 */
class ProductImageController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all ProductImage models.
     * @param int $id product id
     * @return mixed
     *
     * @throws NotFoundHttpException
     */
    public function actionIndex($id)
    {
        if (!Product::find()->where(['id' => $id])->exists()) {
            throw new NotFoundHttpException();
        }

		$product  = Product::findOne($id);

		$dir = Yii::getAlias('@frontend/web/img/');
		$dirFiles = scandir($dir);
		$imgArray = array();

		foreach ($dirFiles as $file) {
			$imgArray[] = substr($file, 0, strpos($file, "."));
		}
		$updateImage = new UpdateImages;

		$update = 0;

		if ($updateImage->load(Yii::$app->request->post()) && $updateImage->validate()) {
	            // Синхронизация картинок

				$items = Product::find()->all();

				foreach ($items as $item) {
					foreach ($imgArray as $imgUid) {
						if ($imgUid == $item->uid) {
							$uploadImg = new ProductImage();
							$uploadImg->product_id = $item->id;
		                    $uploadImg->uid = $item->uid;
		                    $uploadImg->save();
						}
					}
				}
	    } else {
	            $update = 0;
	    }

		$searchModel = new ProductImageSearch();
        $searchModel->product_id = $id;

		$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

		$searchModel->uid   = $product->uid;
		$searchModel->model = $product->model;
        $searchModel->checked = $update;

        $form = new MultipleUploadForm();

        if (Yii::$app->request->isPost) {

            $form->files = UploadedFile::getInstances($form, 'files');

            if ($form->files && $form->validate()) {
                foreach ($form->files as $file) {
                    $image = new ProductImage();
                    $image->product_id = $id;
                    $image->uid = $product->uid;

                    if ($image->save()) {
                        $file->saveAs($image->getPath());
                    }
                }

            }
        }

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'uploadForm' => $form,
            'update' => $update,
            'updateForm' => $updateImage
        ]);
    }

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

        return $this->redirect(['index', 'id' => $productId]);
    }

    /**
     * Finds the ProductImage model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProductImage the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProductImage::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<?php

namespace umi\validation\type;

use umi\validation\BaseValidator;
use umi\validation\exception\RuntimeException;

/**
 * Валидатор по регулярному выражению.
 */
class Regexp extends BaseValidator
{
    /**
     * {@inheritdoc}
     */
    protected $defaultErrorLabel = 'String does not meet regular expression.';

    /**
     * {@inheritdoc}
     */
    public function isValid($value)
    {
        if (empty($this->options['pattern'])) {
            throw new RuntimeException($this->translate(
                'No regular expression pattern.'
            ));
        }

        $pattern = $this->options['pattern'];

        $this->message = null;

        $valid = filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => $pattern]]) !== false;
        if (!$valid) {
            $this->message = $this->translate($this->getErrorLabel());
        }

        return $valid;
    }
}


text:
@interface SBUIAnimationZoomDownAppToPhone : SBUIAnimationZoomDownApp
{
    _Bool _usingSuperZoomImplementation;
    _Bool _fromPhoneAppToFaceTimeAppDuringCall;
}

- (void)_applicationDependencyStateChanged;
- (void)_cleanupAnimation;
- (void)_startAnimation;
- (void)_prepareAnimation;
- (void)animateZoomWithCompletion:(CDUnknownBlockType)arg1;
- (_Bool)_shouldZoomUsingSuperImplementation;
- (id)_animationProgressDependency;
- (_Bool)_waitsForApplicationActivationIfNecessary;
- (void)dealloc;
- (void)_cleanupPhonesContextHostView;
- (id)appStatusBarTransitionInfoWithStartEffectivelyHidden:(_Bool)arg1 endStyleRequest:(id)arg2 endOrientation:(long long)arg3;

@end


text:
Proyecto implementado en Ionic v2 para que los niños con dificultades aprendan a pintar y mezclar colores

# Autores

[Antonio Benítez Guijarro](https://github.com/mrsasuu)

[Emilio Chica Jiménez](https://github.com/nen155)

# Referencias

http://www.purplesquirrels.com.au/blogstuff/canvasdraw/index-touch.html


text:
<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\InvalidParamException;
use common\models\Apply;
use common\models\ApplyLog;

/**
 * Reject apply form
 */
class RejectApplyForm extends Model
{
    public $remark;

    /**
     * @var Apply
     */
    private $_apply;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['remark'], 'trim'],
            [['remark'], 'required'],
            [['remark'], 'string', 'length' => [6, 60]]
        ];
    }

    /**
     * Creates a form model given an apply id.
     *
     * @param  string                          $id
     * @param  array                           $config name-value pairs that will be used to initialize the object properties
     * @throws \yii\base\InvalidParamException if waybill sn is empty or not valid
     */
    public function __construct($id, $config = [])
    {
        if (empty($id) || !is_numeric($id)) {
            throw new InvalidParamException('参数错误!');
        }
        $this->_apply = Apply::findOne($id);

        if (!$this->_apply) {
            throw new InvalidParamException('未找到该申请!');
        }
        if ($this->_apply->status !== Apply::STATUS_PENDING) {
            throw new InvalidParamException('请求错误!');
        }

        parent::__construct($config);
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'remark' => '驳回理由'
        ];
    }

    /**
     * @return boolean
     */
    public function reject($runValidation = true)
    {
        if ($runValidation && !$this->validate()) {
            return false;
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {
            $this->_apply->status = Apply::STATUS_REJECTED;

            if (!$this->_apply->save(false)) {
                throw new \Exception('保存失败!');
            }

            $modelApplyLog = new ApplyLog();
            $modelApplyLog->apply_id = $this->_apply->id;
            $modelApplyLog->remark = '申请被驳回,原因:' . $this->remark;

            if (!$modelApplyLog->save(false)) {
                throw new \Exception('申请日志记录失败!');
            }

            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            return false;
        }
    }

    /**
     * @return Apply
     */
    public function getApply()
    {
        return $this->_apply;
    }
}


text:
<?php

namespace Doctrine\ORM\Mapping\Driver;

use Doctrine\Common\Cache\ArrayCache,
    Doctrine\Common\Annotations\AnnotationReader,
    Doctrine\DBAL\Schema\AbstractSchemaManager,
    Doctrine\DBAL\Schema\SchemaException,
    Doctrine\ORM\Mapping\ClassMetadataInfo,
    Doctrine\ORM\Mapping\MappingException,
    Doctrine\Common\Util\Inflector;

/**
 * The DatabaseDriver reverse engineers the mapping metadata from a database.
 *
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    www.doctrine-project.org
 * @since   2.0
 * @author  Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author  Jonathan Wage <jonwage@gmail.com>
 * @author  Benjamin Eberlei <kontakt@beberlei.de>
 */
class DatabaseDriver implements Driver
{
    /**
     * @var AbstractSchemaManager
     */
    private $_sm;

    /**
     * @var array
     */
    private $tables = null;

    private $classToTableNames = array();

    /**
     * @var array
     */
    private $manyToManyTables = array();

    /**
     * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading
     * docblock annotations.
     *
     * @param AnnotationReader $reader The AnnotationReader to use.
     */
    public function __construct(AbstractSchemaManager $schemaManager)
    {
        $this->_sm = $schemaManager;
    }

    /**
     * Set tables manually instead of relying on the reverse engeneering capabilities of SchemaManager.
     *
     * @param array $entityTables
     * @param array $manyToManyTables
     * @return void
     */
    public function setTables($entityTables, $manyToManyTables)
    {
        $this->tables = $this->manyToManyTables = $this->classToTableNames = array();
        foreach ($entityTables AS $table) {
            $className = Inflector::classify(strtolower($table->getName()));
            $this->classToTableNames[$className] = $table->getName();
            $this->tables[$table->getName()] = $table;
        }
        foreach ($manyToManyTables AS $table) {
            $this->manyToManyTables[$table->getName()] = $table;
        }
    }

    private function reverseEngineerMappingFromDatabase()
    {
        if ($this->tables !== null) {
            return;
        }

        foreach ($this->_sm->listTableNames() as $tableName) {
            $tables[$tableName] = $this->_sm->listTableDetails($tableName);
        }

        $this->tables = $this->manyToManyTables = $this->classToTableNames = array();
        foreach ($tables AS $tableName => $table) {
            /* @var $table Table */
            if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
                $foreignKeys = $table->getForeignKeys();
            } else {
                $foreignKeys = array();
            }

            $allForeignKeyColumns = array();
            foreach ($foreignKeys AS $foreignKey) {
                $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
            }

            $pkColumns = $table->getPrimaryKey()->getColumns();
            sort($pkColumns);
            sort($allForeignKeyColumns);

            if ($pkColumns == $allForeignKeyColumns && count($foreignKeys) == 2) {
                $this->manyToManyTables[$tableName] = $table;
            } else {
                // lower-casing is necessary because of Oracle Uppercase Tablenames,
                // assumption is lower-case + underscore separated.
                $className = Inflector::classify(strtolower($tableName));
                $this->tables[$tableName] = $table;
                $this->classToTableNames[$className] = $tableName;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
    {
        $this->reverseEngineerMappingFromDatabase();

        if (!isset($this->classToTableNames[$className])) {
            throw new \InvalidArgumentException("Unknown class " . $className);
        }

        $tableName = $this->classToTableNames[$className];

        $metadata->name = $className;
        $metadata->table['name'] = $tableName;

        $columns = $this->tables[$tableName]->getColumns();
        $indexes = $this->tables[$tableName]->getIndexes();
        try {
            $primaryKeyColumns = $this->tables[$tableName]->getPrimaryKey()->getColumns();
        } catch(SchemaException $e) {
            $primaryKeyColumns = array();
        }

        if ($this->_sm->getDatabasePlatform()->supportsForeignKeyConstraints()) {
            $foreignKeys = $this->tables[$tableName]->getForeignKeys();
        } else {
            $foreignKeys = array();
        }

        $allForeignKeyColumns = array();
        foreach ($foreignKeys AS $foreignKey) {
            $allForeignKeyColumns = array_merge($allForeignKeyColumns, $foreignKey->getLocalColumns());
        }

        $ids = array();
        $fieldMappings = array();
        foreach ($columns as $column) {
            $fieldMapping = array();
            if ($primaryKeyColumns && in_array($column->getName(), $primaryKeyColumns)) {
                $fieldMapping['id'] = true;
            } else if (in_array($column->getName(), $allForeignKeyColumns)) {
                continue;
            }

            $fieldMapping['fieldName'] = Inflector::camelize(strtolower($column->getName()));
            $fieldMapping['columnName'] = $column->getName();
            $fieldMapping['type'] = strtolower((string) $column->getType());

            if ($column->getType() instanceof \Doctrine\DBAL\Types\StringType) {
                $fieldMapping['length'] = $column->getLength();
                $fieldMapping['fixed'] = $column->getFixed();
            } else if ($column->getType() instanceof \Doctrine\DBAL\Types\IntegerType) {
                $fieldMapping['unsigned'] = $column->getUnsigned();
            }
            $fieldMapping['nullable'] = $column->getNotNull() ? false : true;

            if (isset($fieldMapping['id'])) {
                $ids[] = $fieldMapping;
            } else {
                $fieldMappings[] = $fieldMapping;
            }
        }

        if ($ids) {
            if (count($ids) == 1) {
                $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
            }

            foreach ($ids as $id) {
                $metadata->mapField($id);
            }
        }

        foreach ($fieldMappings as $fieldMapping) {
            $metadata->mapField($fieldMapping);
        }

        foreach ($this->manyToManyTables AS $manyTable) {
            foreach ($manyTable->getForeignKeys() AS $foreignKey) {
                // foreign  key maps to the table of the current entity, many to many association probably exists
                if (strtolower($tableName) == strtolower($foreignKey->getForeignTableName())) {
                    $myFk = $foreignKey;
                    $otherFk = null;
                    foreach ($manyTable->getForeignKeys() AS $foreignKey) {
                        if ($foreignKey != $myFk) {
                            $otherFk = $foreignKey;
                            break;
                        }
                    }

                    if (!$otherFk) {
                        // the definition of this many to many table does not contain
                        // enough foreign key information to continue reverse engeneering.
                        continue;
                    }

                    $localColumn = current($myFk->getColumns());
                    $associationMapping = array();
                    $associationMapping['fieldName'] = Inflector::camelize(str_replace('_id', '', strtolower(current($otherFk->getColumns()))));
                    $associationMapping['targetEntity'] = Inflector::classify(strtolower($otherFk->getForeignTableName()));
                    if (current($manyTable->getColumns())->getName() == $localColumn) {
                        $associationMapping['inversedBy'] = Inflector::camelize(str_replace('_id', '', strtolower(current($myFk->getColumns()))));
                        $associationMapping['joinTable'] = array(
                            'name' => strtolower($manyTable->getName()),
                            'joinColumns' => array(),
                            'inverseJoinColumns' => array(),
                        );

                        $fkCols = $myFk->getForeignColumns();
                        $cols = $myFk->getColumns();
                        for ($i = 0; $i < count($cols); $i++) {
                            $associationMapping['joinTable']['joinColumns'][] = array(
                                'name' => $cols[$i],
                                'referencedColumnName' => $fkCols[$i],
                            );
                        }

                        $fkCols = $otherFk->getForeignColumns();
                        $cols = $otherFk->getColumns();
                        for ($i = 0; $i < count($cols); $i++) {
                            $associationMapping['joinTable']['inverseJoinColumns'][] = array(
                                'name' => $cols[$i],
                                'referencedColumnName' => $fkCols[$i],
                            );
                        }
                    } else {
                        $associationMapping['mappedBy'] = Inflector::camelize(str_replace('_id', '', strtolower(current($myFk->getColumns()))));
                    }
                    $metadata->mapManyToMany($associationMapping);
                    break;
                }
            }
        }

        foreach ($foreignKeys as $foreignKey) {
            $foreignTable = $foreignKey->getForeignTableName();
            $cols = $foreignKey->getColumns();
            $fkCols = $foreignKey->getForeignColumns();

            $localColumn = current($cols);
            $associationMapping = array();
            $associationMapping['fieldName'] = Inflector::camelize(str_replace('_id', '', strtolower($localColumn)));
            $associationMapping['targetEntity'] = Inflector::classify($foreignTable);

            for ($i = 0; $i < count($cols); $i++) {
                $associationMapping['joinColumns'][] = array(
                    'name' => $cols[$i],
                    'referencedColumnName' => $fkCols[$i],
                );
            }
            $metadata->mapManyToOne($associationMapping);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function isTransient($className)
    {
        return true;
    }

    /**
     * Return all the class names supported by this driver.
     *
     * IMPORTANT: This method must return an array of class not tables names.
     *
     * @return array
     */
    public function getAllClassNames()
    {
        $this->reverseEngineerMappingFromDatabase();

        return array_keys($this->classToTableNames);
    }
}


text:
using System;
using System.Linq;
using Microsoft.Azure.Management.WebSites.Models;
using Microsoft.WindowsAzure;

namespace Microsoft.Azure.Management.WebSites.Models
{
    /// <summary>
    /// The Get Web Site Details operation response.
    /// </summary>
    public partial class WebSiteGetResponse : OperationResponse
    {
        private WebSite _webSite;

        /// <summary>
        /// Optional. Details for the requested website.
        /// </summary>
        public WebSite WebSite
        {
            get { return this._webSite; }
            set { this._webSite = value; }
        }

        /// <summary>
        /// Initializes a new instance of the WebSiteGetResponse class.
        /// </summary>
        public WebSiteGetResponse()
        {
        }
    }
}


text:
import { Injectable } from '@angular/core';
import { Action, Selector, State, StateContext } from '@ngxs/store';

import { blogActions } from './blog.actions';
import {
  BLOG_STATE_TOKEN,
  IAppBlogStateModel,
  TAppBlogPayload,
  TAppSelectBlogPostPayload,
} from './blog.interface';

@State<IAppBlogStateModel>({
  name: BLOG_STATE_TOKEN,
  defaults: {
    posts: [],
    selectedPostId: 0,
    selectedPost: null,
  },
})
@Injectable()
export class AppBlogState {
  @Selector()
  public static getState(state: IAppBlogStateModel) {
    return state;
  }

  @Selector()
  public static getPosts(state: IAppBlogStateModel) {
    return state.posts;
  }

  @Selector()
  public static getSelectedPost(state: IAppBlogStateModel) {
    return state.selectedPost;
  }

  @Selector()
  public static listStartReached(state: IAppBlogStateModel) {
    return state.selectedPostId === state.posts.length - 1;
  }

  @Selector()
  public static listEndReached(state: IAppBlogStateModel) {
    return state.selectedPostId === 0;
  }

  @Action(blogActions.setAppBlogState)
  public setAppBlogState(ctx: StateContext<IAppBlogStateModel>, { payload }: TAppBlogPayload) {
    return ctx.patchState(payload);
  }

  @Action(blogActions.selectBlogPost)
  public selectBlogPost(
    ctx: StateContext<IAppBlogStateModel>,
    { payload }: TAppSelectBlogPostPayload,
  ) {
    const state = ctx.getState();
    const selectedPostId = state.posts.findIndex(item => item.code === payload.code);
    const selectedPost = state.posts[selectedPostId];
    return ctx.patchState({ selectedPostId, selectedPost });
  }

  @Action(blogActions.selectNextBlogPost)
  public selectNextBlogPost(ctx: StateContext<IAppBlogStateModel>) {
    const state = ctx.getState();
    const selectedPostId =
      state.selectedPostId - 1 >= 0 ? state.selectedPostId - 1 : state.selectedPostId;
    const selectedPost = state.posts[selectedPostId];
    return ctx.patchState({ selectedPostId, selectedPost });
  }

  @Action(blogActions.selectPreviousBlogPost)
  public selectPreviousBlogPost(ctx: StateContext<IAppBlogStateModel>) {
    const state = ctx.getState();
    const selectedPostId =
      state.selectedPostId + 1 < state.posts.length
        ? state.selectedPostId + 1
        : state.selectedPostId;
    const selectedPost = state.posts[selectedPostId];
    return ctx.patchState({ selectedPostId, selectedPost });
  }
}


text:
package org.elasticsearch.action.ingest;

import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.ingest.IngestDocument;
import org.elasticsearch.ingest.RandomDocumentPicks;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static org.elasticsearch.ingest.IngestDocumentTests.assertIngestDocument;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;

public class SimulatePipelineResponseTests extends ESTestCase {

    public void testSerialization() throws IOException {
        boolean isVerbose = randomBoolean();
        String id = randomBoolean() ? randomAsciiOfLengthBetween(1, 10) : null;
        int numResults = randomIntBetween(1, 10);
        List<SimulateDocumentResult> results = new ArrayList<>(numResults);
        for (int i = 0; i < numResults; i++) {
            boolean isFailure = randomBoolean();
            IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random());
            if (isVerbose) {
                int numProcessors = randomIntBetween(1, 10);
                List<SimulateProcessorResult> processorResults = new ArrayList<>(numProcessors);
                for (int j = 0; j < numProcessors; j++) {
                    String processorTag = randomAsciiOfLengthBetween(1, 10);
                    SimulateProcessorResult processorResult;
                    if (isFailure) {
                        processorResult = new SimulateProcessorResult(processorTag, new IllegalArgumentException("test"));
                    } else {
                        processorResult = new SimulateProcessorResult(processorTag, ingestDocument);
                    }
                    processorResults.add(processorResult);
                }
                results.add(new SimulateDocumentVerboseResult(processorResults));
            } else {
                results.add(new SimulateDocumentBaseResult(ingestDocument));
                SimulateDocumentBaseResult simulateDocumentBaseResult;
                if (isFailure) {
                    simulateDocumentBaseResult = new SimulateDocumentBaseResult(new IllegalArgumentException("test"));
                } else {
                    simulateDocumentBaseResult = new SimulateDocumentBaseResult(ingestDocument);
                }
                results.add(simulateDocumentBaseResult);
            }
        }

        SimulatePipelineResponse response = new SimulatePipelineResponse(id, isVerbose, results);
        BytesStreamOutput out = new BytesStreamOutput();
        response.writeTo(out);
        StreamInput streamInput = out.bytes().streamInput();
        SimulatePipelineResponse otherResponse = new SimulatePipelineResponse();
        otherResponse.readFrom(streamInput);

        assertThat(otherResponse.getPipelineId(), equalTo(response.getPipelineId()));
        assertThat(otherResponse.getResults().size(), equalTo(response.getResults().size()));

        Iterator<SimulateDocumentResult> expectedResultIterator = response.getResults().iterator();
        for (SimulateDocumentResult result : otherResponse.getResults()) {
            if (isVerbose) {
                SimulateDocumentVerboseResult expectedSimulateDocumentVerboseResult = (SimulateDocumentVerboseResult) expectedResultIterator.next();
                assertThat(result, instanceOf(SimulateDocumentVerboseResult.class));
                SimulateDocumentVerboseResult simulateDocumentVerboseResult = (SimulateDocumentVerboseResult) result;
                assertThat(simulateDocumentVerboseResult.getProcessorResults().size(), equalTo(expectedSimulateDocumentVerboseResult.getProcessorResults().size()));
                Iterator<SimulateProcessorResult> expectedProcessorResultIterator = expectedSimulateDocumentVerboseResult.getProcessorResults().iterator();
                for (SimulateProcessorResult simulateProcessorResult : simulateDocumentVerboseResult.getProcessorResults()) {
                    SimulateProcessorResult expectedProcessorResult = expectedProcessorResultIterator.next();
                    assertThat(simulateProcessorResult.getProcessorTag(), equalTo(expectedProcessorResult.getProcessorTag()));
                    if (simulateProcessorResult.getIngestDocument() != null) {
                        assertIngestDocument(simulateProcessorResult.getIngestDocument(), expectedProcessorResult.getIngestDocument());
                    }
                    if (expectedProcessorResult.getFailure() == null) {
                        assertThat(simulateProcessorResult.getFailure(), nullValue());
                    } else {
                        assertThat(simulateProcessorResult.getFailure(), instanceOf(IllegalArgumentException.class));
                        IllegalArgumentException e = (IllegalArgumentException) simulateProcessorResult.getFailure();
                        assertThat(e.getMessage(), equalTo("test"));
                    }
                }
            } else {
                SimulateDocumentBaseResult expectedSimulateDocumentBaseResult = (SimulateDocumentBaseResult) expectedResultIterator.next();
                assertThat(result, instanceOf(SimulateDocumentBaseResult.class));
                SimulateDocumentBaseResult simulateDocumentBaseResult = (SimulateDocumentBaseResult) result;
                if (simulateDocumentBaseResult.getIngestDocument() != null) {
                    assertIngestDocument(simulateDocumentBaseResult.getIngestDocument(), expectedSimulateDocumentBaseResult.getIngestDocument());
                }
                if (expectedSimulateDocumentBaseResult.getFailure() == null) {
                    assertThat(simulateDocumentBaseResult.getFailure(), nullValue());
                } else {
                    assertThat(simulateDocumentBaseResult.getFailure(), instanceOf(IllegalArgumentException.class));
                    IllegalArgumentException e = (IllegalArgumentException) simulateDocumentBaseResult.getFailure();
                    assertThat(e.getMessage(), equalTo("test"));
                }
            }
        }
    }
}


text:
<!doctype html>

    <title>Code coverage report for databseUtils/dropAllTablesScript.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../prettify.css" />
    <link rel="stylesheet" href="../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files / databseUtils dropAllTablesScript.js

        100%
        Statements
        1/1

        100%
        Branches
        0/0

        100%
        Functions
        0/0

        100%
        Lines
        1/1

1
2
3
4
5	1x

const dropAllTablesScript = `SET FOREIGN_KEY_CHECKS=0;
DROP TABLE Student_Assignment, Assignment_Course, Assignment, Lecture_Course, Lecture, Student_Course, Course, GSession, Student;
SET FOREIGN_KEY_CHECKS=1;`
export {dropAllTablesScript}

  Code coverage
  generated by istanbul at Tue Apr 04 2017 02:27:42 GMT+0200 (CEST)


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Address',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('line1', models.CharField(max_length=45)),
                ('line2', models.CharField(max_length=45)),
                ('city', models.CharField(max_length=45)),
                ('state', models.CharField(max_length=2)),
                ('zip', models.PositiveIntegerField(max_length=5)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='Ingredient',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=45)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='IngredientCategory',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=45)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='Item',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=45)),
                ('desc', models.CharField(max_length=255)),
                ('item_photo', models.CharField(max_length=255)),
                ('item_price', models.DecimalField(decimal_places=2, max_digits=10)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='ItemCategory',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=45)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='ItemCustomization',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('add', models.BinaryField()),
                ('ingredient_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_customization', to='MenMew.Ingredient')),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='ItemIngredient',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='ItemOrdered',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('item_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='MenMew.Item')),
            ],
        ),
        migrations.CreateModel(
            name='Restaurant',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=45)),
                ('desc', models.CharField(max_length=255)),
                ('address', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='restaurant', to='MenMew.Address')),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='Server',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('first_name', models.CharField(max_length=45)),
                ('last_name', models.CharField(max_length=45)),
                ('employee_id', models.CharField(max_length=45)),
                ('restaurant_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='MenMew.Restaurant')),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='Table',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('code', models.CharField(max_length=45)),
                ('restaurant_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tables', to='MenMew.Restaurant')),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='Ticket',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('restaurant_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='MenMew.Restaurant')),
                ('server_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='MenMew.Server')),
                ('table_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='MenMew.Table')),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.CreateModel(
            name='User',
            fields=[
                ('id', models.IntegerField(auto_created=True, primary_key=True, serialize=False)),
                ('email', models.CharField(max_length=45)),
                ('password', models.CharField(max_length=128)),
                ('salt', models.CharField(max_length=16)),
                ('first_name', models.CharField(max_length=45)),
                ('last_name', models.CharField(max_length=45)),
            ],
            options={
                'ordering': ('id',),
            },
        ),
        migrations.AddField(
            model_name='ticket',
            name='user_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to='MenMew.User'),
        ),
        migrations.AddField(
            model_name='itemordered',
            name='ticket_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='MenMew.User'),
        ),
        migrations.AddField(
            model_name='itemordered',
            name='user_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items_ordered', to='MenMew.Ticket'),
        ),
        migrations.AddField(
            model_name='itemcustomization',
            name='item_ordered_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_customization', to='MenMew.ItemOrdered'),
        ),
        migrations.AddField(
            model_name='item',
            name='item_category_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='MenMew.ItemCategory'),
        ),
        migrations.AddField(
            model_name='item',
            name='restaurant_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='MenMew.Restaurant'),
        ),
        migrations.AddField(
            model_name='ingredient',
            name='category',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ingredients', to='MenMew.IngredientCategory'),
        ),
    ]


text:
import { OpenIdConfiguration } from '../../openid-configuration';
import { POSITIVE_VALIDATION_RESULT, RuleValidationResult } from '../rule';

export const ensureAuthority = (passedConfig: OpenIdConfiguration): RuleValidationResult => {
  if (!passedConfig.authority) {
    return {
      result: false,
      messages: ['The authority URL MUST be provided in the configuration! '],
      level: 'error',
    };
  }

  return POSITIVE_VALIDATION_RESULT;
};


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using Microsoft.Azure.WebJobs.Host.Converters;
using Microsoft.WindowsAzure.Storage.Table;

namespace Microsoft.Azure.WebJobs.Host.Tables.Converters
{
    internal class Int32ToEntityPropertyConverter : IConverter<int, EntityProperty>
    {
        public EntityProperty Convert(int input)
        {
            return new EntityProperty(input);
        }
    }
}


text:
<?php
/**
 * Redirect page: Special:CreateAccount --> Special:UserLogin/signup.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup SpecialPage
 */

/**
 * Redirect page: Special:CreateAccount --> Special:UserLogin/signup.
 * @todo FIXME: This (and the rest of the login frontend) needs to die a horrible painful death
 *
 * @ingroup SpecialPage
 */
class SpecialCreateAccountPreAuthManager extends SpecialRedirectToSpecial {
	function __construct() {
		parent::__construct(
			'CreateAccount',
			'Userlogin',
			'signup',
			[ 'returnto', 'returntoquery', 'uselang' ]
		);
	}

	public function doesWrites() {
		return true;
	}

	// No reason to hide this link on Special:Specialpages
	public function isListed() {
		return true;
	}

	public function isRestricted() {
		return !User::groupHasPermission( '*', 'createaccount' );
	}

	public function userCanExecute( User $user ) {
		return $user->isAllowed( 'createaccount' );
	}

	protected function getGroupName() {
		return 'login';
	}
}


text:
**UPDATE (June 2018)** -- this project no longer maintained. [BotWikiAwk](https://github.com/greencardamom/BotWikiAwk) is a newer project that includes expanded libraries and tools. Library functions are in library.awk (replacing mwapi.awk) and updated JSON functions are in json.awk (replacing json2var.awk)

MediaWiki Awk API
===========================
by User:Green Cardamom at en.wikipedia.org
May 2015 (1.0)
MIT license

A library of functions in GNU Awk for accessing the MediaWiki API.
For building applications in Awk that use the MediaWiki API.
Supports read/download API functions only, not write.

There are 2 library files and 1 example program (backlinks.awk).

Library files
=============

mwapi.awk

	The API and other functions for building Wikipedia bots and scripts.

json2var.awk

	Json parser. Given a json file, return a single variable with the values needed.
	Depending on the API call, you'll customize a couple lines in parse_value() to
	extract the fields you want.

Demonstration program
=====================

backlinks.awk

	This shows all the backlinks (ie. "Special:What Links Here") for a page.
	It also shows how to use the "continue" command to load > 500 items.

	To run:

		awk -bE backlinks.awk

A complete application, "Backlinks Watchlist" is at
	https://github.com/greencardamom/Backlinks-Watchlist

Other awk based tools
=====================

Wikiget
	https://github.com/greencardamom/Wikiget

WebArchiveMerge
	https://github.com/greencardamom/WebArchiveMerge

WaybackMedic (version 0 is pure awk, 1+ is awk + nim)
	https://github.com/greencardamom/WaybackMedic

PG2WP
	https://github.com/greencardamom/PG2WP


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE415_Double_Free__new_delete_int_82_bad.cpp
Label Definition File: CWE415_Double_Free__new_delete.label.xml
Template File: sources-sinks-82_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 415 Double Free
 * BadSource:  Allocate data using new and Deallocae data using delete
 * GoodSource: Allocate data using new
 * Sinks:
 *    GoodSink: do nothing
 *    BadSink : Deallocate data using delete
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE415_Double_Free__new_delete_int_82.h"

namespace CWE415_Double_Free__new_delete_int_82
{

void CWE415_Double_Free__new_delete_int_82_bad::action(int * data)
{
    /* POTENTIAL FLAW: Possibly deleting memory twice */
    delete data;
}

}
#endif /* OMITBAD */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Grevillea 9(no. 51): 82 (1881)

#### Original name
Phoma xylostei Cooke & Harkn.

### Remarks
null


text:
Developers Guide
================

This documentation is intended for developers who wish to improve or extend the
webdlmon-backend itself.

Adding A New Data Resource
--------------------------

Adding a new data resource always involves adding a new request handler to
controller.py, and may require modifications to model.py, or the addition of a
new model.

Request Handlers
~~~~~~~~~~~~~~~~

Request handlers live in the controller.Controller class. This is a singleton;
IE exactly one instance of Controller is created by the application.

Handlers take a request object and various other arguments parsed from the URL
path. Standard arguments are documented below.

Handlers must return a deferred, which when fired must send a string to it's
callback with the data to be written to the transport. It's perfectly valid for
the deferred to have been fired prior to being returned; this case the data is
written to the transport immediately.

Handlers may be called an arbitrary number of times with the same request
object to facilitate streaming data e.g. on WebSockets.

Handler Arguments
'''''''''''''''''

``request``: All handlers get a request object. For streaming connections, the
handler is called repeatedly with the same request object. The request.repeat
flag is set to False on the first request and True for subsequent requests.
The handler my query this flag and return different data on the first request.
This facilitiates the pattern of sending a full data set immediately upon
connection, followed by deltas only.

``transport``: All handlers get a transport string. This argument is parsed
from the URL path.

``format``: All handlers get a format string. Currently allowed values are
``json`` and ``html``. In all existing handlers, this argument is used to look
up pre-rendered data from the model, although conceivable a future handler
might use this argument to render json, html, or some other format on the fly.

Other arguments: Handlers may accept arbitrary arguments parsed from the URL
path. ``instance`` and ``stations`` are common. Please refer to the Python
Routes documentation for details on url to handler mapping.

URL to Handler Mapping
''''''''''''''''''''''

The get_dispatcher function in controller.py is responsible for connecting
handlers to URLs using txroutes, a Twisted adapter for the Routes packages.

Model Objects
-------------

Model objects may be implemented in any fashion; there really are no constraints on the exact details of how handlers should retrieve data from their models.

However, this application currently ships with various DLMon related objects in
model.py. These all follow a common pattern, which is documented here.

All current model objects have an ObservableDict instance in their .data
member. ObservableDict is part of the kudu project; refer to the kudu
documentation for the full details. However I will describe it briefly here.

ObservableDict is a subclass of dict, with added functionality for returning Twisted Deferred objects. When requesting a deferred, the user my specify that the deferred should be fired immediately, calling back with the current value stored at the specified key. Alternatively the user may request that the deferred fire when the value at the specified key changes, calling back with the new value.

The DLMon model listens to one or more Orb objects for new status packets. As
packets arrive they are distributed to the various model objects by passing to
the update method.

The update method is responsible for transforming the update data into an end
data product, in the form of a JSON-serializable dict.  The DataObject
superclass update method serializes this dict to a JSON string and stores it in
it's data['json'] member. The method also renders the appropriate HTML
template, passing in the serializable dict; the template may take arbitrary
action but must return a string which is then stored in data['html'].

Design Discussion
-----------------

This application primarily receives datalogger status packets from Antelope
orbs and transforms those data into web-friendly data products and makes them
available to both synchronous clients and asynchronous streaming clients.

When designing this application, my initial approach was similar to most other
web applications; render data into strings in response to client requests.

This design has the advantage that data products are only rendered when they
are actually being used, avoiding rendering a bunch of data that nobody is
using at a point in time. This should have good average-case performance when
the volume of incoming data is large and the number of clients is small.  When
the inverse is true, however, the worst case performance could be quite bad.

One important difference from other web apps is that the data served up is NOT
dynamic. It's not like a blog app or something where every request pulls some
data from a database and dynamically renders a template with it; regardless of
when the data is rendered, all users requesting a particular resource see the
same data, until the next packet arrives from the orb. Thus rendering data in
response to queries is wasteful when multiple users request the same resource.

The obvious solution is to implement some sort of cacheing scheme; render the
data on the first request, cache it for subsequent requests, and flush it when
new data arrives from the orb. This scheme would certainly work although it
adds an awful lot of complexity to the application. Caching is notoriously
difficult to get right. Add in the fact that some of our connections are
long-lived and streaming live data and things go downhill fast.

The other disadvantage to this approach is the fact that the model is taking
some action on the data in response to packets off the orb ANYWAY, typically
performing some processing and then storing it in objects until requested by a
handler.

The superior approach in this application is to render data products all the
way to transport-writeable strings in response to packets from the orb. It's
simple for the model to do and no caching is required. It also simplifies the
handler code; all it must do is lookup a string-returning deferred from
somewhere. This approach is much less complex and requires substanially fewer
lines of code.

The performance characteristics of this approach differ slightly. The load to
render the data is relative to the volume of incoming data, which is roughly
constant over periods of days and weeks. So even with zero clients the server
is rendering everything all the time, and this may be seen as wasteful.  In
practice, the load this puts on the server is negligable. While it would be
possible to implement some sort of scheme for only rendering data when clients
are acively requesting it, that would be a premature optimization.

Performance of pre-rendering relative to the number of clients should be
similar to the caching solution described previously. Again in practice, in a
heavily used system with many clients, the rendering load will be negligable
compared to the request handling load.


text:
#include "org_apache_hadoop_io_compress_snappy_SnappyDecompressor.h"
#include "hadoop_snappy.h"
#include <snappy.h>
#include <stdlib.h>

static jfieldID SnappyDecompressor_clazz;
static jfieldID SnappyDecompressor_compressedDirectBuf;
static jfieldID SnappyDecompressor_compressedDirectBufLen;
static jfieldID SnappyDecompressor_uncompressedDirectBuf;

JNIEXPORT void JNICALL Java_org_apache_hadoop_io_compress_snappy_SnappyDecompressor_initIDs
(JNIEnv *env, jclass clazz){
  SnappyDecompressor_clazz = env->GetStaticFieldID(clazz, "clazz",
                                                   "Ljava/lang/Class;");
  SnappyDecompressor_compressedDirectBuf = env->GetFieldID(clazz,
                                                           "compressedDirectBuf",
                                                           "Ljava/nio/Buffer;");
  SnappyDecompressor_compressedDirectBufLen = env->GetFieldID(clazz,
                                                              "compressedDirectBufLen", "I");
  SnappyDecompressor_uncompressedDirectBuf = env->GetFieldID(clazz,
                                                             "uncompressedDirectBuf",
                                                             "Ljava/nio/Buffer;");
}

JNIEXPORT jint JNICALL Java_org_apache_hadoop_io_compress_snappy_SnappyDecompressor_decompressBytesDirect
(JNIEnv *env, jobject thisj){
  // Get members of SnappyDecompressor
  jclass c = env->GetObjectClass(thisj);
  jobject clazz = env->GetStaticObjectField(c, SnappyDecompressor_clazz);
  jobject compressed_direct_buf = env->GetObjectField(thisj, SnappyDecompressor_compressedDirectBuf);
  jint compressed_direct_buf_len = env->GetIntField(thisj, SnappyDecompressor_compressedDirectBufLen);
  jobject uncompressed_direct_buf = env->GetObjectField(thisj, SnappyDecompressor_uncompressedDirectBuf);

  // Get the input direct buffer
  LOCK_CLASS(env, clazz, "SnappyDecompressor");
  const char* compressed_bytes = (const char*)env->GetDirectBufferAddress(compressed_direct_buf);
  UNLOCK_CLASS(env, clazz, "SnappyDecompressor");

  if (compressed_bytes == 0) {
    return (jint)0;
  }

  // Get the output direct buffer
  LOCK_CLASS(env, clazz, "SnappyDecompressor");
  char* uncompressed_bytes = (char *)env->GetDirectBufferAddress(uncompressed_direct_buf);
  UNLOCK_CLASS(env, clazz, "SnappyDecompressor");

  if (uncompressed_bytes == 0) {
    return (jint)0;
  }

  size_t uncompress_length;
  bool ret = snappy::GetUncompressedLength(compressed_bytes, compressed_direct_buf_len, &uncompress_length);
  if (!ret){
    THROW(env, "Ljava/lang/InternalError", "Could not get decompressed length.");
  }

  ret = snappy::RawUncompress(compressed_bytes, compressed_direct_buf_len, uncompressed_bytes);
  if (!ret){
    THROW(env, "Ljava/lang/InternalError", "Could not decompress data.");
  }

  env->SetIntField(thisj, SnappyDecompressor_compressedDirectBufLen, 0);

  return (jint)uncompress_length;
}


text:
A base theme for Hugo sites. Though it looks like a theme, the intent is to provide a solid starting place for Hugo sites and include best practices for performance, A11y, and rapid development.

It's subject to change quite a bit at this point.

Features

- Automated Robots.txt (changes values based on environment)


text:
"""Tests for bsuite.sweep."""

from absl.testing import absltest
from absl.testing import parameterized
from bsuite import sweep

class SweepTest(parameterized.TestCase):

  def test_access_sweep(self):
    self.assertNotEmpty(sweep.SETTINGS)

  def test_access_experiment_constants(self):
    self.assertNotEmpty(sweep.DEEP_SEA)

  @parameterized.parameters(*sweep.SETTINGS)
  def test_sweep_name_format(self, bsuite_id):
    self.assertIn(sweep.SEPARATOR, bsuite_id)
    split = bsuite_id.split(sweep.SEPARATOR)
    self.assertTrue(len(split), 2)
    self.assertNotEmpty(split[0])
    self.assertNotEmpty(split[1])

if __name__ == '__main__':
  absltest.main()


text:
package org.apache.causeway.viewer.wicket.ui.components.property;

import org.apache.wicket.markup.html.WebMarkupContainer;

import org.apache.causeway.core.metamodel.commons.ScalarRepresentation;
import org.apache.causeway.core.metamodel.object.ManagedObject;
import org.apache.causeway.viewer.commons.model.components.UiComponentType;
import org.apache.causeway.viewer.commons.model.hints.RenderingHint;
import org.apache.causeway.viewer.wicket.model.models.ScalarModel;
import org.apache.causeway.viewer.wicket.model.models.ScalarPropertyModel;
import org.apache.causeway.viewer.wicket.ui.components.actions.ActionParametersPanel;
import org.apache.causeway.viewer.wicket.ui.panels.PanelAbstract;
import org.apache.causeway.viewer.wicket.ui.util.Wkt;

/**
 * Corresponding component to prompt for action (parameters) is {@link ActionParametersPanel}.
 */
public class PropertyEditPanel
extends PanelAbstract<ManagedObject, ScalarPropertyModel> {

    private static final long serialVersionUID = 1L;

    private static final String ID_HEADER = "header";
    private static final String ID_PROPERTY_NAME = "propertyName";

    /**
     * Gives a chance to hide the header part of this panel.
     */
    private boolean showHeader = true;

    public PropertyEditPanel(
            final String id,
            final ScalarPropertyModel scalarModel) {

        super(id, scalarModel.copyHaving(
                ScalarRepresentation.EDITING,
                RenderingHint.REGULAR));

        buildGui(scalarModel);
    }

    @Override
    protected void onConfigure() {
        super.onConfigure();

        buildGui(scalarModel());
    }

    private void buildGui(final ScalarModel scalarModel) {
        buildGuiForParameters(scalarModel);
    }

    ScalarPropertyModel scalarModel() {
        return super.getModel();
    }

    public PropertyEditPanel setShowHeader(final boolean showHeader) {
        this.showHeader = showHeader;
        return this;
    }

    private void buildGuiForParameters(final ScalarModel scalarModel) {

        WebMarkupContainer header = addHeader();

        getComponentFactoryRegistry().addOrReplaceComponent(this, UiComponentType.PROPERTY_EDIT_FORM, scalarModel());
        getComponentFactoryRegistry().addOrReplaceComponent(header, UiComponentType.ENTITY_ICON_AND_TITLE, scalarModel.getParentUiModel());

        Wkt.labelAdd(header, ID_PROPERTY_NAME, scalarModel()::getFriendlyName)
            .setEscapeModelStrings(true);
    }

    private WebMarkupContainer addHeader() {
        WebMarkupContainer header = new WebMarkupContainer(ID_HEADER) {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onConfigure() {
                super.onConfigure();

                setVisible(showHeader);
            }
        };
        addOrReplace(header);
        return header;
    }

}


text:
package boofcv.alg.geo.calibration;

import georegression.geometry.RotationMatrixGenerator;
import georegression.struct.point.Point2D_F64;
import georegression.struct.se.Se3_F64;
import org.ddogleg.optimization.FactoryOptimization;
import org.ddogleg.optimization.UnconstrainedLeastSquares;
import org.ejml.data.DenseMatrix64F;

import java.util.ArrayList;
import java.util.List;

/**
 *

 * Full implementation of the Zhang99 camera calibration algorithm using planar calibration targets.  First
 * linear approximations of camera parameters are computed, which are then refined using non-linear estimation.
 * One difference from the original paper is that tangential distortion can be included. No linear estimate
 * if found for tangential, they are estimated by initializing the non-linear estimate with all zero.
 *

 *
 *

 * When processing the results be sure to take in account the coordinate system being left or right handed.  Calibration
 * works just fine with either coordinate system, but most 3D geometric algorithms assume a right handed coordinate
 * system while most images are left handed.
 *

 *
 *

 * A listener can be provide that will give status updates and allows requests for early termination.  If a request
 * for early termination is made then a RuntimeException will be thrown.
 *

 *
 *

 * [1] Zhengyou Zhang, "Flexible Camera Calibration By Viewing a Plane From Unknown Orientations,",
 * International Conference on Computer Vision (ICCV'99), Corfu, Greece, pages 666-673, September 1999.
 *

 *
 * @author Peter Abeles
 */
public class CalibrationPlanarGridZhang99 {

	// estimation algorithms
	private Zhang99ComputeTargetHomography computeHomography;
	private Zhang99CalibrationMatrixFromHomographies computeK;
	private RadialDistortionEstimateLinear computeRadial;
	private Zhang99DecomposeHomography decomposeH = new Zhang99DecomposeHomography();

	// contains found parameters
	private Zhang99ParamAll optimized;

	// optimization algorithm
	private UnconstrainedLeastSquares optimizer;

	// provides information on calibration status
	private Listener listener;

	// where calibration points are layout on the target.
	private List<Point2D_F64> layout;

	/**
	 * Configures calibration process.
	 *
	 * @param layout Layout of calibration points on the target
	 * @param assumeZeroSkew Should it assumed the camera has zero skew. Typically true.
	 * @param numRadialParam Number of radial distortion parameters to consider.  Typically 0,1,2.
	 * @param includeTangential Should it include tangential distortion?
	 */
	public CalibrationPlanarGridZhang99(List<Point2D_F64> layout,
										boolean assumeZeroSkew,
										int numRadialParam,
										boolean includeTangential )
	{
		this.layout = layout;
		computeHomography = new Zhang99ComputeTargetHomography(layout);
		computeK = new Zhang99CalibrationMatrixFromHomographies(assumeZeroSkew);
		computeRadial = new RadialDistortionEstimateLinear(layout,numRadialParam);
		optimized = new Zhang99ParamAll(assumeZeroSkew,numRadialParam,includeTangential);
	}

	/**
	 * Used to listen in on progress and request that processing be stopped
	 *
	 * @param listener The listener
	 */
	public void setListener(Listener listener) {
		this.listener = listener;
	}

	/**
	 * Processes observed calibration point coordinates and computes camera intrinsic and extrinsic
	 * parameters.
	 *
	 * @param observations Set of observed grid locations in pixel coordinates.
	 * @return true if successful and false if it failed
	 */
	public boolean process( List<List<Point2D_F64>> observations ) {

		optimized.setNumberOfViews(observations.size());

		// compute initial parameter estimates using linear algebra
		Zhang99ParamAll initial =  initialParam(observations);
		if( initial == null )
			return false;

		status("Non-linear refinement");
		// perform non-linear optimization to improve results
		if( !optimizedParam(observations,layout,initial,optimized,optimizer))
			return false;

		return true;
	}

	/**
	 * Find an initial estimate for calibration parameters using linear techniques.
	 */
	protected Zhang99ParamAll initialParam( List<List<Point2D_F64>> observations )
	{
		status("Estimating Homographies");
		List<DenseMatrix64F> homographies = new ArrayList<DenseMatrix64F>();
		List<Se3_F64> motions = new ArrayList<Se3_F64>();

		for( List<Point2D_F64> obs : observations ) {
			if( !computeHomography.computeHomography(obs) )
				return null;

			DenseMatrix64F H = computeHomography.getHomography();

			homographies.add(H);
		}

		status("Estimating Calibration Matrix");
		computeK.process(homographies);

		DenseMatrix64F K = computeK.getCalibrationMatrix();

		decomposeH.setCalibrationMatrix(K);
		for( DenseMatrix64F H : homographies ) {
			motions.add(decomposeH.decompose(H));
		}

		status("Estimating Radial Distortion");
		computeRadial.process(K, homographies, observations);

		double distort[] = computeRadial.getParameters();

		return convertIntoZhangParam(motions, K,optimized.assumeZeroSkew, distort,
				optimized.includeTangential);
	}

	private void status( String message ) {
		if( listener != null ) {
			if( !listener.zhangUpdate(message) )
				throw new RuntimeException("User requested termination of calibration");
		}
	}

	/**
	 * Use non-linear optimization to improve the parameter estimates
	 *
	 * @param observations Observations of calibration points in each image
	 * @param grid Location of calibration points on calibration target
	 * @param initial Initial estimate of calibration parameters.
	 * @param found The refined calibration parameters.
	 * @param optimizer Algorithm used to optimize parameters
	 */
	public boolean optimizedParam( List<List<Point2D_F64>> observations ,
								   List<Point2D_F64> grid ,
								   Zhang99ParamAll initial ,
								   Zhang99ParamAll found ,
								   UnconstrainedLeastSquares optimizer )
	{
		if( optimizer == null ) {
//			optimizer = FactoryOptimization.leastSquaresTrustRegion(1,
//					RegionStepType.DOG_LEG_FTF,true);
			optimizer = FactoryOptimization.leastSquaresLM(1e-3,true);
//			optimizer = FactoryOptimization.leastSquareLevenberg(1e-3);
		}

		double model[] = new double[ initial.numParameters() ];
		initial.convertToParam(model);

		Zhang99OptimizationFunction func = new Zhang99OptimizationFunction(
				initial.createNew(), grid,observations);

		Zhang99OptimizationJacobian jacobian = new Zhang99OptimizationJacobian(
				initial.assumeZeroSkew,initial.radial.length,initial.includeTangential,
				observations.size(),grid);

		optimizer.setFunction(func,jacobian);
		optimizer.initialize(model,1e-10,1e-25*observations.size());

		for( int i = 0; i < 500; i++ ) {
			if( optimizer.iterate() ) {
				break;
			} else {
				if( i % 25 == 0 )
					status("Progress "+(100*i/500.0)+"%");
			}
		}

		double param[] = optimizer.getParameters();
		found.setFromParam(param);

		return true;
	}

	/**
	 * Converts results fond in the linear algorithms into {@link Zhang99ParamAll}
	 */
	public static Zhang99ParamAll convertIntoZhangParam(List<Se3_F64> motions,
														  DenseMatrix64F K,
														  boolean assumeZeroSkew,
														  double[] distort,
														  boolean includeTangential ) {
		Zhang99ParamAll ret = new Zhang99ParamAll();

		ret.assumeZeroSkew = assumeZeroSkew;

		ret.a = K.get(0,0);
		ret.b = K.get(1,1);
		ret.c = K.get(0,1);
		ret.x0 = K.get(0,2);
		ret.y0 = K.get(1,2);

		ret.radial = distort;

		ret.includeTangential = includeTangential;

		ret.views = new Zhang99ParamAll.View[motions.size()];
		for( int i = 0; i < ret.views.length; i++ ) {
			Se3_F64 m = motions.get(i);

			Zhang99ParamAll.View v = new Zhang99ParamAll.View();
			v.T = m.getT();
			RotationMatrixGenerator.matrixToRodrigues(m.getR(), v.rotation);

			ret.views[i] = v;
		}

		return ret;
	}

	/**
	 * Applies radial and tangential distortion to the normalized image coordinate.
	 *
	 * @param normPt point in normalized image coordinates
	 * @param radial radial distortion parameters
	 * @param t1 tangential parameter
	 * @param t2 tangential parameter
	 */
	public static void applyDistortion(Point2D_F64 normPt, double[] radial, double t1 , double t2 )
	{
		final double x = normPt.x;
		final double y = normPt.y;

		double a = 0;
		double r2 = x*x + y*y;
		double r2i = r2;
		for( int i = 0; i < radial.length; i++ ) {
			a += radial[i]*r2i;
			r2i *= r2;
		}

		normPt.x = x + x*a + 2*t1*x*y + t2*(r2 + 2*x*x);
		normPt.y = y + y*a + t1*(r2 + 2*y*y) + 2*t2*x*y;
	}

	/**
	 * Specify which optimization algorithm to use
	 */
	public void setOptimizer(UnconstrainedLeastSquares optimizer) {
		this.optimizer = optimizer;
	}

	public Zhang99ParamAll getOptimized() {
		return optimized;
	}

	public static interface Listener
	{
		/**
		 * Updated to update the status and request that processing be stopped
		 *
		 * @param taskName Name of the task being performed
		 * @return true to continue and false to request a stop
		 */
		public boolean zhangUpdate( String taskName );
	}
}


text:
var rimraf = require('rimraf')

var fsHelpers = require('../fs-helpers')

function deleteHandler (configuration) {
  return function (req, res, next) {
    var uuid = req.params.uuid
    if (uuid) {
      var destination = fsHelpers.generateDestination(uuid, configuration.baseUploadDirectory, configuration.finalUploadDirectory)
      rimraf(destination, function (err, cb) {
        if (err) {
          return next(err)
        }
        return res.status(200).send()
      })
    } else {
      res.status(404).send()
    }
  }
}

module.exports = deleteHandler


text:
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {isBlank, isPresent, BaseException, CONST} from 'angular2/src/facade/lang';
import {Pipe} from './pipe';
import {Injectable} from 'angular2/src/di/decorators';
import {ChangeDetectorRef} from '../change_detector_ref';

@Injectable()
export class PipeRegistry {
  constructor(public config) {}

  get(type: string, obj, cdRef: ChangeDetectorRef): Pipe {
    var listOfConfigs = this.config[type];
    if (isBlank(listOfConfigs)) {
      throw new BaseException(`Cannot find '${type}' pipe supporting object '${obj}'`);
    }

    var matchingConfig = ListWrapper.find(listOfConfigs, (pipeConfig) => pipeConfig.supports(obj));

    if (isBlank(matchingConfig)) {
      throw new BaseException(`Cannot find '${type}' pipe supporting object '${obj}'`);
    }

    return matchingConfig.create(cdRef);
  }
}


text:
'use strict'

const m = require('mithril')
const mnr = require('mithril-node-render')

const render = module.exports = (data, els) =>
  [ '<!DOCTYPE html>'
  , mnr(m('html', {lang: 'en-us'}, els.map(el => el(data))))
  ].join('')


text:
package models

import play.api.mvc.{Request, Security}

import SQ._

case class User(
						email: String,
						passhash: String
						) extends IdPK {

//	def this() = this("", "")

	val username = email

	def profile = transaction { Profile.table.where(_.user_id === id).head }

	lazy val haves = Schema.userHaves.left(this)
	lazy val wants = Schema.userWants.left(this)

	def isAdmin = false

	def meta = User
}

object User extends MetaModel[User] {
	val table = Schema.users

	def getByName(username:String) = inTransaction {
		table.where(_.username === username).head
	}

	def lookupByName(username:String) = inTransaction {
		table.where(_.username === username).headOption
	}

	def currentUser(implicit request:Request[_]) = request.session.get(Security.username).flatMap(User.lookupByName(_))

	def authenticate(username: String, password: String):Option[User] = inTransaction {
		// TODO: use SHA1
		table.where( u => u.username === username and u.passhash === password ).headOption
	}

	def register(newUser:User) = transaction {
		val user = table.insert(newUser)
		Profile.table.insert(Profile.blank(user))
		user
	}
}


text:
@implementation Term

-(id)initWithDictionary:(NSDictionary *)dictionary
{
    if (self = [super init])
    {
        self.id = [[JSONUtils jsonValueOrNil:dictionary forKey:@"id"] integerValue];
        self.name = [JSONUtils jsonValueOrNil:dictionary forKey:@"name"];
    }// End of if

    return self;
}// End of initWithDictionary

@end


text:
class TicketNotificationMailerPreview < ActionMailer::Preview
  def message_to_student
    sender = User.new(username: 'admin',
                      real_name: 'Delano (Wiki Edu)',
                      permissions: User::Permissions::ADMIN)
    recipient = User.new(username: 'flanagan.hyder')
    TicketNotificationMailer.notify(
      course:, message:, recipient:,
      sender:, bcc_to_salesforce: false
    )
  end

  def message_to_instructor
    sender = User.new(username: 'flanagan.hyder')
    recipient = User.new(username: 'admin',
                         real_name: 'Delano (Wiki Edu)',
                         permissions: User::Permissions::ADMIN)
    TicketNotificationMailer.notify(
      course:, message:, recipient:,
      sender:, bcc_to_salesforce: false
    )
  end

  def open_tickets_notification
    owner = User.admin.first
    tickets = TicketDispenser::Ticket.first(20)
    TicketNotificationMailer.open_tickets_notify(
      owner:,
      tickets:
    )
  end

  private

  def course
    Course.new(slug: 'course/title', title: 'My Course')
  end

  def message
    ticket = TicketDispenser::Ticket.first
    ticket.messages.last
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Epsilon Aurigae in Total Eclipse, 2010 - Revealing the Transiting Disk</AwardTitle>
    <AwardEffectiveDate>02/15/2010</AwardEffectiveDate>
    <AwardExpirationDate>01/31/2012</AwardExpirationDate>
    <AwardAmount>122018</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      03020000
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Astronomical Sciences</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Maria Womack</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>Dr. Robert Stencil of the University of Denver will undertake a detailed study of the enigmatic star epsilon Aurigae. In the year 2010, the star will undergo an eclipse by a massive, dusty circumstellar disk. These eclipses take place only about every 27 years. In this effort, Dr. Stencel and his collaborators will use interferometric observations to make high-resolution images of the stellar surface and the disk, and to examine the properties of the disk compared to those in other systems.<br/><br/>The project will have broader impacts in education and workforce development through the training of graduate and undergraduate students. Results from this study will be widely disseminated at scientific meetings. This effort is part of a larger international collaboration which will study this star with many different observational techniques.</AbstractNarration>
    <MinAmdLetterDate>02/16/2010</MinAmdLetterDate>
    <MaxAmdLetterDate>02/16/2010</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1016678</AwardID>
    <Investigator>
      <FirstName>Robert</FirstName>
      <LastName>Stencel</LastName>
      <EmailAddress>rstencel@du.edu</EmailAddress>
      <StartDate>02/16/2010</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>University of Denver</Name>
      <CityName>Denver</CityName>
      <ZipCode>802104711</ZipCode>
      <PhoneNumber>3038712000</PhoneNumber>
      <StreetAddress>2199 S. University Blvd.</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Colorado</StateName>
      <StateCode>CO</StateCode>
    </Institution>
    <ProgramElement>
      1215
      <Text>STELLAR ASTRONOMY & ASTROPHYSC</Text>
    </ProgramElement>
    <ProgramReference>
      0000
      <Text>UNASSIGNED</Text>
    </ProgramReference>
    <ProgramReference>
      1207
      <Text>OBSERVATIONAL ASTRONOMY</Text>
    </ProgramReference>
    <ProgramReference>
      OTHR
      <Text>OTHER RESEARCH OR EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
<?php
namespace ltbapi\V2\Rest\Tag;

use Zend\Paginator\Paginator;

class TagCollection extends Paginator
{
}


text:
package org.camunda.bpm.engine.impl.migration.validation.activity;

import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;

/**
 * Check if an activity can be migrated. For example
 * if the activity type is supported by the migration.
 */
public interface MigrationActivityValidator {

  /**
   * Check that an activity can be migrated.
   *
   * @param activity the activity to migrate
   * @return true if the activity can be migrated, false otherwise
   */
  boolean valid(ActivityImpl activity);

}


text:
"""
Tests for the calendarserver.tap module.
"""


text:
package org.sakaiproject.gradebookng.tool.actions;

import com.fasterxml.jackson.databind.JsonNode;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.sakaiproject.gradebookng.business.GradebookNgBusinessService;
import org.sakaiproject.service.gradebook.shared.Assignment;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

abstract public class MoveAssignmentAction extends InjectableAction implements Serializable {

	private static final long serialVersionUID = 1L;

	@SpringBean(name = "org.sakaiproject.gradebookng.business.GradebookNgBusinessService")
	protected GradebookNgBusinessService businessService;

	public MoveAssignmentAction() {
	}

	/**
	 * Get the assignment's current sort index within its category. If this value is null in the database, best calculate this index from
	 * the assignments.
	 *
	 * @param assignmentId the id of the assignment
	 * @return the current sort index of the assignment within their category
	 */
	protected Integer calculateCurrentCategorizedSortOrder(final Long assignmentId) {
		final Assignment assignment = MoveAssignmentAction.this.businessService.getAssignment(assignmentId.longValue());
		Integer order = assignment.getCategorizedSortOrder();

		if (order == null) {
			// if no categorized order for assignment, calculate one based on the default sort order
			final List<Assignment> assignments = MoveAssignmentAction.this.businessService.getGradebookAssignments();
			final List<Long> assignmentIdsInCategory = assignments.stream()
					.filter(a -> (a.getCategoryId() != null) && a.getCategoryId().equals(assignment.getCategoryId()))
					.map(Assignment::getId)
					.collect(Collectors.toList());

			order = assignmentIdsInCategory.indexOf(assignmentId);
		}

		return order;
	}

}


text:
"use strict";

var fs = require( "fs" );
var os = require( "os" );
var path = require( "path" );
var util = require( "util" );

var winston = require( "winston" );

var Assert = require( "assertable" );
var Logger = winston.Logger;
var FileLogger = require( "./file_logger" );
var LogulusProxy = require( "./logulus_proxy" );

var modulePackage = require( "../package.json" );

/**
 * Singleton that exposes methods used in logging.
 * @type Object
 */
var Logulus = {};
module.exports = Logulus;

/**
 * Constant that defines the transports available.
 * @type {{CONSOLE: string, FILE: string}}
 */
Logulus.TRANSPORTS = {
    CONSOLE: "console",
    FILE: "file"
};

/**
 * Instance to the Winston logging service.
 * @type {Object}
 */
Logulus.logger = null;

/**
 * Initializes the Winston logging service using configuration file settings.
 * @private
 */
Logulus._init = function () {

    var transportDefinitions = Assert.setDefault(Logulus.config.transports,
        [
            {"type":"console", "name": "logulus-console", "colorize": true, "level": "debug", "handleExceptions": true, "silent": false},
            {"type":"file", "name": "logulus-file", "directory": "logs", "saveCount": 5, "level": "debug", "handleExceptions": true, "silent": false}
        ]
    );
    Logulus.config.transports = [];

    Logulus.config.configFilePath = Assert.setDefault(Logulus.configFilePath, path.resolve('.'));
    Logulus.config.baseName = Assert.setDefault( Logulus.config.baseName, "default" );
    Logulus.config.colors = Assert.setDefault( Logulus.config.colors, {debug: "white", info: "blue", warn: "yellow", error: "red"} );
    Logulus.config.excludeFilters = Assert.setDefault( Logulus.config.excludeFilters, [] );
    Logulus.config.exitOnError = Assert.setDefault( Logulus.config.exitOnError, false );
    Logulus.config.includeFilters = Assert.setDefault( Logulus.config.includeFilters, [{
        "pattern": "*",
        "levels": ["debug", "info", "warn", "error"]
    }] );
    Logulus.config.levels = Assert.setDefault( Logulus.config.levels, {debug: 0, info: 1, warn: 2, error: 3} );
    Logulus.config.showModule = Assert.setDefault( Logulus.config.showModule, true );
    Logulus.config.timestampSettings = Assert.setDefault( Logulus.timestampSettings, {
        includeDate: true,
        includeMilliseconds: true
    } );

    // Set defaults from the loaded config.

    // Instantiate the transports and set default values.
    if (Assert.isArray( transportDefinitions )) {

        transportDefinitions.forEach( function ( item ) {
            var transport = null;
            var transportConfig = {timestamp: Logulus.localTimestamp};
            var levelKeys = Object.keys( Logulus.config.levels );
            var minLevel = Number.MAX_VALUE;
            var minLevelName = null;
            levelKeys.forEach( function ( levelKey ) {
                if (Logulus.config.levels[levelKey] < minLevel) {
                    minLevel = Logulus.config.levels[levelKey];
                    minLevelName = levelKey;
                }
            } );

            switch (item.type) {
                case Logulus.TRANSPORTS.CONSOLE:
                    transportConfig.name = Assert.setDefault( item.name, 'logulus-console' );
                    transportConfig.level = Assert.setDefault( item.level, minLevelName );
                    transportConfig.levels =  Assert.setDefault( Logulus.config.levels, {debug: 0, info: 1, warn: 2, error: 3} );
                    transportConfig.colorize = Assert.setDefault( item.colorize, true );
                    transportConfig.handleExceptions = Assert.setDefault( item.handleExceptions, true );
                    transportConfig.silent = Assert.setDefault( item.silent, false );
                    transport = new winston.transports.Console( transportConfig );
                    break;

                case Logulus.TRANSPORTS.FILE:
                    transportConfig.name = Assert.setDefault( item.name, 'logulus-file' );;
                    if (Assert.isString(item.directory)) {
                        transportConfig.directory = path.resolve('.', item.directory);
                    } else {
                        transportConfig.directory = path.resolve('.');
                    }
                    transportConfig.level = Assert.setDefault( item.level, minLevelName );
                    transportConfig.levels =  Assert.setDefault( Logulus.config.levels, {debug: 0, info: 1, warn: 2, error: 3} );
                    transportConfig.handleExceptions = Assert.setDefault( item.handleExceptions, true );
                    transportConfig.silent = Assert.setDefault( item.silent, false );
                    transportConfig.saveCount = Assert.setDefault( item.saveCount, 3 );
                    transportConfig.baseName = Assert.setDefault(Logulus.config.baseName, 'logulus');
                    transport = new FileLogger( transportConfig );
                    break;

                default:
                    console.log( "" );
                    console.log( "Logulus: Unknown transport - " + item.type );
                    console.log( "" );
                    break;
            }
            Logulus.config.transports.push( transport );
        } );
    }

    Logulus.logger = new Logger( Logulus.config );

    // Dynamically generate message functions based on the levels defined.
    var levelKeys = Object.keys( Logulus.config.levels );
    levelKeys.forEach( function ( key ) {

        Logulus[key] = function ( message, moduleId, meta ) {
            if (Logulus.isAllowed( moduleId, key )) {
                meta = Assert.setDefault( meta, null );
                if (Logulus.logger) {
                    if (Logulus.config.showModule) {
                        message = util.format( "[%s] - %s", moduleId, message );
                    }
                    Logulus.logger.log( key, message, meta );
                }
            }
        };

    } );

};

/**
 * Loads the config file based on environment variable.
 * @returns {String}
 * @private
 */
Logulus._loadEnvironmentConfig = function () {

    var result = null;
    var configPath;

    try {
        configPath = path.resolve( ".", process.env.LOGULUS_CONFIG );
    } catch (error) {
        configPath = undefined;
    }

    // Read from the environment variable.
    if (configPath && fs.existsSync( configPath )) {
        try {
            Logulus.config = JSON.parse( fs.readFileSync( configPath, "utf8" ) );
            result = configPath;
        } catch (error) {
            console.log( "" );
            console.log( "Logulus: Unable to read environment configuration file." );
            console.log( "" );
        }
    }
    return result;
};

/**
 * Loads the config file based on the package version (looks for -alpha, -beta, and -rc).
 * @returns {String}
 * @private
 */
Logulus._loadTestingConfig = function () {

    var result = null;
    var configPath;

    try {
        if (modulePackage.version.match( /-alpha/g ) || modulePackage.version.match( /-beta/g ) || modulePackage.version.match( /-rc/ )) {
            configPath = path.resolve( ".", "testing.json" );
        }
    } catch (error) {
        configPath = undefined;
    }

    // Read from a testing file.
    if (configPath && fs.existsSync( configPath )) {
        try {
            Logulus.config = JSON.parse( fs.readFileSync( configPath, "utf8" ) );
            result = configPath;
        } catch (error) {
            console.log( "" );
            console.log( "Logulus: Unable to read the testing configuration file." );
            console.log( "" );
        }
    }
    return result;
};

/**
 * Loads the config file based on the host name.
 * @returns {String}
 * @private
 */
Logulus._loadHostConfig = function () {

    var result = null;
    var configPath;

    try {
        configPath = path.resolve( ".", util.format( "logulus.%s.json", os.hostname() ) );
    } catch (error) {
        configPath = null;
    }

    // Read from a host file.
    if (configPath && fs.existsSync( configPath )) {
        try {
            Logulus.config = JSON.parse( fs.readFileSync( configPath, "utf8" ) );
            result = configPath;
        } catch (error) {
            console.log( "" );
            console.log( "Logulus: Unable to read the host configuration file." );
            console.log( "" );
        }
    }

    return result;

};

/**
 * Loads the default config file.
 * @returns {String}
 * @private
 */
Logulus._loadDefaultConfig = function () {

    var result = null;
    var configPath;

    try {
        configPath = path.resolve( __dirname, util.format( "../defaults.json" ) );
    } catch (error) {
        configPath = undefined;
    }

    // Read from the default file.
    if (configPath && fs.existsSync( configPath )) {
        try {
            Logulus.config = JSON.parse( fs.readFileSync( configPath, "utf8" ) );
            result = configPath;
        } catch (error) {
            console.log( "" );
            console.log( "Logulus: Unable to read the default configuration file." );
            console.log( "" );
        }
    }
    return result;

};

/**
 * Loads the appropriate configuration file; called automatically on instantiation.
 * @private
 */
Logulus._loadConfig = function () {

    var configFilePath = null;

    configFilePath = Logulus._loadEnvironmentConfig();
    if (configFilePath) {
        console.log( "" );
        console.log('Logulus is using LOGULUS_CONFIG environment config: ' + configFilePath);
        console.log( "" );
    }
    if (!configFilePath) {
        configFilePath = Logulus._loadHostConfig();
        if (configFilePath) {
            console.log( "" );
            console.log('Logulus is using host file config: ' + configFilePath);
            console.log( "" );
        }
    }
    if (!configFilePath) {
        configFilePath = Logulus._loadTestingConfig();
        if (configFilePath) {
            console.log( "" );
            console.log('Logulus is using testing file config: ' + configFilePath);
            console.log( "" );
        }
    }
    if (!configFilePath) {
        Logulus.config = {};
        console.log( "" );
        console.log('Logulus is using default settings.');
        console.log( "" );
    }

    // Ensure default settings.
    Logulus._init();
};

/**
 * Creates a Winston proxy that manages which messages are sent.
 * @param {String} moduleId The path id of the module.
 * @returns {LogulusProxy}
 */
Logulus.create = function ( moduleId ) {
    Assert.string( moduleId );
    return new LogulusProxy( moduleId, Logulus, winston );
};

/**
 * Flag that indicates whether the message should be sent to the logger.
 * @param {String} moduleId The path id of the module.
 * @param {String} level The level name.
 * @returns Boolean
 */
Logulus.isAllowed = function ( moduleId, level ) {

    Assert.string( moduleId );

    var result = false, includeAll = false;

    Logulus.config.includeFilters.some( function ( filter ) {
        if (filter.levels.indexOf( level ) >= 0 && (filter.pattern === "*" || moduleId.match( new RegExp( filter.pattern, "g" ) ))) {
            if (filter.pattern === "*") {
                includeAll = true;
            }
            result = true;
            return true;
        }
        return false;
    } );

    if (includeAll) {
        Logulus.config.excludeFilters.some( function ( filter ) {
            if (filter.levels.indexOf( level ) >= 0 && moduleId.match( new RegExp( filter.pattern, "g" ) )) {
                result = false;
                return true;
            }
            return false;
        } );
    }

    return result;
};

/**
 * Returns a timestamp string for the given date value, or for the current time if no date is given.
 * @param {Date} date Optional date value; defaults to now.
 * @return {String}
 */
Logulus.localTimestamp = function ( date ) {

    date = Assert.setDefault( date, new Date() );

    var result = date.toLocaleTimeString( 'en-US', {hour12: false} );

    if (Logulus.config.timestampSettings) {
        if (Logulus.config.timestampSettings.includeDate) {
            result = util.format( "%s-%s-%s %s", date.getFullYear(), String( "0" + (date.getMonth() + 1) ).slice( -2 ), ("0" + date.getDate()).slice( -2 ), result );
        }
        if (Logulus.config.timestampSettings.includeMilliseconds) {
            result = util.format( "%s.%s", result, ("000" + date.getMilliseconds()).slice( -3 ) );
        }
    }
    return result;
};

// Load the configuration
Logulus._loadConfig();


text:
require 'chef/json_compat'
require 'chef/node'

class Chef
  class Knife
    class NodeEditor

      attr_reader :node
      attr_reader :ui
      attr_reader :config

      def initialize(node, ui, config)
        @node, @ui, @config = node, ui, config
      end

      def edit_node
        abort "You specified the --disable_editing option, nothing to edit" if config[:disable_editing]
        assert_editor_set!

        updated_node_data = edit_data(view)
        apply_updates(updated_node_data)
        @updated_node
      end

      def view
        result = {}
        result["name"] = node.name
        result["chef_environment"] = node.chef_environment
        result["normal"] = node.normal_attrs
        result["run_list"] = node.run_list

        if config[:all_attributes]
          result["default"]   = node.default_attrs
          result["override"]  = node.override_attrs
          result["automatic"] = node.automatic_attrs
        end
        Chef::JSONCompat.to_json_pretty(result)
      end

      def edit_data(text)
        edited_data = tempfile_for(text) {|filename| system("#{config[:editor]} #{filename}")}
        Chef::JSONCompat.from_json(edited_data)
      end

      def apply_updates(updated_data)
        if node.name and node.name != updated_data["name"]
          ui.warn "Changing the name of a node results in a new node being created, #{node.name} will not be modified or removed."
          confirm = ui.confirm "Proceed with creation of new node"
        end

        @updated_node = Node.new.tap do |n|
          n.name( updated_data["name"] )
          n.chef_environment( updated_data["chef_environment"] )
          n.run_list( updated_data["run_list"])
          n.normal_attrs = updated_data["normal"]

          if config[:all_attributes]
            n.default_attrs   = updated_data["default"]
            n.override_attrs  = updated_data["override"]
            n.automatic_attrs = updated_data["automatic"]
          else
            n.default_attrs   = node.default_attrs
            n.override_attrs  = node.override_attrs
            n.automatic_attrs = node.automatic_attrs
          end
        end
      end

      def updated?
        pristine_copy = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(node), :create_additions => false)
        updated_copy  = Chef::JSONCompat.from_json(Chef::JSONCompat.to_json(@updated_node), :create_additions => false)
        unless pristine_copy == updated_copy
          updated_properties = %w{name normal chef_environment run_list default override automatic}.reject do |key|
             pristine_copy[key] == updated_copy[key]
          end
        end
        ( pristine_copy != updated_copy ) && updated_properties
      end

      private

      def abort(message)
        ui.error(message)
        exit 1
      end

      def assert_editor_set!
        unless config[:editor]
          abort "You must set your EDITOR environment variable or configure your editor via knife.rb"
        end
      end

      def tempfile_for(data)
        # TODO: include useful info like the node name in the temp file
        # name
        basename = "knife-edit-" << rand(1_000_000_000_000_000).to_s.rjust(15, '0') << '.js'
        filename = File.join(Dir.tmpdir, basename)
        File.open(filename, "w+") do |f|
          f.sync = true
          f.puts data
        end

        yield filename

        IO.read(filename)
      ensure
        File.unlink(filename)
      end
    end
  end
end


text:
#ifndef CTIGLFUSEPLANE_H
#define CTIGLFUSEPLANE_H

#include "CNamedShape.h"
#include "ListPNamedShape.h"

namespace tigl
{

class CCPACSConfiguration;
class CTiglAbstractPhysicalComponent;

enum TiglFuseResultMode
{
    HALF_PLANE = 0,
    FULL_PLANE = 1,
    HALF_PLANE_TRIMMED_FF = 2,
    FULL_PLANE_TRIMMED_FF = 3
};

class CTiglFusePlane
{
public:
    TIGL_EXPORT CTiglFusePlane(CCPACSConfiguration& config);

    // sets mode for plane generation, by default a half plane is created
    TIGL_EXPORT void SetResultMode(TiglFuseResultMode mode);

    TIGL_EXPORT const PNamedShape FusedPlane();
    TIGL_EXPORT const PNamedShape FarField();
    TIGL_EXPORT const ListPNamedShape& Intersections();

private:
    PNamedShape FuseWithChilds(CTiglAbstractPhysicalComponent* parent);

    void Invalidate();
    void Perform();

    PNamedShape          _result;         /**< contains the result of the fusing operation >**/
    ListPNamedShape      _intersections;  /**< contains the shape shape intersections >**/
    PNamedShape          _farfield;       /**< contains the farfield if available >**/
    CCPACSConfiguration& _myconfig;       /**< Ref to CPACS config >**/
    TiglFuseResultMode    _mymode;
    bool _hasPerformed;
};

} // namespace tigl

#endif // CTIGLFUSEPLANE_H