text:
package edu.ucsb.cs56.w15.drawings.sadykoff.advanced;
import java.awt.geom.GeneralPath; // combinations of lines and curves
import java.awt.geom.AffineTransform; // translation, rotation, scale
import java.awt.Shape; // general class for shapes

// all imports below this line needed if you are implementing Shape
import java.awt.geom.Point2D;
import java.awt.geom.Line2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.PathIterator;
import java.awt.geom.AffineTransform;
import java.lang.Math;

import edu.ucsb.cs56.w15.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w15.drawings.utilities.GeneralPathWrapper;
/**
   A Pizza with Pepperoni

   @author Boris Sadykoff
   @version for CS56, W15, UCSB, 02/12/2015

*/
public class PepperoniPizza extends Pizza implements Shape
{
    /**
     * Constructor for objects of class Pizza
     */
    public PepperoniPizza(double x, double y, double radius)
    {
	// construct the basic house shell
	super(x,y,radius);

	// get the GeneralPath that we are going to append stuff to
	GeneralPath gp = this.get();

	// Add a pepperoni per slice
	//
	// radius of the pepperonis will be 1/5 of the radius

	Ellipse2D.Double pepOne = new Ellipse2D.Double(x + .6*radius*Math.cos(Math.toRadians(22.5)),
				   y + .6*radius*Math.sin(Math.toRadians(22.5)),
						       radius/4,radius/4);

	Ellipse2D.Double pepTwo = new Ellipse2D.Double(x + .6*radius*Math.cos(Math.toRadians(67.5)),
				   y + .6*radius*Math.sin(Math.toRadians(67.5)),
						       radius/4,radius/4);

	Ellipse2D.Double pepThree = new Ellipse2D.Double(x + .9*radius*Math.cos(Math.toRadians(112.5)),
				     y + .6*radius*Math.sin(Math.toRadians(112.5)),
							 radius/4,radius/4);

	Ellipse2D.Double pepFour = new Ellipse2D.Double(x + .8*radius*Math.cos(Math.toRadians(157.5)),
				    y + .6*radius*Math.sin(Math.toRadians(157.5)),
							radius/4,radius/4);

	Ellipse2D.Double pepFive = new Ellipse2D.Double(x + .75*radius*Math.cos(Math.toRadians(202.5)),
				    y + .8*radius*Math.sin(Math.toRadians(202.5)),
							radius/4,radius/4);

	Ellipse2D.Double pepSix = new Ellipse2D.Double(x + .9*radius*Math.cos(Math.toRadians(247.5)),
				   y + .75*radius*Math.sin(Math.toRadians(247.5)),
						       radius/4,radius/4);

	Ellipse2D.Double pepSeven = new Ellipse2D.Double(x + .5*radius*Math.cos(Math.toRadians(292.5)),
				     y + .75*radius*Math.sin(Math.toRadians(292.5)),
							 radius/4,radius/4);

	Ellipse2D.Double pepEight = new Ellipse2D.Double(x + .6*radius*Math.cos(Math.toRadians(337.5)),
				     y + .8*radius*Math.sin(Math.toRadians(337.5)),
							 radius/4,radius/4);

	// add the pepperonis to the pizza

        GeneralPath wholePizza = this.get();
        wholePizza.append(pepOne, false);
	wholePizza.append(pepTwo, false);
	wholePizza.append(pepThree, false);
	wholePizza.append(pepFour, false);
	wholePizza.append(pepFive, false);
	wholePizza.append(pepSix, false);
	wholePizza.append(pepSeven, false);
	wholePizza.append(pepEight, false);
    }

}


text:
cask "gitfox" do
  version "2.8.5,7239"
  sha256 "9a59dc20a0933fd4a8209575d5c28c9bb21a99ec429e7209e076985cbc36e39b"

  url "https://storage.googleapis.com/gitfox/builds/retail/#{version.csv.second}/Gitfox.#{version.csv.second}.zip",
      verified: "storage.googleapis.com/gitfox/"
  name "Gitfox"
  desc "Git client"
  homepage "https://www.gitfox.app/"

  livecheck do
    url "https://storage.googleapis.com/gitfox/Gitfox.latest.stable.zip"
    strategy :extract_plist
  end

  auto_updates true
  depends_on macos: ">= :big_sur"

  app "Gitfox.app"
  binary "#{appdir}/Gitfox.app/Contents/SharedSupport/bin/gitfox-cli", target: "gitfox"

  zap trash: [
    "~/Library/Application Support/com.bytieful.Gitfox",
    "~/Library/Application Support/com.bytieful.Gitfox-retail",
    "~/Library/Application Support/Gitfox",
    "~/Library/Caches/com.bytieful.Gitfox",
    "~/Library/Caches/com.bytieful.Gitfox-retail",
    "~/Library/Caches/com.crashlytics.data/com.bytieful.Gitfox",
    "~/Library/Preferences/com.bytieful.Gitfox.*",
    "~/Library/Preferences/com.bytieful.Gitfox-retail.plist",
    "~/Library/Saved Application State/com.bytieful.Gitfox-retail.savedState",
    "~/Library/WebKit/com.bytieful.Gitfox",
  ]
end

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * @file
 * Contains \Drupal\content_translation\Tests\Views\TranslationLinkTest.
 */

namespace Drupal\content_translation\Tests\Views;

use Drupal\content_translation\Tests\ContentTranslationTestBase;
use Drupal\views\Tests\ViewTestData;
use Drupal\Core\Language\Language;
use Drupal\user\Entity\User;

/**
 * Tests the content translation overview link field handler.
 *
 * @group content_translation
 * @see \Drupal\content_translation\Plugin\views\field\TranslationLink
 */
class TranslationLinkTest extends ContentTranslationTestBase {

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = array('test_entity_translations_link');

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('content_translation_test_views');

  protected function setUp() {
    // @todo Use entity_type once it is has multilingual Views integration.
    $this->entityTypeId = 'user';

    parent::setUp();

    // Assign user 1  a language code so that the entity can be translated.
    $user = User::load(1);
    $user->langcode = 'en';
    $user->save();

    // Assign user 2 LANGCODE_NOT_SPECIFIED code so entity can't be translated.
    $user = User::load(2);
    $user->langcode = Language::LANGCODE_NOT_SPECIFIED;
    $user->save();

    ViewTestData::createTestViews(get_class($this), array('content_translation_test_views'));
  }

  /**
   * {@inheritdoc}
   */
  protected function getTranslatorPermissions() {
    $permissions = parent::getTranslatorPermissions();
    $permissions[] = 'access user profiles';
    return $permissions;
  }

  /**
   * Tests the content translation overview link field handler.
   */
  public function testTranslationLink() {
    $this->drupalGet('test-entity-translations-link');
    $this->assertLinkByHref('user/1/translations');
    $this->assertNoLinkByHref('user/2/translations', 'The translations link is not present when content_translation_translate_access() is FALSE.');
  }

}


text:
With those few steps you can install *LUYA* on your Webserver. To install *LUYA* you have to install [Composer](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx) on your Mac, Unix or Windows System.

> We have made an [installation Video on Youtube](https://www.youtube.com/watch?v=7StCJviSGkg) in order to help you install LUYA.

First of all you have to install the global `fxp/composer-asset-plugin` plugin, which is required by Yii to install bower packages via composer. To global install the plugin open your Terminal and run the following code:

```sh
composer global require "fxp/composer-asset-plugin:~1.3"
```

After setting up composer, we execute the composer `create-project` command to checkout the **luya-kickstarter** application, an *out of the box* setup enabling you to directly run your website. We recommend to run the `create-project` command directly from your htdocs/webserver folder:

```sh
composer create-project luyadev/luya-kickstarter:1.0.0-RC3
```

> Note: During the installation Composer may ask for your Github login credentials. This is normal because Composer needs to get enough API rate-limit to retrieve the dependent package information from Github. For more details, please refer to the [Composer documentation](https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens).

The `create-project` command will create a folder (inside of your current folder where the `composer create-project` command was execute) named **luya-kickstarter**. After the command is finished go into the **configs** folder inside the application and copy the dist template files to original php files.

```sh
cp env.php.dist env.php
cp env-local-db.php.dist env-local-db.php
```

Now change the database connection inside the `configs/env-local-db.php` file to fit your mysql servers configuration. You should open all config files once to change values and understand the behavior. In order to understand the config files read more in the [environemnt configs section](install-configs.md). After successfully setting up your database connection, you have to reopen your Terminal and change into your project directory and excute the **luya** binary files which has been installed into your vendor folder by composer as described in the follwing.

Run the migration files with the [migrate console command](luya-console.md):

> Note: If the migration process failed, try to replace localhost with 127.0.0.1 in the database DNS configuration `(env-local-db.php)` which is located in the  configs folder.

```sh
./vendor/bin/luya migrate
```

Build and import all filesystem configurations into the database with the [import console command](luya-console.md):

```sh
./vendor/bin/luya import
```

At last we execute the [setup console command](luya-console.md) which is going to setup a user, group and permissions:

```sh
./vendor/bin/luya admin/setup
```

The setup proccess will ask you for an email and password to store your personal login data inside the database (of course the password will be encrypted).

> `./vendor/bin/luya health` will make a small check if several directories exist and readable/writable.

You can now log in into your administration interface `http://localhost/luya-kickstarter/admin` (depending on where you have located the LUYA files).

> Visit the [Installation Problems and Questions Site](install-problems.md) when you have any problems with the LUYA Setup.


text:
(function () {
    "use strict";

//   angular.module('scotchTodo', ['todoController', 'todoService']);

console.log('running app.js');
    var app = angular.module("scotchTodo",
                            ["common.services"
                            , "ui.router" ,'todoController', 'todoService'
                             ]); //setter method has [] to hold parameters

    app.config(["$stateProvider", "$urlRouterProvider",
            function ($stateProvider, $urlRouterProvider) {
                $urlRouterProvider.otherwise("/");

                $stateProvider
                        .state("home_state", {
                            url: "/",
                            templateUrl: "ticketListView.html"
                        })

                        //Products
                        .state("productList_state", {
                            url: "/products",
                            templateUrl: "productListView.html",
                            controller: "ProductListCtrl as vm"
                        })

                        //Tickets
                        .state("ticketList_state", {
                            url: "/tickets",
                            templateUrl: "ticketListView.html",
                            controller: "TicketListCtrl as vm"
                        })

                        //Detail
                        .state("ticketDetail_state", {
                            url: "/tickets/:id",
                            templateUrl: "ticketDetailView.html",
                            controller: "TicketDetailCtrl as vm",
                            resolve: {
                                ticketResource: "ticketResource",
                                ticket: function (ticketResource, $stateParams) {
                                    var id = $stateParams.id;
                                     console.log('trying ticketResource -- id from $stateParam is:' + id);
                                    return ticketResource.get({ id: id }).$promise; //get method returns a single item. note query seems to work with real data and get works with mock

                                }
                            }
                        })

                    }
            ])

}());


text:
<?php

/**
 * This class adds structure of 'spy_form_builder_fields' table to 'propel' DatabaseMap object.
 *
 *
 * This class was autogenerated by Propel 1.3.0-dev on:
 *
 * 11/26/09 11:06:06
 *
 *
 * These statically-built map classes are used by Propel to do runtime db structure discovery.
 * For example, the createSelectSql() method checks the type of a given column used in an
 * ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
 * (i.e. if it's a text column type).
 *
 * @package    plugins.spyFormBuilderInterface2Plugin.lib.model.map
 */
class SpyFormBuilderFieldsMapBuilder implements MapBuilder {

	/**
	 * The (dot-path) name of this class
	 */
	const CLASS_NAME = 'plugins.spyFormBuilderInterface2Plugin.lib.model.map.SpyFormBuilderFieldsMapBuilder';

	/**
	 * The database map.
	 */
	private $dbMap;

	/**
	 * Tells us if this DatabaseMapBuilder is built so that we
	 * don't have to re-build it every time.
	 *
	 * @return     boolean true if this DatabaseMapBuilder is built, false otherwise.
	 */
	public function isBuilt()
	{
		return ($this->dbMap !== null);
	}

	/**
	 * Gets the databasemap this map builder built.
	 *
	 * @return     the databasemap
	 */
	public function getDatabaseMap()
	{
		return $this->dbMap;
	}

	/**
	 * The doBuild() method builds the DatabaseMap
	 *
	 * @return     void
	 * @throws     PropelException
	 */
	public function doBuild()
	{
		$this->dbMap = Propel::getDatabaseMap(SpyFormBuilderFieldsPeer::DATABASE_NAME);

		$tMap = $this->dbMap->addTable(SpyFormBuilderFieldsPeer::TABLE_NAME);
		$tMap->setPhpName('SpyFormBuilderFields');
		$tMap->setClassname('SpyFormBuilderFields');

		$tMap->setUseIdGenerator(true);

		$tMap->addPrimaryKey('ID', 'Id', 'INTEGER', true, null);

		$tMap->addColumn('WIDGET_TYPE', 'WidgetType', 'VARCHAR', true, 255);

		$tMap->addColumn('LABEL', 'Label', 'VARCHAR', false, 255);

		$tMap->addColumn('NAME', 'Name', 'VARCHAR', true, 255);

		$tMap->addColumn('HELP', 'Help', 'VARCHAR', false, 255);

		$tMap->addColumn('WIDGET_PARAMS', 'WidgetParams', 'LONGVARCHAR', false, null);

		$tMap->addColumn('HIDE_ON_EDIT', 'HideOnEdit', 'LONGVARCHAR', false, null);

		$tMap->addColumn('ONLY_FOR', 'OnlyFor', 'LONGVARCHAR', false, null);

		$tMap->addForeignKey('FORM_ID', 'FormId', 'INTEGER', 'spy_form_builder', 'ID', true, null);

		$tMap->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null);

		$tMap->addColumn('RANK', 'Rank', 'INTEGER', true, null);

	} // doBuild()

} // SpyFormBuilderFieldsMapBuilder


text:
Given students' names along with the grade that they are in, create a roster
for the school.

In the end, you should be able to:

- Add a student's name to the roster for a grade
  - "Add Jim to grade 2."
  - "OK."
- Get a list of all students enrolled in a grade
  - "Which students are in grade 2?"
  - "We've only got Jim just now."
- Get a sorted list of all students in all grades.  Grades should sort
  as 1, 2, 3, etc., and students within a grade should be sorted
  alphabetically by name.
  - "Who all is enrolled in school right now?"
  - "Grade 1: Anna, Barb, and Charlie. Grade 2: Alex, Peter, and Zoe.
    Grade 3…"

Note that all our students only have one name.  (It's a small town, what
do you want?)

## For bonus points

Did you get the tests passing and the code clean? If you want to, these
are some additional things you could try:

- If you're working in a language with mutable data structures and your
  implementation allows outside code to mutate the school's internal DB
  directly, see if you can prevent this. Feel free to introduce additional
  tests.

Then please share your thoughts in a comment on the submission. Did this
experiment make the code better? Worse? Did you learn anything from it?

## Setup

Go through the setup instructions for JavaScript to install the
 necessary dependencies:

http://exercism.io/languages/javascript/installation

## Running the test suite

The provided test suite uses [Jasmine](https://jasmine.github.io/).
You can install it by opening a terminal window and running the
following command:

```sh
npm install -g jasmine
```

Run the test suite from the exercise directory with:

```sh
jasmine grade-school.spec.js
```

In many test suites all but the first test have been marked "pending".
Once you get a test passing, activate the next one by changing `xit` to `it`.

## Source

A pairing session with Phil Battos at gSchool [http://gschool.it](http://gschool.it)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
#if !defined(Q_OS_SYMBIAN) || (defined(Q_OS_SYMBIAN) && !defined(Q_CC_RVCT))

#include "qplatformdefs.h"

#include <QtCore/qatomic.h>

QT_BEGIN_NAMESPACE
static pthread_mutex_t qAtomicMutex = PTHREAD_MUTEX_INITIALIZER;

Q_CORE_EXPORT
bool QBasicAtomicInt_testAndSetOrdered(volatile int *_q_value, int expectedValue, int newValue)
{
    bool returnValue = false;
    pthread_mutex_lock(&qAtomicMutex);
    if (*_q_value == expectedValue) {
        *_q_value = newValue;
        returnValue = true;
    }
    pthread_mutex_unlock(&qAtomicMutex);
    return returnValue;
}

Q_CORE_EXPORT
int QBasicAtomicInt_fetchAndStoreOrdered(volatile int *_q_value, int newValue)
{
    int returnValue;
    pthread_mutex_lock(&qAtomicMutex);
    returnValue = *_q_value;
    *_q_value = newValue;
    pthread_mutex_unlock(&qAtomicMutex);
    return returnValue;
}

Q_CORE_EXPORT
int QBasicAtomicInt_fetchAndAddOrdered(volatile int *_q_value, int valueToAdd)
{
    int returnValue;
    pthread_mutex_lock(&qAtomicMutex);
    returnValue = *_q_value;
    *_q_value += valueToAdd;
    pthread_mutex_unlock(&qAtomicMutex);
    return returnValue;
}

Q_CORE_EXPORT
bool QBasicAtomicPointer_testAndSetOrdered(void * volatile *_q_value,
                                           void *expectedValue,
                                           void *newValue)
{
    bool returnValue = false;
    pthread_mutex_lock(&qAtomicMutex);
    if (*_q_value == expectedValue) {
        *_q_value = newValue;
        returnValue = true;
    }
    pthread_mutex_unlock(&qAtomicMutex);
    return returnValue;
}

Q_CORE_EXPORT
void *QBasicAtomicPointer_fetchAndStoreOrdered(void * volatile *_q_value, void *newValue)
{
    void *returnValue;
    pthread_mutex_lock(&qAtomicMutex);
    returnValue = *_q_value;
    *_q_value = newValue;
    pthread_mutex_unlock(&qAtomicMutex);
    return returnValue;
}

Q_CORE_EXPORT
void *QBasicAtomicPointer_fetchAndAddOrdered(void * volatile *_q_value, qptrdiff valueToAdd)
{
    void *returnValue;
    pthread_mutex_lock(&qAtomicMutex);
    returnValue = *_q_value;
    *_q_value = reinterpret_cast<char *>(returnValue) + valueToAdd;
    pthread_mutex_unlock(&qAtomicMutex);
    return returnValue;
}
QT_END_NAMESPACE
#endif //!defined(Q_OS_SYMBIAN) && !defined(Q_CC_RVCT)


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/compute/v1/compute.proto

namespace Google\Cloud\Compute\V1\InterconnectAttachment;

use UnexpectedValueException;

/**
 * [Output Only] The current status of whether or not this interconnect attachment is functional, which can take one of the following values: - OS_ACTIVE: The attachment has been turned up and is ready to use. - OS_UNPROVISIONED: The attachment is not ready to use yet, because turnup is not complete.
 *
 * Protobuf type google.cloud.compute.v1.InterconnectAttachment.OperationalStatus
 */
class OperationalStatus
{
    /**
     * A value indicating that the enum field is not set.
     *
     * Generated from protobuf enum UNDEFINED_OPERATIONAL_STATUS = 0;
     */
    const UNDEFINED_OPERATIONAL_STATUS = 0;
    /**
     * Indicates that attachment has been turned up and is ready to use.
     *
     * Generated from protobuf enum OS_ACTIVE = 55721409;
     */
    const OS_ACTIVE = 55721409;
    /**
     * Indicates that attachment is not ready to use yet, because turnup is not complete.
     *
     * Generated from protobuf enum OS_UNPROVISIONED = 239771840;
     */
    const OS_UNPROVISIONED = 239771840;

    private static $valueToName = [
        self::UNDEFINED_OPERATIONAL_STATUS => 'UNDEFINED_OPERATIONAL_STATUS',
        self::OS_ACTIVE => 'OS_ACTIVE',
        self::OS_UNPROVISIONED => 'OS_UNPROVISIONED',
    ];

    public static function name($value)
    {
        if (!isset(self::$valueToName[$value])) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no name defined for value %s', __CLASS__, $value));
        }
        return self::$valueToName[$value];
    }

    public static function value($name)
    {
        $const = __CLASS__ . '::' . strtoupper($name);
        if (!defined($const)) {
            throw new UnexpectedValueException(sprintf(
                    'Enum %s has no value defined for name %s', __CLASS__, $name));
        }
        return constant($const);
    }
}


text:
package com.obtuse.util.gowing;

import com.obtuse.exceptions.HowDidWeGetHereError;
import com.obtuse.util.ObtuseUtil;
import com.obtuse.util.gowing.p2a.GowingEntityReference;
import com.obtuse.util.gowing.p2a.GowingUtil;
import com.obtuse.util.gowing.p2a.holders.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.*;

/**
 Carry around a key-value pair in a packable format.
 */

@SuppressWarnings("unchecked")
public class GowingPackableKeyValuePair<K, V> extends GowingAbstractPackableEntity {

    private static final EntityTypeName ENTITY_TYPE_NAME = new EntityTypeName( GowingPackableKeyValuePair.class );
    private static final int VERSION = 1;

    private static final EntityName KEY_FIELD_NAME = new EntityName( "_k" );
    private static final EntityName VALUE_FIELD_NAME = new EntityName( "_v" );

    private K _key;
    private Object _keyReference;
    private V _value;
    private Object _valueReference;

    private boolean _keyAndValueResolved = false;

    public static final GowingEntityFactory FACTORY = new GowingEntityFactory( ENTITY_TYPE_NAME ) {

        @Override
        public int getOldestSupportedVersion() {

            return VERSION;
        }

        @Override
        public int getNewestSupportedVersion() {

            return VERSION;
        }

        @Override
        @NotNull
        public GowingPackable createEntity(
                final @NotNull GowingUnPacker unPacker,
                final @NotNull GowingPackedEntityBundle bundle,
                final @NotNull GowingEntityReference er
        ) {

            return new GowingPackableKeyValuePair( unPacker, bundle, er );

        }

    };

    public GowingPackableKeyValuePair( final K key, final V value ) {

        super( new GowingNameMarkerThing() );

        _key = key;
        _value = value;

        if ( value instanceof Optional ) {

            throw new HowDidWeGetHereError( "huh1?" );

        }

        if ( !isObjectsClassSupported( key ) ) {

            throw new IllegalArgumentException( "GowingPackableKeyValuePair:  key objects of class " + key.getClass() + " are not supported" );

        }
        if ( !isObjectsClassSupported( value ) ) {

            throw new IllegalArgumentException( "GowingPackableKeyValuePair:  value objects of class " + value.getClass() + " are not supported" );

        }

    }

    public GowingPackableKeyValuePair(
            final GowingUnPacker unPacker,
            final @NotNull GowingPackedEntityBundle bundle,
            @SuppressWarnings("unused") final GowingEntityReference er
    ) {

        super( unPacker, bundle.getSuperBundle() );

        _keyReference = bundle.getNotNullField( KEY_FIELD_NAME ).getObjectValue();
        _valueReference = bundle.getNotNullField( VALUE_FIELD_NAME ).getObjectValue();

    }

    public K getKey() {

        return _key;

    }

    public V getValue() {

        return _value;

    }

    @NotNull
    @Override
    public GowingPackedEntityBundle bundleThyself( final boolean isPackingSuper, final @NotNull GowingPacker packer ) {

        GowingPackedEntityBundle bundle = new GowingPackedEntityBundle(
                ENTITY_TYPE_NAME,
                VERSION,
                // super.bundleThyself( true, packer ),
                super.bundleRoot( packer ),
                packer.getPackingContext()
        );

        packObj( bundle, KEY_FIELD_NAME, _key, packer, true );
        packObj( bundle, VALUE_FIELD_NAME, _value, packer, true );

        return bundle;

    }

    @Override
    public boolean finishUnpacking( final @NotNull GowingUnPacker unPacker ) {

        // A bit of careful processing of the value reference.
        // If _valueReference is null then either
        // (1) the value is null and we can just leave _value as null or
        // (2) we have already dealt with the value reference and set _valueReference to null below
        //
        // Consequently, we can use the nullity of _valueReference as a safe gate into the code that
        // actually ensures that _value has the correct value.

        // Our ability to resolve either _key or _value does not depend upon either _keyReference or _valueReference being finished.
        //
        // Once both _key and _value have been resolved, we can declare ourselves finished as soon as our key is finished since
        // a finished _key is all that is needed to rebuild a table of key->value mappings.
        //
        // Lastly, our ability to handle circular references relies on us not needing our _value to be finished before we declare
        // ourselves finished.

        // So . . .

        // Step one is to resolve _key and _value (we only do this on the first call to this method).

        if ( !_keyAndValueResolved ) {

            _key = (K)GowingUtil.fetchActualValue( unPacker, _keyReference );
            if ( _valueReference instanceof Optional ) {

                throw new HowDidWeGetHereError( "huh2?" );

            }
            _value = (V)GowingUtil.fetchActualValue( unPacker, _valueReference );

            _keyAndValueResolved = true;

        }

        // Step two is to decide if we are finished. We decide that entirely by checking if _keyReference is finished.
        // See longer comment above for why this is a necessary check and must be a sufficient check.

        //noinspection RedundantIfStatement
        if ( _keyReference instanceof GowingEntityReference && !unPacker.isEntityFinished( (GowingEntityReference)_keyReference ) ) {

            return false;

        }

        return true;

    }

    private interface HolderFactory {

        GowingAbstractPackableHolder constructHolder( EntityName name, Object obj, GowingPacker packer );

    }

    /**
     The holder factories for the standard Java classes and a few of the built-in Gowing classes.

This mapping is unmodifiable once created.

     */

    private static final SortedMap<String, HolderFactory> STANDARD_JAVA_CLASS_HOLDER_FACTORIES;

    static {

        SortedMap<String,HolderFactory> factories = new TreeMap<>();
        factories.put(
                String.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingStringHolder( name, (String)obj, true )
        );

        factories.put(
                File.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingFileHolder( name, (File)obj, true )
        );

        factories.put(
                Byte.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingByteHolder( name, (Byte)obj, true )
        );

        factories.put(
                Short.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingShortHolder( name, (Short)obj, true )
        );

        factories.put(
                Integer.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingIntegerHolder( name, (Integer)obj, true )
        );

        factories.put(
                Long.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingLongHolder( name, (Long)obj, true )
        );

        factories.put(
                Float.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingFloatHolder( name, (Float)obj, true )
        );

        factories.put(
                Double.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingDoubleHolder( name, (Double)obj, true )
        );

        factories.put(
                Boolean.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingBooleanHolder( name, (Boolean)obj, true )
        );

        factories.put(
                EntityName.class.getCanonicalName(),
                ( name, obj, packer ) -> new GowingEntityNameHolder( name, (EntityName)obj, true )
        );

        STANDARD_JAVA_CLASS_HOLDER_FACTORIES = Collections.unmodifiableSortedMap( factories );

    }

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    public static boolean isObjectsClassSupported( @Nullable final Object obj ) {

        return isObjectsClassSupported( obj, new HashSet<>() );

    }

    private static boolean isObjectsClassSupported( Object obj, HashSet<Object> whatWeveSeen ) {

        if ( obj instanceof String ) {

            ObtuseUtil.doNothing();

        }

        if ( obj == null || whatWeveSeen.contains( obj ) ) {

            return true;

        }

        if ( obj instanceof File ) {

            ObtuseUtil.doNothing();

        }

        whatWeveSeen.add( obj );

        final boolean rval;

        String className = obj.getClass().getCanonicalName();
        if ( obj instanceof File ) {

            className = File.class.getCanonicalName();

        }
        if ( STANDARD_JAVA_CLASS_HOLDER_FACTORIES.containsKey( className ) ) {

            rval = true;

        } else if ( obj instanceof GowingPackableCollection ) {

            boolean thisCheck = true;
            for ( Object element : (Collection)obj ) {

                if ( !isObjectsClassSupported( element ) ) {

                    thisCheck = false;
                    break;

                }

            }

            rval = thisCheck;

        } else if ( obj instanceof GowingPackable ) {

            rval = true;

        } else if ( obj instanceof EntityName ) {

            rval = true;

        } else {

            if ( obj instanceof File ) {
                ObtuseUtil.doNothing();
            }

            rval = isClassSupported( obj.getClass() );

        }

        return rval;

    }

    private static synchronized boolean isClassSupported( final @NotNull Class entityClass ) {

        boolean rval = STANDARD_JAVA_CLASS_HOLDER_FACTORIES.containsKey( entityClass.getCanonicalName() );

        return rval;

    }

    public static void packObj( final GowingPackedEntityBundle bundle, final EntityName entityName, final Object obj, final GowingPacker packer ) {

        packObj( bundle, entityName, obj, packer, false );

    }

    public static void packObj(
            final GowingPackedEntityBundle bundle,
            final EntityName entityName,
            final Object obj,
            final GowingPacker packer,
            final boolean classSupportVerified
    ) {

        if ( obj == null ) {

            bundle.addHolder( new GowingNullHolder( entityName ) );

        } else if ( obj instanceof GowingPackable ) {

            bundle.addPackableEntityHolder( entityName, (GowingPackable)obj, packer, true );

        } else if ( obj instanceof Collection ) {

            bundle.addHolder(
                    new GowingPackableEntityHolder(
                            entityName,
                            new GowingPackableCollection<>(
                                    (Collection)obj
                            ),
                            packer,
                            true
                    )
            );

        } else {

            String className = obj.getClass().getCanonicalName();
            if ( obj instanceof File ) {

                className = File.class.getCanonicalName();

            }

            HolderFactory factory = STANDARD_JAVA_CLASS_HOLDER_FACTORIES.get( className );

            if ( factory == null ) {

                if ( classSupportVerified ) {

                    throw new HowDidWeGetHereError( "GowingPackableKeyValuePair#packObj:  unsupported object class " +
                                                    className +
                                                    " (should have been caught by earlier verification)" );

                } else {

                    throw new IllegalArgumentException( "GowingPackableKeyValuePair#packObj:  unsupported object class " + className );

                }

            }

            bundle.addHolder( factory.constructHolder( entityName, obj, packer ) );

        }

    }

    public String toString() {

        return "GowingPackableKeyValuePair( key=" + _key + ", value = " + _value + " )";

    }

}


text:
package org.oscm.tenant.dao;

import java.util.List;

import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.oscm.converter.ParameterizedTypes;
import org.oscm.dataservice.local.DataService;
import org.oscm.domobjects.Tenant;
import org.oscm.domobjects.TenantSetting;
import org.oscm.internal.types.enumtypes.IdpSettingType;
import org.oscm.internal.types.exception.DomainObjectException.ClassEnum;
import org.oscm.internal.types.exception.ObjectNotFoundException;

@Stateless
@LocalBean
public class TenantDao {

    @EJB
    DataService dataManager;

    public List<Tenant> getAllTenants() {
        Query query = dataManager.createNamedQuery("Tenant.getAll");
        return ParameterizedTypes.list(query.getResultList(), Tenant.class);
    }

    public Tenant getTenantByTenantId(String tenantId) throws ObjectNotFoundException {
        Tenant tenant = new Tenant();
        tenant.setTenantId(tenantId);
        return (Tenant) dataManager.getReferenceByBusinessKey(tenant);
    }

    public List<TenantSetting> getAllTenantSettingsForTenant(Tenant tenant) {
        Query query = dataManager.createNamedQuery("TenantSetting.getAllForTenant");
        query.setParameter("tenant", tenant);
        return ParameterizedTypes.list(query.getResultList(), TenantSetting.class);
    }

    public List<Tenant> getTenantsByIdPattern(String tenantIdPattern) {
        Query query = dataManager.createNamedQuery("Tenant.getTenantsByIdPattern");
        query.setParameter("tenantIdPattern", tenantIdPattern);
        return ParameterizedTypes.list(query.getResultList(), Tenant.class);
    }

    public Tenant find(long tenantID) {
        return dataManager.find(Tenant.class, tenantID);
    }

    public long doesOrganizationForTenantExist(Tenant tenant) {
        Query query = dataManager.createNamedQuery("Tenant.checkOrganization");
        query.setParameter("tenant", tenant);
        return (long) query.getSingleResult();
    }

    public long doesMarketplaceAssignedToTenantExist(Tenant tenant) {
        Query query = dataManager.createNamedQuery("Tenant.checkMarketplace");
        query.setParameter("tenant", tenant);
        return (long) query.getSingleResult();
    }

    public List<String> getNonUniqueOrgUserIdsInTenant(String orgId, long tenantKey) {

        final String queryString = "SELECT groupedusers.userid " + "FROM "
                + "(SELECT users.userid, count(users.orgkey) as numberOfUsers FROM"
                + "(SELECT u.userid, o.tkey as orgkey FROM platformuser u "
                + "LEFT JOIN organization o ON u.organizationkey=o.tkey WHERE o.organizationid=:orgId "
                + "UNION  "
                + "SELECT u.userid, o.tkey as orgkey FROM platformuser u "
                + "LEFT JOIN organization o ON u.organizationkey=o.tkey WHERE (CASE :tenantKey WHEN 0 THEN o.tenant_tkey IS NULL ELSE o.tenant_tkey=:tenantKey END)) "
                + "as users " + "GROUP BY users.userid) " + "as groupedusers "
                + "WHERE groupedusers.numberOfUsers>1";

        Query query = dataManager.createNativeQuery(queryString);
        query.setParameter("orgId", orgId);
        query.setParameter("tenantKey", tenantKey);

        return ParameterizedTypes.list(query.getResultList(), String.class);
    }

    public TenantSetting getTenantSetting(String settingKey, String tenantId)
            throws ObjectNotFoundException {

        Tenant tenant = this.getTenantByTenantId(tenantId);

        Query query = dataManager
                .createNamedQuery("TenantSetting.findByBusinessKey");
        query.setParameter("tenant", tenant);
        query.setParameter("name", IdpSettingType.valueOf(settingKey));

        TenantSetting tenantSetting;

        try {
            tenantSetting = (TenantSetting) query.getSingleResult();
        } catch (NoResultException e) {
            throw new ObjectNotFoundException(ClassEnum.TENANT_SETTING,
                    settingKey + " for tenant: " + tenantId);
        }

        return tenantSetting;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Net;
using System.Web;

namespace SimpleOAuth.OAuth2
{
    /// <summary>
    /// A generic OAuth2 Client.
    /// </summary>
    public class OAuth2Client
    {
        #region Nested
        /// <summary>
        /// Represents an explicit authorization request return.
        /// </summary>
        public class AuthorizationReturn
        {
            #region Properties
            /// <summary>
            /// The authorization code.
            /// </summary>
            public string Code { get; internal set; }

            /// <summary>
            /// The state, if provided.
            /// </summary>
            public string State { get; internal set; }
            #endregion Properties
        }
        #endregion Nested

        #region Properties
        /// <summary>
        /// The configuration to use.
        /// </summary>
        protected ClientConfiguration Configuration { get; private set; }
        #endregion Properties

        #region Construction / Destruction
        /// <summary>
        /// Initializes a new instance of <c>OAuth2Client</c>.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <exception cref="ArgumentNullException"><paramref name="configuration"/> was <see langword="null"/>.</exception>
        public OAuth2Client(ClientConfiguration configuration)
        {
            if (null == configuration)
                throw new ArgumentNullException("configuration");

            this.Configuration = configuration;
        }
        #endregion

        #region Static Methods
        /// <summary>
        /// Creates an <see cref="HttpWebRequest"/> for a given uri and token.
        /// </summary>
        /// <param name="uri">The uri.</param>
        /// <param name="token">The <see cref="AccessToken"/>.</param>
        /// <returns>An <see cref="HttpWebRequest"/> instance.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="uri"/> was <see langword="null"/> or <see cref="string.Empty"/> or <paramref name="token"/> was null.</exception>
        static public HttpWebRequest CreateAuthorizedRequest(string uri, AccessToken token)
        {
            if (string.IsNullOrWhiteSpace(uri))
                throw new ArgumentNullException("uri");

            if (null == token)
                throw new ArgumentNullException("token");

            HttpWebRequest r = (HttpWebRequest)HttpWebRequest.Create(uri);

            r.Headers.Add("Authorization", (TokenType.bearer.Equals(token.TokenType) ? "Bearer" : "MAC") + " " + token.Token);

            return r;
        }

        /// <summary>
        /// Gets an explicit <see cref="AuthorizationReturn"/> from an authorization request,
        /// redirected back from the target server after sending the user to the url in
        /// <see cref="GetAuthorizationUrl"/>.
        /// </summary>
        /// <param name="expectedState">Optional expected state from passing one to <see cref="GetAuthorizationUrl"/>.</param>
        /// <returns>An <see cref="AuthorizationReturn"/> or <see langword="null"/> if none was detected.</returns>
        /// <exception cref="InvalidOperationException">There is no current <see cref="HttpContext"/>.</exception>
        /// <exception cref="OAuth2Exception">Something went wrong.</exception>
        static public AuthorizationReturn GetAuthorizationReturn(string expectedState = null)
        {
            if (null == HttpContext.Current)
                throw new InvalidOperationException("There is no current HttpContext.");

            HttpRequest request = HttpContext.Current.Request;

            string s = request[Parameter.error];

            if (!string.IsNullOrEmpty(s))
                throw new OAuth2Exception(s, request[Parameter.error_description], request[Parameter.error_uri], request[Parameter.state]);

            s = request[Parameter.code];

            if (string.IsNullOrEmpty(s))
                return null;

            AuthorizationReturn r = new AuthorizationReturn
            {
                Code = s,
                State = request[Parameter.state]
            };

            if (!string.IsNullOrWhiteSpace(expectedState) && !string.IsNullOrWhiteSpace(r.State) && !expectedState.Equals(r.State))
                throw new OAuth2Exception("The expected state was not received.");

            return r;
        }
        #endregion Static Methods

        #region Methods
        /// <summary>
        /// Get the authorization url.
        /// </summary>
        /// <param name="state">Optional state.</param>
        /// <param name="implicit"><see langword="true"/> for an implicit authorization; otherwise (default) <see langword="false"/>.</param>
        /// <exception cref="InvalidOperationException">The client is not configured correctly.</exception>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">The client is not configured correctly.</exception>
        /// <exception cref="ArgumentNullException">The configuration <see cref="ClientConfiguration.AuthorizationStateRequired"/> is <see langword="true"/> and <paramref name="state "/> was <see langword="null"/> or <see cref="string.Empty"/>.</exception>
        public string GetAuthorizationUrl(string state = null, bool @implicit = false)
        {
            _ValidateConfiguration();

            if (this.Configuration.AuthorizationStateRequired && string.IsNullOrWhiteSpace(state))
                throw new ArgumentNullException("State is required.");

            Dictionary<string, object> p = new Dictionary<string, object>();

            p.Add(Parameter.response_type, @implicit ? ResponseType.token : ResponseType.code);
            p.Add(Parameter.client_id, this.Configuration.ClientId);

            if (!string.IsNullOrWhiteSpace(this.Configuration.Scope))
                p.Add(Parameter.scope, this.Configuration.Scope);

            if (!string.IsNullOrEmpty(this.Configuration.RedirectUrl))
                p.Add(Parameter.redirect_uri, this.Configuration.RedirectUrl);

            if (!string.IsNullOrWhiteSpace(state))
                p.Add(Parameter.state, state);

            FixupAuthorizationUrlParameters(p);

            return this.Configuration.AuthorizationUrl + p.ToQueryString();
        }

        /// <summary>
        /// When overridden in derived classes, allows the opportunity to examine and modify the
        /// authorization url parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        virtual protected void FixupAuthorizationUrlParameters(Dictionary<string, object> parameters)
        {
        }

        /// <summary>
        /// Gets an access token given a redirection back to the <see cref="ClientConfiguration.RedirectUrl"/> from an authorization url.
        /// </summary>
        /// <param name="code">The authorization code, required if <paramref name="implicit"/> is <see langword="false"/>.</param>
        /// <param name="expectedState">Optional expected state, if any.</param>
        /// <param name="implicit"><see langword="true"/> for an implicit token request; otherwise (default) <see langword="false"/>.</param>
        /// <returns>The <see cref="AccessToken"/> constructed by <see cref="OnGotTokenResponse"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="implicit"/> is <see langword="false"/> and <paramref name="code"/> was <see langword="null"/> or <see cref="string.Empty"/>.</exception>
        /// <exception cref="InvalidOperationException">The client is not configured correctly.</exception>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">The client is not configured correctly.</exception>
        /// <exception cref="OAuth2Exception">Something went wrong.</exception>
        public AccessToken GetAccessToken(string code = null, string expectedState = null, bool @implicit = false)
        {
            _ValidateConfiguration();

            if (@implicit)
                return new AccessToken(HttpContext.Current.Request);

            if (string.IsNullOrEmpty(code))
                throw new ArgumentNullException("code");

            try
            {
                Dictionary<string, object> p = new Dictionary<string, object>();

                p.Add(Parameter.grant_type, GrantType.authorization_code);
                p.Add(Parameter.code, code);
                p.Add(Parameter.client_id, this.Configuration.ClientId);
                p.Add(Parameter.client_secret, this.Configuration.ClientSecret);

                if (!string.IsNullOrWhiteSpace(this.Configuration.RedirectUrl))
                    p.Add(Parameter.redirect_uri, this.Configuration.RedirectUrl);

                FixupGetAccessTokenParameters(p);

                string uri = this.Configuration.TokenUrl + p.ToQueryString();

                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);

                req.ContentType = ApplicationContentType.FormEncoded;

                using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                    return OnGotTokenResponse(res, expectedState);
            }
            catch (OAuth2Exception)
            {
                throw;
            }
            catch (Exception e)
            {
                if (e is WebException)
                    return OnGotTokenResponse((HttpWebResponse)((WebException)e).Response);

                throw new OAuth2Exception("Could not get an access token -- " + e.Message, e);
            }
        }

        /// <summary>
        /// When overridden in derived classes, allows the opportunity to examine and modify the
        /// access token url parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        virtual protected void FixupGetAccessTokenParameters(Dictionary<string, object> parameters)
        {
        }

        /// <summary>
        /// Refreshes an access token.
        /// </summary>
        /// <param name="refreshToken">The refresh token.</param>
        /// <returns>The <see cref="AccessToken"/> constructed by <see cref="OnGotTokenResponse"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="refreshToken"/> was <see langword="null"/> or <see cref="string.Empty"/>.</exception>
        /// <exception cref="InvalidOperationException">The client is not configured correctly.</exception>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">The client is not configured correctly.</exception>
        /// <exception cref="OAuth2Exception">Something went wrong.</exception>
        public AccessToken RefreshToken(string refreshToken)
        {
            _ValidateConfiguration();

            if (string.IsNullOrWhiteSpace(refreshToken))
                throw new ArgumentNullException("refreshToken");

            try
            {
                Dictionary<string, object> p = new Dictionary<string, object>();

                p.Add(Parameter.grant_type, GrantType.refresh_token);
                p.Add(Parameter.refresh_token, refreshToken);

                if (!string.IsNullOrWhiteSpace(this.Configuration.Scope))
                    p.Add(Parameter.scope, this.Configuration.Scope);

                FixupRefreshTokenParameters(p);

                string uri = this.Configuration.TokenUrl + p.ToQueryString();

                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);

                req.ContentType = ApplicationContentType.FormEncoded;

                using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
                    return OnGotTokenResponse(res);
            }
            catch (OAuth2Exception)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new OAuth2Exception("Could not get an access token -- " + e.Message, e);
            }
        }

        /// <summary>
        /// When overridden in derived classes, allows the opportunity to examine and modify the
        /// refresh token url parameters.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        virtual protected void FixupRefreshTokenParameters(Dictionary<string, object> parameters)
        {
        }

        /// <summary>
        /// Constructs an <see cref="AccessToken"/> from the server response.
        /// </summary>
        /// <param name="response">The <see cref="HttpWebResponse"/>.</param>
        /// <param name="state">Optional expected state.</param>
        /// <returns>An <see cref="AccessToken"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="response"/> was <see langword="null"/>.</exception>
        /// <exception cref="OAuth2Exception">Something wend wrong, e.g. the response contained an error from the server.</exception>
        virtual protected AccessToken OnGotTokenResponse(HttpWebResponse response, string state = null)
        {
            if (null == response)
                throw new ArgumentNullException("response");

            return new AccessToken(response, state);
        }
        #endregion Methods

        #region Implementation
        private void _ValidateConfiguration()
        {
            if (null == HttpContext.Current)
                throw new InvalidOperationException("There is no current HttpContext.");

            this.Configuration.Validate();
        }
        #endregion Implementation
    }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

#include "event-parse.h"
#include "event-utils.h"

/*
 * The TRACE_SEQ_POISON is to catch the use of using
 * a trace_seq structure after it was destroyed.
 */
#define TRACE_SEQ_POISON	((void *)0xdeadbeef)
#define TRACE_SEQ_CHECK(s)						\
do {									\
	if ((s)->buffer == TRACE_SEQ_POISON)			\
		die("Usage of trace_seq after it was destroyed");	\
} while (0)

/**
 * trace_seq_init - initialize the trace_seq structure
 * @s: a pointer to the trace_seq structure to initialize
 */
void trace_seq_init(struct trace_seq *s)
{
	s->len = 0;
	s->readpos = 0;
	s->buffer_size = TRACE_SEQ_BUF_SIZE;
	s->buffer = malloc_or_die(s->buffer_size);
}

/**
 * trace_seq_destroy - free up memory of a trace_seq
 * @s: a pointer to the trace_seq to free the buffer
 *
 * Only frees the buffer, not the trace_seq struct itself.
 */
void trace_seq_destroy(struct trace_seq *s)
{
	if (!s)
		return;
	TRACE_SEQ_CHECK(s);
	free(s->buffer);
	s->buffer = TRACE_SEQ_POISON;
}

static void expand_buffer(struct trace_seq *s)
{
	s->buffer_size += TRACE_SEQ_BUF_SIZE;
	s->buffer = realloc(s->buffer, s->buffer_size);
	if (!s->buffer)
		die("Can't allocate trace_seq buffer memory");
}

/**
 * trace_seq_printf - sequence printing of trace information
 * @s: trace sequence descriptor
 * @fmt: printf format string
 *
 * It returns 0 if the trace oversizes the buffer's free
 * space, 1 otherwise.
 *
 * The tracer may use either sequence operations or its own
 * copy to user routines. To simplify formating of a trace
 * trace_seq_printf is used to store strings into a special
 * buffer (@s). Then the output may be either used by
 * the sequencer or pulled into another buffer.
 */
int
trace_seq_printf(struct trace_seq *s, const char *fmt, ...)
{
	va_list ap;
	int len;
	int ret;

	TRACE_SEQ_CHECK(s);

 try_again:
	len = (s->buffer_size - 1) - s->len;

	va_start(ap, fmt);
	ret = vsnprintf(s->buffer + s->len, len, fmt, ap);
	va_end(ap);

	if (ret >= len) {
		expand_buffer(s);
		goto try_again;
	}

	s->len += ret;

	return 1;
}

/**
 * trace_seq_vprintf - sequence printing of trace information
 * @s: trace sequence descriptor
 * @fmt: printf format string
 *
 * The tracer may use either sequence operations or its own
 * copy to user routines. To simplify formating of a trace
 * trace_seq_printf is used to store strings into a special
 * buffer (@s). Then the output may be either used by
 * the sequencer or pulled into another buffer.
 */
int
trace_seq_vprintf(struct trace_seq *s, const char *fmt, va_list args)
{
	int len;
	int ret;

	TRACE_SEQ_CHECK(s);

 try_again:
	len = (s->buffer_size - 1) - s->len;

	ret = vsnprintf(s->buffer + s->len, len, fmt, args);

	if (ret >= len) {
		expand_buffer(s);
		goto try_again;
	}

	s->len += ret;

	return len;
}

/**
 * trace_seq_puts - trace sequence printing of simple string
 * @s: trace sequence descriptor
 * @str: simple string to record
 *
 * The tracer may use either the sequence operations or its own
 * copy to user routines. This function records a simple string
 * into a special buffer (@s) for later retrieval by a sequencer
 * or other mechanism.
 */
int trace_seq_puts(struct trace_seq *s, const char *str)
{
	int len;

	TRACE_SEQ_CHECK(s);

	len = strlen(str);

	while (len > ((s->buffer_size - 1) - s->len))
		expand_buffer(s);

	memcpy(s->buffer + s->len, str, len);
	s->len += len;

	return len;
}

int trace_seq_putc(struct trace_seq *s, unsigned char c)
{
	TRACE_SEQ_CHECK(s);

	while (s->len >= (s->buffer_size - 1))
		expand_buffer(s);

	s->buffer[s->len++] = c;

	return 1;
}

void trace_seq_terminate(struct trace_seq *s)
{
	TRACE_SEQ_CHECK(s);

	/* There's always one character left on the buffer */
	s->buffer[s->len] = 0;
}

int trace_seq_do_printf(struct trace_seq *s)
{
	TRACE_SEQ_CHECK(s);
	return printf("%.*s", s->len, s->buffer);
}


text:
``` diff
+namespace System.ServiceModel.Activation.Configuration {
+    public sealed class DiagnosticSection : ConfigurationSection {
+        public DiagnosticSection();
+        public bool PerformanceCountersEnabled { get; set; }
+        protected override ConfigurationPropertyCollection Properties { get; }
+    }
+    public sealed class NetPipeSection : ConfigurationSection {
+        public NetPipeSection();
+        public SecurityIdentifierElementCollection AllowAccounts { get; }
+        public int MaxPendingAccepts { get; set; }
+        public int MaxPendingConnections { get; set; }
+        protected override ConfigurationPropertyCollection Properties { get; }
+        public TimeSpan ReceiveTimeout { get; set; }
+        protected override void InitializeDefault();
+    }
+    public sealed class NetTcpSection : ConfigurationSection {
+        public NetTcpSection();
+        public SecurityIdentifierElementCollection AllowAccounts { get; }
+        public int ListenBacklog { get; set; }
+        public int MaxPendingAccepts { get; set; }
+        public int MaxPendingConnections { get; set; }
+        protected override ConfigurationPropertyCollection Properties { get; }
+        public TimeSpan ReceiveTimeout { get; set; }
+        public bool TeredoEnabled { get; set; }
+        protected override void InitializeDefault();
+    }
+    public sealed class SecurityIdentifierElement : ConfigurationElement {
+        public SecurityIdentifierElement();
+        public SecurityIdentifierElement(SecurityIdentifier sid);
+        protected override ConfigurationPropertyCollection Properties { get; }
+        public SecurityIdentifier SecurityIdentifier { get; set; }
+    }
+    public sealed class SecurityIdentifierElementCollection : ServiceModelConfigurationElementCollection<SecurityIdentifierElement> {
+        public SecurityIdentifierElementCollection();
+        protected override object GetElementKey(ConfigurationElement element);
+    }
+    public sealed class ServiceModelActivationSectionGroup : ConfigurationSectionGroup {
+        public ServiceModelActivationSectionGroup();
+        public DiagnosticSection Diagnostics { get; }
+        public NetPipeSection NetPipe { get; }
+        public NetTcpSection NetTcp { get; }
+        public static ServiceModelActivationSectionGroup GetSectionGroup(Configuration config);
+    }
+}
```


text:
"""This module, custom_keyword_mapping.py, only serves
"""

from code_manager.abstract_definitions import classes
from code_manager.abstract_definitions import code_file
from code_manager.abstract_definitions import conditionals
from code_manager.abstract_definitions import functions
from code_manager.abstract_definitions import variables

library_nickname_mapping = {}
for key in classes.library_nickname_mapping.keys():
	library_nickname_mapping[key] = classes.library_nickname_mapping[key]
for key in code_file.library_nickname_mapping.keys():
	library_nickname_mapping[key] = code_file.library_nickname_mapping[key]
for key in conditionals.library_nickname_mapping.keys():
	library_nickname_mapping[key] = conditionals.library_nickname_mapping[key]
for key in functions.library_nickname_mapping.keys():
	library_nickname_mapping[key] = functions.library_nickname_mapping[key]
for key in variables.library_nickname_mapping.keys():
	library_nickname_mapping[key] = variables.library_nickname_mapping[key]
library_nickname_mapping['c'] = 'from code_manager.code_generator_support.import_error_mask import c'


text:
module Theblog
  module ApplicationHelper
    def link_to_content_node(node)
      link = path_to_content_node(node)

      if block_given?
        link_to(link) { yield }
      else
        link_to node.title, link
      end
    end
  end
end


text:
/**
 * This Code was created on April 2014
 * If you find any bug, unreadable code, messy code, potential bug code, etc
 * Please contact me at:
 * Ega Radiegtya / radiegtya@yahoo.co.id / 085641278479
 */

Students = new Mongo.Collection("students");

var schemas = new SimpleSchema({
    name:{
type:String,
label: 'Name',
},
birthDate:{
type:Date,
label: 'BirthDate',
optional: true,
},

            /* AUTOVALUE */
            appId: {
                type: String,
                label: "App Id",
                autoValue: function() {
                    if (this.isInsert)
                        return App.id;
                },
            },
    createdAt: {
        type: Date,
        label: "Created Date",
        autoValue: function() {
            if (this.isInsert)
                return new Date;
        },
        denyUpdate: true,
        optional: true
    },
    updatedAt: {
        type: Date,
        label: "Updated Date",
        autoValue: function() {
            return new Date();
        },
        optional: true
    },
    createdUserId: {
        type: String,
        label: "Created by",
        autoValue: function() {
            if (this.isInsert)
                return Meteor.user()._id;
        },
        denyUpdate: true,
        optional: true
    },
    updatedUserId: {
        type: String,
        label: "Updated by",
        autoValue: function() {
            return Meteor.user()._id;
        },
        optional: true
    },
});

Students.attachSchema(schemas);

Students.allow({
    insert: function(userId, doc) {
        var result = Meteor.call('MugenRoleActions.getRoles', 'students', 'insert');
        return result;
    },
    update: function(userId, doc) {
        var result = Meteor.call('MugenRoleActions.getRoles', 'students', 'update');
        return result;
    },
    remove: function(userId, doc) {
        var result = Meteor.call('MugenRoleActions.getRoles', 'students', 'remove');
        return result;
    },
});

//activate groundDB for students collection to work offline
/* uncomment to use
 Ground.Collection(Students);
 */

/* register helper for default relations */
Students.helpers({

    createdUser: function() {
        return Meteor.users.findOne(this.createdUserId);
    },
    updatedUser: function() {
        return Meteor.users.findOne(this.updatedUserId);
    },
});


text:
from datetime import datetime, timedelta
import settings_local as settings
import posixpath
import re

# Ugh. But this avoids any zamboni or django imports at all.
# Perhaps we can import these without any problems and we can
# remove all this.

from constants.applications import APPS_ALL
from constants.platforms import PLATFORMS
from constants.base import (STATUS_PUBLIC, STATUS_DISABLED, STATUS_BETA,
                            STATUS_LITE, STATUS_LITE_AND_NOMINATED)

APP_GUIDS = dict([(app.guid, app.id) for app in APPS_ALL.values()])
PLATFORMS = dict([(plat.api_name, plat.id) for plat in PLATFORMS.values()])

ADDON_SLUGS_UPDATE = {
    1: 'extension',
    2: 'theme',
    3: 'extension',
    4: 'search',
    5: 'item',
    6: 'extension',
    7: 'plugin'}

STATUSES_PUBLIC = {'STATUS_PUBLIC': STATUS_PUBLIC,
                   'STATUS_LITE': STATUS_LITE,
                   'STATUS_LITE_AND_NOMINATED': STATUS_LITE_AND_NOMINATED}

version_re = re.compile(r"""(?P<major>\d+)         # major (x in x.y)
                            \.(?P<minor1>\d+)      # minor1 (y in x.y)
                            \.?(?P<minor2>\d+|\*)? # minor2 (z in x.y.z)
                            \.?(?P<minor3>\d+|\*)? # minor3 (w in x.y.z.w)
                            (?P<alpha>[a|b]?)      # alpha/beta
                            (?P<alpha_ver>\d*)     # alpha/beta version
                            (?P<pre>pre)?          # pre release
                            (?P<pre_ver>\d)?       # pre release version""",
                        re.VERBOSE)

def get_mirror(status, id, row):
    if row['datestatuschanged']:
        published = datetime.now() - row['datestatuschanged']
    else:
        published = timedelta(minutes=0)

    if row['disabled_by_user'] or status == STATUS_DISABLED:
        host = settings.PRIVATE_MIRROR_URL
    elif (status == STATUS_PUBLIC
          and not row['disabled_by_user']
          and row['file_status'] in (STATUS_PUBLIC, STATUS_BETA)
          and published > timedelta(minutes=settings.MIRROR_DELAY)
          and not settings.DEBUG):
        host = settings.MIRROR_URL
    else:
        host = settings.LOCAL_MIRROR_URL

    return posixpath.join(host, str(id), row['filename'])


text:
package cn.wizzer.common.shiro.realm;

import cn.wizzer.common.shiro.exception.EmptyCaptchaException;
import cn.wizzer.common.shiro.exception.IncorrectCaptchaException;
import cn.wizzer.modules.back.sys.models.Sys_user;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.util.ByteSource;
import org.nutz.dao.Cnd;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;

public class NutDaoRealm extends AbstractNutRealm {
    private static final Log log = Logs.get();

    public NutDaoRealm() {
        setAuthenticationTokenClass(CaptchaToken.class);
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        CaptchaToken authcToken = (CaptchaToken) token;
        String loginname = authcToken.getUsername();
        String captcha = authcToken.getCaptcha();
        if (Strings.isBlank(loginname)) {
            throw Lang.makeThrow(AuthenticationException.class, "Account name is empty");
        }
        Sys_user user = getUserService().fetch(Cnd.where("loginname", "=", loginname));
        if (Lang.isEmpty(user)) {
            throw Lang.makeThrow(UnknownAccountException.class, "Account [ %s ] not found", loginname);
        }
        int errCount = NumberUtils.toInt(Strings.sNull(SecurityUtils.getSubject().getSession(true).getAttribute("errCount")));
        if (errCount > 2) {
            //输错三次显示验证码窗口
            if (Strings.isBlank(captcha)) {
                throw Lang.makeThrow(EmptyCaptchaException.class, "Captcha is empty");
            }
            String _captcha = Strings.sBlank(SecurityUtils.getSubject().getSession(true).getAttribute("captcha"));
            if (!authcToken.getCaptcha().equalsIgnoreCase(_captcha)) {
                throw Lang.makeThrow(IncorrectCaptchaException.class, "Captcha is error");
            }
        }
        if (user.isDisabled()) {
            throw Lang.makeThrow(LockedAccountException.class, "Account [ %s ] is locked.", loginname);
        }
        SecurityUtils.getSubject().getSession(true).setAttribute("errCount", 0);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        info.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return info;
    }

}


text:
<?php
/**
 * Interface for filters.
 *
 * @package     stubbles
 * @subpackage  ipo_request_filter
 * @version     $Id: stubFilter.php 2329 2009-09-16 16:00:05Z mikey $
 */
stubClassLoader::load('net::stubbles::ipo::request::filter::stubFilterException');
/**
 * Interface for filter.
 *
 * Filters can be used to take request values, validate them and change them
 * into any other value.
 *
 * @package     stubbles
 * @subpackage  ipo_request_filter
 */
interface stubFilter extends stubObject
{
    /**
     * execute the filter
     *
     * @param   mixed                $value  value to filter
     * @return  mixed                filtered value
     * @throws  stubFilterException  in case $value has errors
     */
    public function execute($value);
}
?>


text:
(function() {

    var namespace = WEBLAB.namespace("WEBLAB.utils.animation");
    var TweenDelay = namespace.TweenDelay;

    var ListenerFunctions = WEBLAB.namespace("WEBLAB.utils.events").ListenerFunctions;
    var Utils = WEBLAB.namespace("WEBLAB.utils").Utils;

    if (namespace.DomElementOpacityTween === undefined) {

        var DomElementOpacityTween = function DomElementOpacityTween() {
            this._init();
        }

        namespace.DomElementOpacityTween = DomElementOpacityTween;

        var p = DomElementOpacityTween.prototype;

        p._init = function() {
            this._element = null;
            this._opacity = 1;

            this._updateCallback = ListenerFunctions.createListenerFunction(this, this._update);

            this._tween = new TWEEN.Tween(this);
            this._tween.onUpdate(this._updateCallback);

            this._tweenDelay = TweenDelay.create(this._tween);
        }

        p.setElement = function(aElement) {
            this._element = aElement;

            return this;
        };

        p.getElemet = function() {
            return this._element;
        };

        p.getOpacity = function() {
            return this._x;
        };

        p.setStartOpacity = function(aOpacity) {
            this._opacity = aOpacity;

            return this;
        };

        p.animateTo = function(aOpacity, aTime, aEasing, aDelay) {
            //console.log("WEBLAB.utils.animation.DomElementOpacityTween::animateTo");
            //console.log(aOpacity, aTime, aEasing, aDelay);

            this._tweenDelay.animateTo({
                "_opacity": aOpacity
            }, aTime, aEasing, aDelay);

            return this;
        };

        p.update = function() {
            this._update();
        };

        p._update = function() {
            if (this._element !== null) {
                this._element.style.setProperty("opacity", this._opacity, "");
            }
        };

        p.destroy = function() {
            this._element = null;
            this._updateCallback = null;
            this._tween = null;
            Utils.destroyIfExists(this._tweenDelay);
            this._tweenDelay = null;

            //WEBLAB.namespace("WEBLAB.utils.dev").DestroyVerification.verifyNoComplexObjects(this);
        };

        DomElementOpacityTween.create = function(aElement, aStartOpacity) {
            var newDomElementOpacityTween = new DomElementOpacityTween();
            newDomElementOpacityTween.setElement(aElement);
            newDomElementOpacityTween.setStartOpacity(aStartOpacity);
            return newDomElementOpacityTween;
        };

        DomElementOpacityTween.createWithAnimation = function(aElement, aStartOpacity, aOpacity, aTime, aEasing, aDelay) {
            var newDomElementOpacityTween = new DomElementOpacityTween();
            newDomElementOpacityTween.setElement(aElement);
            newDomElementOpacityTween.setStartOpacity(aStartOpacity);
            newDomElementOpacityTween.animateTo(aOpacity, aTime, aEasing, aDelay);
            return newDomElementOpacityTween;
        };
    }
})();


text:
{% extends "wagtailadmin/base.html" %}
{% load i18n static %}

{% block titletag %}{{ view.get_meta_title }}{% endblock %}

{% block extra_css %}
    {{ view.media.css }}
    <link rel="stylesheet" href="{% static 'wagtailmodeladmin/css/breadcrumbs_page.css' %}" type="text/css"/>
{% endblock %}

{% block extra_js %}
    {{ view.media.js }}
{% endblock %}

{% block content %}

    {% block header %}
        {% include "modeladmin/includes/header_with_breadcrumb.html" with title=view.get_page_title subtitle=view.get_page_subtitle icon=view.header_icon tabbed=True %}
    {% endblock %}

        {% block content_main %}

{% blocktrans with view.verbose_name as model_name %}Back to {{ model_name }} list{% endblocktrans %}

                {% block fields_output %}
                    {% if fields %}

                        {% for field in fields %}

{{ field.label }}

{{ field.value }}

                        {% endfor %}

                    {% endif %}
                {% endblock %}

        {% endblock %}

    {% block footer %}
        {% if buttons %}

                    {% for button in buttons %}
                        {% include "modeladmin/includes/button.html" %}
                    {% endfor %}

        {% endif %}
    {% endblock %}
{% endblock %}


text:
"use strict";
module.exports = function(Promise, CapturedTrace, isDebugging) {
var contextStack = [];
function Context() {
    this._trace = new CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
    if (!isDebugging()) return;
    if (this._trace !== undefined) {
        contextStack.push(this._trace);
    }
};

Context.prototype._popContext = function () {
    if (!isDebugging()) return;
    if (this._trace !== undefined) {
        contextStack.pop();
    }
};

function createContext() {
    if (isDebugging()) return new Context();
}

function peekContext() {
    var lastIndex = contextStack.length - 1;
    if (lastIndex >= 0) {
        return contextStack[lastIndex];
    }
    return undefined;
}

Promise.prototype._peekContext = peekContext;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;

return createContext;
};


text:
using ApathyEngine.Menus.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ApathyEngine.Menus
{
    ///
    /// Provides a default implementation of a menu that can be used to confirm if the player
    /// wants to exit the game.
    ///
    /// <remarks>Ideally, this class (and the Exiting game state) should be replaced by the
ConfirmationMenu

    /// class; but since there's a few different places you can exit the game from, here it remains for now.</remarks>
    public class ExitMenu : Menu
    {
        private readonly string exitString = "Are you sure you want to exit?";
        private Vector2 exitStringCenter;
        private readonly SpriteFont font;

        ///
        /// Creates a menu that can be used to ask if the player wants to exit the game.
        ///
        /// <param name="game">Owning game.</param>
        public ExitMenu(BaseGame game)
            : base(game)
        {
            MenuButton yes, no;
            yes = new MenuButton(loader.yesButton, delegate { Program.Game.Exit(); });
            no = new MenuButton(loader.noButton, delegate { game.ChangeState(game.PreviousState); });
            yes.SetDirectionals(null, no, null, null);
            no.SetDirectionals(yes, null, null, null);
            selectedControl = yes;
            yes.IsSelected = null;

            controlArray.AddRange(new MenuControl[] { yes, no });

            font = loader.BiggerFont;
            exitStringCenter = font.MeasureString(exitString) * 0.5f;
        }

        public override void Draw(GameTime gameTime)
        {
            RenderingDevice.SpriteBatch.Begin(SpriteSortMode.Immediate, null, SamplerState.LinearClamp, null, null);

            RenderingDevice.SpriteBatch.Draw(loader.halfBlack, new Rectangle(0, 0, (int)RenderingDevice.Width, (int)RenderingDevice.Height), Color.White);
            RenderingDevice.SpriteBatch.Draw(loader.mainMenuLogo, new Vector2(RenderingDevice.Width * 0.97f - loader.mainMenuLogo.Width / 2, RenderingDevice.Height * 0.03f - loader.mainMenuLogo.Height / 2), null, Color.White, 0.0f, new Vector2(loader.mainMenuLogo.Width / 2, loader.mainMenuLogo.Height / 2), 0.3f * RenderingDevice.TextureScaleFactor, SpriteEffects.None, 0);
            RenderingDevice.SpriteBatch.DrawString(font, exitString, new Vector2(RenderingDevice.Width * 0.5f, RenderingDevice.Height * 0.3f), Color.White, 0.0f, exitStringCenter, RenderingDevice.TextureScaleFactor, SpriteEffects.None, 0);
            base.Draw(gameTime);

            RenderingDevice.SpriteBatch.End();
        }
    }
}


text:
module StudentsHelper
  def can_current_user_create_new_student
    current_user_admin?
  end

  def get_student_team_name(student)
    student.team ? student.team.team_name : 'Nil'
  end

  def get_student_team_project_level(student)
    student.team ? student.team.get_project_level : 'Nil'
  end

  def get_student_team_adviser_name(student)
    (student.team && student.team.adviser) ? student.team.adviser.user.user_name : 'Nil'
  end

  def get_student_team_dropped_status(student)
    student.team ? student.team.has_dropped : 'Nil'
  end
end


text:
tips-and-tricks
===============

tips and tricks for ruby, rails, vim, postgres, mysql..

* [vim](vim.md)


text:
{% load staticfiles %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="A portfolio template that uses Material Design Lite.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">

    <title>{% block title %}VIEWER{% endblock %}</title>

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.light_green-deep_purple.min.css" />
    <link rel="stylesheet" href='{% static "css/styles.css" %}' />
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

    {% block extraheader %}
    {% endblock %}

                    welcome to {{ user.username }}

                    Profile

                Profile

{% block content %}

{% endblock%}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
    <form action="" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <input type="file" name="alunos"/>
        <input type="submit" value="Enviar"/>
    </form>
</body>
</html>


text:
/*
 * @include GeoExt/tree/LayerContainer.js
 */

/**
 * A layer node plugin that will collect all base layers of an OpenLayers
 * map. Only layers that have `displayInLayerSwitcher` set to `true` will
 * be included. The childrens' iconCls defaults to "gx-tree-baselayer-icon"
 * and the node' text defaults to "Base Layer".
 *
 * Children will be rendered with a radio button instead of a checkbox,
 * showing the user that only one base layer can be active at a time.
 *
 * To use this node plugin in a tree node config, configure a node like this:
 *
 *     {
 *         plugins: "gx_baselayercontainer",
 *         text: "My base layers"
 *     }
 *
 * @class GeoExt.tree.BaseLayerContainer
 */
Ext.define('GeoExt.tree.BaseLayerContainer', {
    extend: 'GeoExt.tree.LayerContainer',
    alias: 'plugin.gx_baselayercontainer',

    /**
     * The default text for the target node.
     *
     * @private
     */
    defaultText: 'Base Layers',

    /**
     * @private
     */
    init: function(target) {
        var me = this,
            loader = me.loader;

        me.loader = Ext.applyIf(loader || {}, {
            baseAttrs: Ext.applyIf((loader && loader.baseAttrs) || {}, {
                iconCls: 'gx-tree-baselayer-icon',
                checkedGroup: 'baselayer'
            }),
            filter: function(record) {
                var layer = record.getLayer();
                return layer.displayInLayerSwitcher === true &&
                    layer.isBaseLayer === true;
            }
        });
        me.callParent(arguments);
    }
});


text:
<?php

abstract class BaseController {
    protected $controllerName;
    protected $actionName;
    protected $layoutName = DEFAULT_LAYOUT;
    protected $isViewRendered = false;
    protected $isPost = false;
    protected $isLoggedIn;
    protected $isAdmin;
    protected $isEditor;
    protected $validationErrors;
    protected $formValues;
    protected $categories;
    protected $statuses;

    function __construct($controllerName, $actionName) {
        $this->controllerName = $controllerName;
        $this->actionName = $actionName;

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->isPost = true;
        }

        if (isset($_SESSION['username'])) {
            $this->isLoggedIn = true;
        }

        if (isset($_SESSION['admin'])) {
            $this->isAdmin = true;
        }

        if (isset($_SESSION['editor'])) {
            $this->isEditor = true;
        }

        $this->onInit();
    }

    public function onInit() {
        // Implement initializing logic in the subclasses
    }

    public function index() {
        // Implement the default action in the subclasses
    }

    public function renderView($viewName = null, $includeLayout = true) {
        if (!$this->isViewRendered) {
            if ($viewName == null) {
                $viewName = $this->actionName;
            }
            $viewFileName = 'views/' . $this->controllerName
                . '/' . $viewName . '.php';
            if ($includeLayout) {
                $headerFile = 'views/layouts/' . $this->layoutName . '/header.php';
                include_once($headerFile);
            }
            include_once($viewFileName);
            if ($includeLayout) {
                $footerFile = 'views/layouts/' . $this->layoutName . '/footer.php';
                include_once($footerFile);
            }
            $this->isViewRendered = true;
        }
    }

    public function redirectToUrl($url) {
        header("Location: " . $url);
        die;
    }

    public function redirect($controllerName, $actionName = null, $params = null) {
        $url = DX_ROOT_URL . urlencode($controllerName);
        if ($actionName != null) {
            $url .= '/' . urlencode($actionName);
        }
        if ($params != null) {
            $encodedParams = array_map($params, 'urlencode');
            if($encodedParams) {
                $url .= implode(DX_DS, $encodedParams);
            } else {
                $url .= DX_DS . $params;
            }
        }
        $this->redirectToUrl($url);
    }

    public function authorize() {
        if (! $this->isLoggedIn) {
            $this->addErrorMessage("Please login first");
            $this->redirect("account", "login");
        }
    }

    public function setAdminLogin($value) {
        $_SESSION['admin'] = true;
    }

    public function setEditorLogin($value) {
        $_SESSION['editor'] = true;
    }

    public function addValidationError($field, $message) {
        $this->validationErrors[$field] = $message;
    }

    public function getValidationError($field) {
        return $this->validationErrors[$field];
    }

    public function addFieldValue($field, $value) {
        $this->formValues[$field] = $value;
    }

    public function getFieldValue($field) {
        return $this->formValues[$field];
    }

    private function addMessage($msgSessionkey, $msgText) {
        if (!isset($_SESSION[$msgSessionkey])) {
            $_SESSION[$msgSessionkey] = [];
        }
        array_push($_SESSION[$msgSessionkey], $msgText);

    }

    protected function addErrorMessage($errorMsg) {
        $this->addMessage(ERROR_MESSAGES_SESSION_KEY, $errorMsg);
    }

    protected function addInfoMessage($infoMsg) {
        $this->addMessage(INFO_MESSAGES_SESSION_KEY, $infoMsg);
    }
}


text:
import React, { PropTypes } from 'react';
// import { Panel, Input, Button } from 'react-bootstrap';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
import { FormControl, Checkbox } from 'react-bootstrap';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Login.css';
import history from '../../core/history';
import $ from "jquery";
import { sendXHR } from '../../core/util.js';

const title = 'Log In';

function getLoginCheck(email, password, cb) {
  var user = "select user_name from Active_Directory where email = " + "\'" + email + "\'" + ' and pass_word = ' + "\'"+password + "\'";
  sendXHR("POST", "http://localhost:3001/sql_request", user, (xhr) => {
         cb(JSON.parse(xhr.responseText));
    });
}

function sendUserNameToFile(username, cb){
  sendXHR("POST", "http://localhost:3001/writefile", username, (xhr) => {
    cb(JSON.parse(xhr.responseText));
  });
}

function submitHandler(e) {
  e.preventDefault();
  var login = $("#login").serializeArray();
  var email = login[0].value;
  var password = login[1].value;
  getLoginCheck(email, password, (results) => {
        var username = results[0].user_name;
        sendUserNameToFile(username, (results) => {
        });
        history.push('/app');
  });
}

function Login(props, context) {
  context.setTitle(title);
  return (

Liberty Dash Login

      <Panel header={
Please Sign In
} className="login-panel">

        <form role="form" id="login" onSubmit={(e) => { submitHandler(e); }}>
          <fieldset>

              <FormControl
                type="text"
                className="form-control"
                placeholder="Username"
                name="name"
              />

              <FormControl
                className="form-control"
                placeholder="Password"
                type="password"
                name="password"
              />

            <Checkbox label="Remember Me" > Remember Me </Checkbox>
            <Button type="submit" bsSize="large" bsStyle="success" block>Login</Button>
          </fieldset>
        </form>

      </Panel>

  );
}

Login.contextTypes = { setTitle: PropTypes.func.isRequired };

export default withStyles(s)(Login);


text:
namespace ImportantClasses.Enums
{
    /// <summary>
    /// determiens an axis
    /// </summary>
    public enum Axis
    {
        Front = 0,
        Rear = 1
    }

    /// <summary>
    /// determines a wheel
    /// </summary>
    public enum Wheels
    {
        FrontLeft = 0,
        FrontRight,
        RearLeft,
        RearRight
    }
}


text:
struct Camera {

	void init()
	{
		position = make_float3(0.f, 0.f, 0.f);
		direction = make_float3(0.f, 0.f, 1.f);
		right = make_float3(1.f, 0.f, 0.f);
		up = make_float3(0.f, 1.f, 0.f);
	}

	void lookAt(float3 const& eye, float3 const& target, float3 const& sky, float const& fov, float const& ratio) {
		position = eye;

		direction = target - eye;
		normalize(direction);

		right = cross(sky, direction);
		normalize(right);
		right *= ratio;

		up = cross(direction, right);
		normalize(up);
	}

	__device__ Ray getRay(float u, float v) const {
		return Ray(position, CUDA::float3_add(direction, CUDA::float3_mult(u, right), CUDA::float3_mult(v, up)));
	}

	float3 position;
	float3 direction;
	float3 right;
	float3 up;

};

#endif


text:
"""
Gravatar Support for Bloog
"""
__author__ = 'Matteo Crippa'

import md5

from google.appengine.ext import webapp

register = webapp.template.create_template_register()

def gravatar(email):
	return md5.new(email).hexdigest()

register.filter(gravatar)


text:
package org.mockito.internal.stubbing.answers;

import static java.lang.Boolean.TRUE;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.internal.invocation.InvocationBuilder;

public class ReturnsTest {
    @Test
    public void should_return_value() throws Throwable {
        assertThat(
                        new Returns("value")
                                .answer(
                                        new InvocationBuilder()
                                                .method("oneArg")
                                                .arg("A")
                                                .toInvocation()))
                .isEqualTo("value");
    }

    @Test(expected = MockitoException.class)
    public void should_fail_when_return_Value_is_set_for_void_method() throws Throwable {
        new Returns("one").validateFor(new InvocationBuilder().method("voidMethod").toInvocation());
    }

    @Test
    public void should_allow_correct_type_of_return_value() throws Throwable {
        new Returns("one").validateFor(new InvocationBuilder().simpleMethod().toInvocation());
        new Returns(false)
                .validateFor(
                        new InvocationBuilder().method("booleanReturningMethod").toInvocation());
        new Returns(TRUE)
                .validateFor(
                        new InvocationBuilder()
                                .method("booleanObjectReturningMethod")
                                .toInvocation());
        new Returns(1)
                .validateFor(
                        new InvocationBuilder().method("integerReturningMethod").toInvocation());
        new Returns(1L)
                .validateFor(new InvocationBuilder().method("longReturningMethod").toInvocation());
        new Returns(1L)
                .validateFor(
                        new InvocationBuilder().method("longObjectReturningMethod").toInvocation());
        new Returns(null)
                .validateFor(
                        new InvocationBuilder()
                                .method("objectReturningMethodNoArgs")
                                .toInvocation());
        new Returns(1)
                .validateFor(
                        new InvocationBuilder()
                                .method("objectReturningMethodNoArgs")
                                .toInvocation());
    }

    @Test(expected = MockitoException.class)
    public void should_fail_on_return_type_mismatch() throws Throwable {
        new Returns("String")
                .validateFor(
                        new InvocationBuilder().method("booleanReturningMethod").toInvocation());
    }

    @Test(expected = MockitoException.class)
    public void should_fail_on_wrong_primitive() throws Throwable {
        new Returns(1)
                .validateFor(
                        new InvocationBuilder().method("doubleReturningMethod").toInvocation());
    }

    @Test(expected = MockitoException.class)
    public void should_fail_on_null_with_primitive() throws Throwable {
        new Returns(null)
                .validateFor(
                        new InvocationBuilder().method("booleanReturningMethod").toInvocation());
    }
}


text:
package io.truthencode.ddo.subscription

import com.sksamuel.pulsar4s.PulsarAsyncClient

trait PulsarEnabled {
val client: PulsarAsyncClient
}


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#ifndef _TYPESWIN32_H_
#define _TYPESWIN32_H_

// We have to check this.  Since every file will eventually wind up including
//  this header, but not every header includes a windows or system header...
//
#ifndef NULL
#define NULL 0
#endif

// Let's just have this in a nice central location.  Again, since every file
//  will wind up including this file, we can affect compilation most effectively
//  from this location.
//
#define PLATFORM_LITTLE_ENDIAN      ///< Signals this platfrom is Little Endian

#define FN_CDECL __cdecl            ///< Calling convention

//------------------------------------------------------------------------------
//-------------------------------------- Basic Types...

typedef signed char        S8;      ///< Compiler independent Signed Char
typedef unsigned char      U8;      ///< Compiler independent Unsigned Char

typedef signed short       S16;     ///< Compiler independent Signed 16-bit short
typedef unsigned short     U16;     ///< Compiler independent Unsigned 16-bit short

typedef signed int         S32;     ///< Compiler independent Signed 32-bit integer
typedef unsigned int       U32;     ///< Compiler independent Unsigned 32-bit integer

#ifdef __BORLANDC__
typedef signed __int64     S64;     ///< Compiler independent Signed 64-bit integer
typedef unsigned __int64   U64;     ///< Compiler independent Unsigned 64-bit integer

#elif defined(__MWERKS__) // This has to go before MSC_VER since CodeWarrior defines MSC_VER too
typedef signed long long   S64;     ///< Compiler independent Signed 64-bit integer
typedef unsigned long long U64;     ///< Compiler independent Unsigned 64-bit integer

#elif defined(_MSC_VER)
typedef signed _int64      S64;     ///< Compiler independent Signed 64-bit integer
typedef unsigned _int64    U64;     ///< Compiler independent Unsigned 64-bit integer
#pragma warning(disable: 4291) // disable warning caused by memory layer...

#else
typedef signed long long   S64;     ///< Compiler independent Signed 64-bit integer
typedef unsigned long long U64;     ///< Compiler independent Unsigned 64-bit integer
#endif

typedef float              F32;     ///< Compiler independent 32-bit float
typedef double             F64;     ///< Compiler independent 64-bit float

// size_t is needed to overload new
// size_t tends to be OS and compiler specific and may need to
// be if/def'ed in the future
typedef unsigned int  dsize_t;

typedef const char* StringTableEntry;

/*  Platform dependent file date-time structure.  The defination of this structure
  * will likely be different for each OS platform.
  */
struct FileTime
{
   U32 v1;
   U32 v2;
};

//------------------------------------------------------------------------------
//-------------------------------------- Type constants...
#define __EQUAL_CONST_F F32(0.000001)                             ///< Constant float epsilon used for F32 comparisons

static const F32 Float_One  = F32(1.0);                           ///< Constant float 1.0
static const F32 Float_Half = F32(0.5);                           ///< Constant float 0.5
static const F32 Float_Zero = F32(0.0);                           ///< Constant float 0.0
static const F32 Float_Pi   = F32(3.14159265358979323846);        ///< Constant float PI
static const F32 Float_2Pi  = F32(2.0 * 3.14159265358979323846);  ///< Constant float 2*PI

static const S8  S8_MIN  = S8(-128);                              ///< Constant Min Limit S8
static const S8  S8_MAX  = S8(127);                               ///< Constant Max Limit S8
static const U8  U8_MAX  = U8(255);                               ///< Constant Max Limit U8

static const S16 S16_MIN = S16(-32768);                           ///< Constant Min Limit S16
static const S16 S16_MAX = S16(32767);                            ///< Constant Max Limit S16
static const U16 U16_MAX = U16(65535);                            ///< Constant Max Limit U16

static const S32 S32_MIN = S32(-2147483647 - 1);                  ///< Constant Min Limit S32
static const S32 S32_MAX = S32(2147483647);                       ///< Constant Max Limit S32
static const U32 U32_MAX = U32(0xffffffff);                       ///< Constant Max Limit U32

static const F32 F32_MIN = F32(1.175494351e-38F);                 ///< Constant Min Limit F32
static const F32 F32_MAX = F32(3.402823466e+38F);                 ///< Constant Max Limit F32

#ifdef _MSC_VER
#define for if(false) {} else for   ///< Hack to work around Microsoft VC's non-C++ compliance on variable scoping
#endif

#endif //_NTYPES_H_


text:
const {Helper} = require("@kaoscript/runtime");
module.exports = function() {
	const AnimalFlags = Helper.enum(Number, {
		None: 0,
		HasClaws: 1,
		CanFly: 2,
		EatsFish: 4,
		Endangered: 8
	});
	AnimalFlags.EndangeredFlyingClawedFishEating = AnimalFlags(AnimalFlags.HasClaws | AnimalFlags.CanFly | AnimalFlags.EatsFish | AnimalFlags.Endangered);
	AnimalFlags.Predator = AnimalFlags(AnimalFlags.CanFly | AnimalFlags.HasClaws);
};