text:
static void enableMouseCursor( void )
{
    int centerPosX, centerPosY;

    if( !_glfwWin.opened || !_glfwWin.mouseLock )
    {
        return;
    }

    // Show mouse cursor
    _glfwPlatformShowMouseCursor();

    centerPosX = _glfwWin.width / 2;
    centerPosY = _glfwWin.height / 2;

    if( centerPosX != _glfwInput.MousePosX || centerPosY != _glfwInput.MousePosY )
    {
        _glfwPlatformSetMouseCursorPos( centerPosX, centerPosY );

        _glfwInput.MousePosX = centerPosX;
        _glfwInput.MousePosY = centerPosY;

        if( _glfwWin.mousePosCallback )
        {
            _glfwWin.mousePosCallback( _glfwInput.MousePosX,
                                       _glfwInput.MousePosY );
        }
    }

    // From now on the mouse is unlocked
    _glfwWin.mouseLock = GL_FALSE;
}

//========================================================================
// Disable (hide) mouse cursor
//========================================================================

static void disableMouseCursor( void )
{
    if( !_glfwWin.opened || _glfwWin.mouseLock )
    {
        return;
    }

    // Hide mouse cursor
    _glfwPlatformHideMouseCursor();

    // Move cursor to the middle of the window
    _glfwPlatformSetMouseCursorPos( _glfwWin.width >> 1,
                                    _glfwWin.height >> 1 );

    // From now on the mouse is locked
    _glfwWin.mouseLock = GL_TRUE;
}

//========================================================================
// Enable sticky keys
//========================================================================

static void enableStickyKeys( void )
{
    _glfwInput.StickyKeys = 1;
}

//========================================================================
// Disable sticky keys
//========================================================================

static void disableStickyKeys( void )
{
    int i;

    _glfwInput.StickyKeys = 0;

    // Release all sticky keys
    for( i = 0; i <= GLFW_KEY_LAST; i++ )
    {
        if( _glfwInput.Key[ i ] == 2 )
        {
            _glfwInput.Key[ i ] = 0;
        }
    }
}

//========================================================================
// Enable sticky mouse buttons
//========================================================================

static void enableStickyMouseButtons( void )
{
    _glfwInput.StickyMouseButtons = 1;
}

//========================================================================
// Disable sticky mouse buttons
//========================================================================

static void disableStickyMouseButtons( void )
{
    int i;

    _glfwInput.StickyMouseButtons = 0;

    // Release all sticky mouse buttons
    for( i = 0; i <= GLFW_MOUSE_BUTTON_LAST; i++ )
    {
        if( _glfwInput.MouseButton[ i ] == 2 )
        {
            _glfwInput.MouseButton[ i ] = 0;
        }
    }
}

//========================================================================
// Enable system keys
//========================================================================

static void enableSystemKeys( void )
{
    if( !_glfwWin.sysKeysDisabled )
    {
        return;
    }

    _glfwPlatformEnableSystemKeys();

    // Indicate that system keys are no longer disabled
    _glfwWin.sysKeysDisabled = GL_FALSE;
}

//========================================================================
// Disable system keys
//========================================================================

static void disableSystemKeys( void )
{
    if( _glfwWin.sysKeysDisabled )
    {
        return;
    }

    _glfwPlatformDisableSystemKeys();

    // Indicate that system keys are now disabled
    _glfwWin.sysKeysDisabled = GL_TRUE;
}

//========================================================================
// Enable key repeat
//========================================================================

static void enableKeyRepeat( void )
{
    _glfwInput.KeyRepeat = 1;
}

//========================================================================
// Disable key repeat
//========================================================================

static void disableKeyRepeat( void )
{
    _glfwInput.KeyRepeat = 0;
}

//========================================================================
// Enable automatic event polling
//========================================================================

static void enableAutoPollEvents( void )
{
    _glfwWin.autoPollEvents = 1;
}

//========================================================================
// Disable automatic event polling
//========================================================================

static void disableAutoPollEvents( void )
{
    _glfwWin.autoPollEvents = 0;
}

//************************************************************************
//****                    GLFW user functions                         ****
//************************************************************************

//========================================================================
// Enable certain GLFW/window/system functions.
//========================================================================

GLFWAPI void GLFWAPIENTRY glfwEnable( int token )
{
    // Is GLFW initialized?
    if( !_glfwInitialized )
    {
        return;
    }

    switch( token )
    {
        case GLFW_MOUSE_CURSOR:
            enableMouseCursor();
            break;
        case GLFW_STICKY_KEYS:
            enableStickyKeys();
            break;
        case GLFW_STICKY_MOUSE_BUTTONS:
            enableStickyMouseButtons();
            break;
        case GLFW_SYSTEM_KEYS:
            enableSystemKeys();
            break;
        case GLFW_KEY_REPEAT:
            enableKeyRepeat();
            break;
        case GLFW_AUTO_POLL_EVENTS:
            enableAutoPollEvents();
            break;
        default:
            break;
    }
}

//========================================================================
// Disable certain GLFW/window/system functions.
//========================================================================

GLFWAPI void GLFWAPIENTRY glfwDisable( int token )
{
    // Is GLFW initialized?
    if( !_glfwInitialized )
    {
        return;
    }

    switch( token )
    {
        case GLFW_MOUSE_CURSOR:
            disableMouseCursor();
            break;
        case GLFW_STICKY_KEYS:
            disableStickyKeys();
            break;
        case GLFW_STICKY_MOUSE_BUTTONS:
            disableStickyMouseButtons();
            break;
        case GLFW_SYSTEM_KEYS:
            disableSystemKeys();
            break;
        case GLFW_KEY_REPEAT:
            disableKeyRepeat();
            break;
        case GLFW_AUTO_POLL_EVENTS:
            disableAutoPollEvents();
            break;
        default:
            break;
    }
}


text:
package endian

import "encoding/binary"

var Native = binary.BigEndian

const (
	IsBigEndian     = true
	NativeEndian    = BigEndian
	NonNativeEndian = LittleEndian
)

redpajama_set_name: RedPajamaGithub


text:
namespace Jobbie.Sample.Scheduler.Host.Infrastructure.WebApi.Hosting
{
    internal sealed class HostConfiguration : IHostConfiguration
    {
        public string Url => "http://*:31900";

        public override string ToString() => $"Url={Url}";
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    tools:context="br.ifcibirama.dell_pc.javaisfun.BoasPraticas5">

    <Button
        android:id="@+id/button37"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="164dp"
        android:layout_height="52dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@color/colorPrimary"
        android:onClick="executar"
        android:text="Executar"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.719" />

    <TextView
        android:id="@+id/textView380"
        android:layout_width="347dp"
        android:layout_height="53dp"

        android:background="@color/caixa_de_texto"
        android:paddingLeft="20dp"
        android:paddingTop="10dp"
        android:textAlignment="viewStart"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.863" />

    <TextView
        android:id="@+id/textView376"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="}"
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.133"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.584" />

    <TextView
        android:id="@+id/textView379"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text='");'
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.975"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.535" />

    <TextView
        android:id="@+id/textView378"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text='System.out.println("'
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.32"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.535" />

    <TextView
        android:id="@+id/textView377"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="public static void main(String[] args){"
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.483"
        app:layout_constraintHorizontal_bias="0.509" />

    <ImageButton
        android:id="@+id/imageButton166"
        android:layout_width="28dp"
        android:layout_height="31dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/transparent"
        android:contentDescription="@string/menu"
        android:onClick="TextDialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.023"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.015"
        app:srcCompat="@drawable/back" />

    <TextView
        android:id="@+id/textView373"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:fontFamily="sans-serif"
        android:text="Execução e verificação"
        android:textAlignment="center"
        android:textColor="@android:color/holo_blue_dark"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.124"
        app:layout_constraintHorizontal_bias="0.513" />

    <ImageButton
        android:id="@+id/imageButton167"
        android:layout_width="42dp"
        android:layout_height="38dp"
        android:layout_marginBottom="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:background="@android:color/transparent"
        android:onClick="next"
        android:scaleType="fitXY"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.973"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0"
        app:srcCompat="@drawable/proximo" />

    <TextView
        android:id="@+id/textView374"
        android:layout_width="291dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Para isso temos que ir no método main e escrever o Hello World!"
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.385"
        app:layout_constraintHorizontal_bias="0.509" />

    <TextView
        android:id="@+id/textView375"
        android:layout_width="291dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="7dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Vamos lá, agora que já sabemos printar podemos fazer nosso primeiro Hello World em Java!"
        android:textAlignment="center"
        android:textColor="@color/cinzinha"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.246"
        app:layout_constraintHorizontal_bias="0.509" />

    <EditText
        android:id="@+id/editText9"
        android:layout_width="100dp"
        android:layout_height="40dp"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textNoSuggestions|textVisiblePassword"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.889"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.528" />
</android.support.constraint.ConstraintLayout>


text:
package eu.monnetproject.math.sparse;

import it.unimi.dsi.fastutil.ints.IntSet;
import java.util.Map;
import java.util.Set;

/**
 * A sparse array of some values
 *
 * @author John McCrae
 */
public interface Vector<N extends Number> {

    /**
     * The value at the given index. Note the default value will be returned at
     * sparse indexes
     *
     * @param idx The index
     * @return The value
     */
    double doubleValue(int idx);

    /**
     * The value at the given index. Note the default value will be returned at
     * sparse indexes
     *
     * @param idx The index
     * @return The value
     */
    int intValue(int idx);

    /**
     * The value at the given index. Note the default value will be returned at
     * sparse indexes
     *
     * @param idx The index
     * @return The value
     */
    N value(int idx);

    /**
     * Set a value at a given index
     *
     * @param idx The index
     * @param n The value
     * @return The previous value
     */
    N put(Integer idx, N n);

    /**
     * Set a value at a given index
     *
     * @param idx The index
     * @param n The value
     * @return The previous value
     */
    double put(int idx, double value);

    /**
     * Set a value at a given index
     *
     * @param idx The index
     * @param n The value
     * @return The previous value
     */
    int put(int idx, int value);

    /**
     * Add a value to the sparse array. This will automatically remove an
     * element if it results in the value at this index being the sparse value
     *
     * @param idx The index
     * @param val The value
     */
    int add(int idx, int val);

    /**
     * Subtract a value from the sparse array. This will automatically remove an
     * element if it results in the value at this index being the sparse value
     *
     * @param idx The index
     * @param val The value
     */
    void sub(int idx, int val);

    /**
     * Multiply a value by a value in the sparse array. This will automatically
     * remove an element if it results in the value at this index being the
     * sparse value
     *
     * @param idx The index
     * @param val The value
     */
    void multiply(int idx, int val);

    /**
     * Divide a value by a value in the sparse array. This will automatically
     * remove an element if it results in the value at this index being the
     * sparse value
     *
     * @param idx The index
     * @param val The value
     */
    void divide(int idx, int val);

    /**
     * Add a value to the sparse array. This will automatically remove an
     * element if it results in the value at this index being the sparse value
     *
     * @param idx The index
     * @param val The value
     */
    double add(int idx, double val);

    /**
     * Subtract a value from the sparse array. This will automatically remove an
     * element if it results in the value at this index being the sparse value
     *
     * @param idx The index
     * @param val The value
     */
    void sub(int idx, double val);

    /**
     * Multiply a value by a value in the sparse array. This will automatically
     * remove an element if it results in the value at this index being the
     * sparse value
     *
     * @param idx The index
     * @param val The value
     */
    void multiply(int idx, double val);

    /**
     * Divide a value by a value in the sparse array. This will automatically
     * remove an element if it results in the value at this index being the
     * sparse value
     *
     * @param idx The index
     * @param val The value
     */
    void divide(int idx, double val);

    /**
     * Add a vector to this vector. This will automatically remove an element if
     * it results in the value at this index being the sparse value
     *
     * @param vector The vector
     */
    <M extends Number> void add(Vector<M> vector);

    /**
     * Subtract a vector from this vector. This will automatically remove an
     * element if it results in the value at this index being the sparse value
     *
     * @param idx The index
     * @param val The value
     */
    <M extends Number> void sub(Vector<M> vector);

    /**
     * Multiply all values of this matrix by a value
     *
     * @param n The value to multiply by
     */
    void multiply(double n);

    /**
     * Calculate the inner product of this array with another array, i.e.,
     * this^T y
     *
     * @param y The other array
     * @return The inner product
     */
    <M extends Number> double innerProduct(Vector<M> y);

    /**
     * Calculate the outer product of this array with another array i.e., this
     * y^T
     *
     * @param y The other array
     * @param using The factory for creating rows of the matrix
     * @return The outer product matrix
     */
    <M extends Number, O extends Number> Matrix<O> outerProduct(Vector<M> y, Vectors.Factory<O> using);

    /**
     * Get all non-sparse values in the array
     */
    Set<Map.Entry<Integer, N>> entrySet();

    /**
     * Convert to a dense array
     */
    double[] toDoubleArray();

    /**
     * Get the number of non-sparse values in the array
     */
    int size();

    /**
     * Get the default value of the array
     */
    N defaultValue();

    /**
     * Get the length (i.e., number of sparse and non-sparse values) of the
     * array
     */
    int length();

    /**
     * Return the 2-norm.
     */
    double norm();

    /**
     * Creates a copy of this vector
     */
    Vector<N> clone();

    /**
     * The factory for making more of this type of vector
     *
     * @return
     */
    Vectors.Factory<N> factory();

    /**
     * Get the set of indices with non-default value
     *
     * @return
     */
    IntSet keySet();

    /**
     * Is the following index in range and with non-default value
     *
     * @param idx
     * @return
     */
    boolean containsKey(int idx);

    /**
     * Get the sum of all the values in this vector
     *
     * @return
     */
    N sum();

    /**
     * Create a subvector
     * @param offset The first index to return
     * @param length The length of the index to return
     * @return
     */
    Vector<N> subvector(int offset, int length);
}


text:
"""This module implements the logic of the operations for selecting,
unselecting, expanding, hiding, showing etc. of clusters of
streamlines. It basically provides set operations for streamline IDs.

Copyright (c) 2012-2014, Emanuele Olivetti and Eleftherios Garyfallidis
Distributed under the BSD 3-clause license. See COPYING.txt.
"""

import numpy as np
import random
import copy
import code

def clustering_random(data, clusters_number, streamline_ids, seed=0):
    """Create fake clustering just playing randomly with streamline
    ids. For testing purpose.
    """
    if clusters_number > len(streamline_ids):
        clusters_number = len(streamline_ids)
        print "clustering_function WARNING: clusters_number > len(streamline_ids)"

    random.seed(seed)
    representatives = set(random.sample(streamline_ids, clusters_number))
    what_remains = set(streamline_ids).difference(representatives)
    random_splits_ids = np.random.randint(low=0, high=len(representatives), size=len(what_remains))
    clusters = {}
    what_remains = np.array(list(what_remains))
    for i, representative in enumerate(representatives):
        clusters[representative] = set(what_remains[random_splits_ids==i].tolist()).union([representative])

    return clusters

class Manipulator(object):
    """This class provides the functions to manipulate streamline IDs
    that can suit an interactive session. It provides history
    capabilities and other amenities.
    """

    def __init__(self, initial_clusters, clustering_function):
        """Initialize the object.
        """
        self.initial_clusters = copy.deepcopy(initial_clusters)
        self.history = []
        self.streamline_ids = 0
        self.numstream_handler = EventHook()
        self.numrep_handler = EventHook()
        self.remselect_handler = EventHook()
        self.clusters_reset(initial_clusters)
        self.simple_history_start()
        self.clustering_function = clustering_function

    def clusters_reset(self, clusters):
        """Standard operations to do whenever self.clusters is
        modified.
        """
        self.clusters = clusters
        self.streamline_ids = reduce(set.union, clusters.values())
        self.representative_ids = set(self.clusters.keys())
        self.selected = set()
        self.expanded = set()
        self.show_representatives = True
        self.history.append('clusters_reset('+str(clusters)+')')
        self.numstream_handler.fire(len(self.streamline_ids))
        self.numrep_handler.fire(len(self.representative_ids))

    def select(self, representative_id):
        """Select one representative.
        """
        assert(representative_id in self.representative_ids)
        assert(representative_id not in self.selected)
        self.selected.add(representative_id)
        self.history.append('select('+str(representative_id)+')')
        self.select_action(representative_id)

    def select_action(self, representative_id):
        """This is the actual action to perform in the application.
        """
        pass

    def unselect(self, representative_id):
        """Select one representative.
        """
        assert(representative_id in self.representative_ids)
        assert(representative_id in self.selected)
        self.selected.remove(representative_id)
        self.history.append('unselect('+str(representative_id)+')')
        self.unselect_action(representative_id)

    def unselect_action(self, representative_id):
        """This is the actual action to perform in the application.
        """
        pass

    def select_toggle(self, representative_id):
        """Toggle for dispatching select or unselect.
        """
        if representative_id not in self.selected:
            self.select(representative_id)
        else:
            self.unselect(representative_id)

    def select_all(self):
        """Select all streamlines.
        """
        # it is safer to make a copy of the ids to avoid subtle
        # dependecies when manipulating self.representative_ids in
        # later steps.
        self.selected = set(copy.deepcopy(self.representative_ids))
        self.history.append('select_all()')
        self.select_all_action()

    def select_all_action(self):
        pass

    def unselect_all(self):
        self.selected = set()
        self.history.append('unselect_all()')
        self.unselect_all_action()

    def unselect_all_action(self):
        pass

    def select_all_toggle(self):
        if self.selected == self.representative_ids:
            self.unselect_all()
        else:
            self.select_all()

    def remove_selected(self):
        """Remove all clusters whose representative is selected.
        """
        clusters = {}
        for representative in set(self.representative_ids).difference(self.selected):
            clusters[representative] = self.clusters[representative]
        self.clusters_reset(clusters)
        self.history.append('remove_selected()')
        self.remove_selected_action()
        self.remselect_handler.fire(True)

    def remove_selected_action(self):
        pass

    def remove_unselected(self):
        """Remove all clusters whose representative is not selected.
        """
        clusters = {}
        for representative in self.selected:
            clusters[representative] = self.clusters[representative]
        self.clusters_reset(clusters)
        self.history.append('remove_unselected()')
        self.simple_history_store()
        self.remove_unselected_action()
        self.remselect_handler.fire(True)

    def remove_unselected_action(self):
        pass

    def recluster(self, clustering_parameter, data=None):
        """Operate self.clustering with clustering_parameter on the
        current objects.
        """
        streamline_ids_new = reduce(set.union, self.clusters.values())
        clusters_new = self.clustering_function(data, clustering_parameter, streamline_ids_new)
        # sanity check:
        assert(streamline_ids_new == reduce(set.union, clusters_new.values()))
        self.history.append('recluster('+str(clustering_parameter)+')')
        self.clusters_reset(clusters_new)
        self.simple_history_store()
        self.recluster_action()

    def recluster_action(self):
        pass

    def invert(self):
        """Invert the selection of representatives.
        """
        self.selected = self.representative_ids.difference(self.selected)
        self.history.append('invert()')
        self.invert_action()

    def invert_action(self):
        pass

    def show_representatives(self):
        """Show representatives.
        """
        self.show_representatives = True
        self.history.append('show_representatives()')

    def hide_representatives(self):
        """Do not show representatives.
        """
        self.show_representatives = False
        self.history.append('hide_representatives()')

    def expand_collapse_selected(self):
        """Toggle expand/collapse status of selected representatives.
        """
        self.expand = not self.expand
        self.history.append('expand_collapse_selected()')
        self.expand_collapse_selected_action()

    def expand_collapse_selected_action(self):
        pass

    def replay_history(self, until=None):
        """Create a Manipulator object by replaying the history of
        self starting from self.initial_clusters.
        """
        m = Manipulator(self.initial_clusters, self.clustering_function)
        # skip the first action in the history because already done
        # during __init__():
        c = ['m.'+h for h in self.history[1:until]]
        c = '; '.join(c)
        c = code.compile_command(c)
        exec(c)
        return m

    def simple_history_start(self):
        """Start simple history.
        """
        self.simple_history = [copy.deepcopy(self.clusters)]
        self.simple_history_pointer = 0
        print "Simple history started."

    def simple_history_store(self):
        """Store the current clusters into the history. If there are
        future steps stored in the history, then throw them away
        first.
        """
        if self.simple_history_pointer < len(self.simple_history)-1:
            print "Removing future steps."
            self.simple_history = self.simple_history[:self.simple_history_pointer+1]

        print "Appending to the existing simple history."
        self.simple_history.append(copy.deepcopy(self.clusters))
        self.simple_history_pointer += 1

    def simple_history_back_one_step(self):
        """Go back one step into the past.
        """
        if self.simple_history_pointer == 0:
            print "We are at the initial step and cannot go backward."
        else:
            self.simple_history_pointer -= 1
            self.clusters_reset(self.simple_history[self.simple_history_pointer])
            self.recluster_action()

    def simple_history_forward_one_step(self):
        """Go one step into the future.
        """
        if self.simple_history_pointer == len(self.simple_history)-1:
            print "We are at the last step and cannot go forward."
        else:
            self.simple_history_pointer += 1
            self.clusters_reset(self.simple_history[self.simple_history_pointer])
            self.recluster_action()

    def get_state(self):
        """Create a dictionary from which it is possible to
        reconstruct the current Manipulator.
        """
        state = {}
        state['clusters'] = copy.deepcopy(self.clusters)
        state['selected'] = copy.deepcopy(self.selected)
        state['expand'] = self.expand
        state['simple_history'] = copy.deepcopy(self.simple_history)
        state['simple_history_pointer'] = copy.deepcopy(self.simple_history_pointer)
        return state

    def set_state(self, state):
        """Set the current object with a given state. Useful to
        serialize the Manipulator to file etc.
        """
        self.clusters_reset(state['clusters'])
        self.selected = state['selected']
        self.expand = state['expand']
        self.simple_history = state['simple_history']
        self.simple_history_pointer = state['simple_history_pointer']
        self.recluster_action()

    def __str__(self):
        string = "Clusters: " + str(self.clusters)
        string += "\n"
        string += "Selected: " + str(self.selected)
        string += "\n"
        string += "Show Representatives: " + str(self.show_representatives)
        string += "\n"
        string += "Initial Clusters: " + str(self.initial_clusters)
        string += "\n"
        string += "History: " + str(self.history)
        return string

class EventHook(object):
    """
    Class that allows simulating the events-delegate functionality.
    Check later if there is a simplest way to do it in a more
    Pythonian way.
    """
    def __init__(self):
        self.__handlers = []

    def __iadd__(self, handler):
        self.__handlers.append(handler)
        return self

    def __isub__(self, handler):
        self.__handlers.remove(handler)
        return self

    def fire(self, *args, **keywargs):
        for handler in self.__handlers:
            handler(*args, **keywargs)

    def clearObjectHandlers(self, inObject):
        for theHandler in self.__handlers:
            if theHandler.im_self == inObject:
                self -= theHandler

if __name__ == '__main__':

    seed = 0
    random.seed(0)
    np.random.seed(0)

    clustering = clustering_random
    k = 3

    streamline_ids = np.arange(10, dtype=np.int)

    initial_clusters = clustering(None, k, streamline_ids)

    m = Manipulator(initial_clusters, clustering)

    print "Initial setting:"
    print "clusters:", m.clusters
    print "selected:", m.selected
    print "Select 3 and 6:"
    m.select_toggle(3)
    m.select_toggle(6)
    print "clusters:", m.clusters
    print "selected:", m.selected
    print "Invert selection:"
    m.invert()
    print "clusters:", m.clusters
    print "selected:", m.selected
    print "Remove unselected:"
    m.remove_unselected()
    print "clusters:", m.clusters
    print "selected:", m.selected
    print "Re-cluster into 2 clusters:"
    m.recluster(2)
    print "clusters:", m.clusters
    print "selected:", m.selected
    print "Select cluster 8:"
    m.select_toggle(8)
    print "clusters:", m.clusters
    print "selected:", m.selected
    print "Re-cluster into 2 clusters:"
    print "Remove unselected:"
    m.remove_unselected()
    print "clusters:", m.clusters
    print "selected:", m.selected
    m.recluster(2)
    print "clusters:", m.clusters
    print "selected:", m.selected


text:
import BallSprite from 'objects/BallSprite';
import { gameProperties, playerProperties, graphicAssets, soundAssets, audioAssets, fontAssets, labels } from '../config';

class GameStateMenu extends Phaser.State {
	initGraphics() {
		this.backgroundGraphics = this.game.add.graphics(0, 0);

		this.ballSprite = new BallSprite(this.game, this.game.world.centerX, this.game.world.centerY, this.randomCharacter());

		this.backgroundSprite = this.game.add.tileSprite(0, 0, gameProperties.screenWidth, gameProperties.screenHeight, 'background');
		this.backgroundSprite.visible = false;

		this.logoSprite = this.game.add.sprite(this.game.world.centerX, 240, 'logo');
		this.logoSprite.anchor.set(0.5, 0.5);

		this.instructions = this.game.add.text(this.game.world.centerX, 370, labels.instructionsMenu, fontAssets.instructionsFontStyle);
		this.instructions.anchor.set(0.5, 0.5);
	}

	initSounds() {
		this.audio = [];
		for(let groupKey in audioAssets){
			for(let assetKey in audioAssets[groupKey]){
				this.audio[groupKey+'-'+assetKey] = this.game.add.audio(groupKey+'-'+assetKey);
			}
		}
		//this.game.sound.mute = true;
	}

	randomCharacter() {
		return this.game.rnd.integerInRange(0, graphicAssets.balls.length - 1);
	}

	startDemo() {
		this.ballSprite.reinitialize();
		this.backgroundGraphics.lineStyle(2, 0x000000, 1);
		this.game.stage.backgroundColor = '#000';
		this.logoSprite.visible = true;
		this.backgroundSprite.visible = false;
	}

	create() {
		this.initGraphics();
		this.initSounds();

		this.game.physics.startSystem(Phaser.Physics.ARCADE);
		this.game.physics.enable(this.ballSprite);

		this.ballSprite.initPhysics();

		this.startDemo();

		this.game.input.onDown.add(() => this.state.start('GameStateSolo') , this);

		this.audio['music-background'].loop = true;
		this.audio['music-background'].play();
	}

	update(){
		if (this.game.input.keyboard.isDown(Phaser.Keyboard.SPACEBAR)) {
			this.state.start('GameState');
		}

		if (this.ballSprite.body.blocked.up || this.ballSprite.body.blocked.down || this.ballSprite.body.blocked.left || this.ballSprite.body.blocked.right) {
			this.audio['sound-bounce'].play();
		}
	}
}

export default GameStateMenu;


text:
This repository contains extra samples and SAS macros that can be used with the
[Metacoda® Identity Sync Plug-in](https://www.metacoda.com/en/products/security-plug-ins/identity-sync/).
Metacoda customers and partners, and potentially other SAS customers, may find these utilities
useful when setting up an identity synchronisation process between a [SAS®](http://www.sas.com/)
Metadata Server and an external identity provider, such as Microsoft Active Directory.

## Documentation

The documentation is generated using [MkDocs](http://www.mkdocs.org/), from the sources in this
repositories docs/ folder, and hosted using GitHub pages at
<https://metacoda.github.io/idsync-utils/>.

## License

See [License](docs/about/license.md)

## Trademarks

See [Trademarks](docs/about/trademarks.md)


text:
package org.apache.cloudstack.api.agent.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.cloud.agent.api.AttachVolumeCommand;
import com.cloud.storage.Storage.StoragePoolType;

public class AttachVolumeCommandTest {
    AttachVolumeCommand avc = new AttachVolumeCommand(true, false, "vmname",
            StoragePoolType.Filesystem, "vPath", "vName",
            123456789L, "chainInfo");

    @Test
    public void testExecuteInSequence() {
        boolean b = avc.executeInSequence();
        assertTrue(b);
    }

    @Test
    public void testGetAttach() {
        boolean b = avc.getAttach();
        assertTrue(b);
    }

    @Test
    public void testGetVmName() {
        String vmName = avc.getVmName();
        assertTrue(vmName.equals("vmname"));
    }

    @Test
    public void testGetPooltype() {
        StoragePoolType pt = avc.getPooltype();
        assertTrue(pt.equals(StoragePoolType.Filesystem));

        avc.setPooltype(StoragePoolType.NetworkFilesystem);
        pt = avc.getPooltype();
        assertTrue(pt.equals(StoragePoolType.NetworkFilesystem));

        avc.setPooltype(StoragePoolType.IscsiLUN);
        pt = avc.getPooltype();
        assertTrue(pt.equals(StoragePoolType.IscsiLUN));

        avc.setPooltype(StoragePoolType.Iscsi);
        pt = avc.getPooltype();
        assertTrue(pt.equals(StoragePoolType.Iscsi));
    }

    @Test
    public void testGetVolumePath() {
        String vPath = avc.getVolumePath();
        assertTrue(vPath.equals("vPath"));
    }

    @Test
    public void testGetVolumeName() {
        String vName = avc.getVolumeName();
        assertTrue(vName.equals("vName"));
    }

    @Test
    public void testGetDeviceId() {
        Long dId = avc.getDeviceId();
        Long expected = 123456789L;
        assertEquals(expected, dId);

        avc.setDeviceId(5L);
        dId = avc.getDeviceId();
        expected = 5L;
        assertEquals(expected, dId);

        avc.setDeviceId(0L);
        dId = avc.getDeviceId();
        expected = 0L;
        assertEquals(expected, dId);

        avc.setDeviceId(-5L);
        dId = avc.getDeviceId();
        expected = -5L;
        assertEquals(expected, dId);
    }

    @Test
    public void testGetPoolUuid() {
        avc.setPoolUuid("420fa39c-4ef1-a83c-fd93-46dc1ff515ae");
        String pUuid = avc.getPoolUuid();
        assertTrue(pUuid.equals("420fa39c-4ef1-a83c-fd93-46dc1ff515ae"));
    }

    @Test
    public void testGetWait() {
        String cInfo = avc.getChainInfo();
        assertTrue(cInfo.equals("chainInfo"));
    }
}


text:
try:
    # Python 2.7
    from collections import OrderedDict
except:
    # Python 2.6
    from gluon.contrib.simplejson.ordered_dict import OrderedDict

try:
    import json # try stdlib (Python 2.6)
except ImportError:
    try:
        import simplejson as json # try external module
    except:
        import gluon.contrib.simplejson as json # fallback to pure-Python module

from gluon import current
from gluon.storage import Storage

def config(settings):
    """
        Template settings for CAP: Common Alerting Protocol
    """

    T = current.T

    settings.base.system_name = T("Sahana Alerting and Messaging Broker")
    settings.base.system_name_short = T("SAMBRO")

    # Pre-Populate
    settings.base.prepopulate += ("SAMBRO", "SAMBRO/Demo", "default/users")

    # Theme (folder to use for views/layout.html)
    #settings.base.theme = "SAMBRO"

    # The Registration functionality shouldn't be visible to the Public
    settings.security.registration_visible = False

    # Link Users to Organisations
    settings.auth.registration_requests_organisation = True

    # GeoNames username
    settings.gis.geonames_username = "eden_test"

    # =========================================================================
    # System Settings
    # -------------------------------------------------------------------------
    # Security Policy
    # http://eden.sahanafoundation.org/wiki/S3/S3AAA#System-widePolicy
    # 1: Simple (default): Global as Reader, Authenticated as Editor
    # 2: Editor role required for Update/Delete, unless record owned by session
    # 3: Apply Controller ACLs
    # 4: Apply both Controller & Function ACLs
    # 5: Apply Controller, Function & Table ACLs
    # 6: Apply Controller, Function, Table ACLs and Entity Realm
    # 7: Apply Controller, Function, Table ACLs and Entity Realm + Hierarchy
    # 8: Apply Controller, Function, Table ACLs, Entity Realm + Hierarchy and Delegations
    settings.security.policy = 4 # Controller-Function ACLs

    # Record Approval
    settings.auth.record_approval = True
    # cap_alert record requires approval before sending
    settings.auth.record_approval_required_for = ("cap_alert",)
    # Don't auto-approve so that can save draft
    settings.auth.record_approval_manual = ("cap_alert",)

    # =========================================================================
    # Module Settings
    # -------------------------------------------------------------------------
    # CAP Settings
    # Uncomment this according to country profile
    #settings.cap.restrict_fields = True

    # -------------------------------------------------------------------------
    # Notifications

    # Template for the subject line in update notifications
    settings.msg.notify_subject = "$S %s" % T("Alert Notification")

    # Filename for FTP
    # Characters not allowed are [\ / : * ? " < > | % .]
    # https://en.wikipedia.org/wiki/Filename
    # http://docs.attachmate.com/reflection/ftp/15.6/guide/en/index.htm?toc.htm?6503.htm
    settings.sync.upload_filename = "$s-%s" % ("recent_alert")

    # -------------------------------------------------------------------------
    # L10n (Localization) settings
    languages = OrderedDict([
        #("ar", "العربية"),
        ("dv", "ދިވެހި"), # Divehi (Maldives)
        ("en-US", "English"),
        #("es", "Español"),
        #("fr", "Français"),
        #("km", "ភាសាខ្មែរ"),        # Khmer
        #("mn", "Монгол хэл"),  # Mongolian
        ("my", "မြန်မာစာ"),        # Burmese
        #("ne", "नेपाली"),          # Nepali
        #("prs", "دری"),        # Dari
        #("ps", "پښتو"),        # Pashto
        #("tet", "Tetum"),
        #("th", "ภาษาไทย"),        # Thai
        ("tl", "Tagalog"), # Filipino
        #("vi", "Tiếng Việt"),   # Vietnamese
        #("zh-cn", "中文 (简体)"),
    ])
    settings.L10n.languages = languages
    settings.cap.languages = languages
    # Translate the cap_area name
    settings.L10n.translate_cap_area = True

    # -------------------------------------------------------------------------
    # Messaging
    # Parser
    settings.msg.parser = "SAMBRO"

    # -------------------------------------------------------------------------
    # Organisations
    # Enable the use of Organisation Branches
    settings.org.branches = True
    # Show branches as tree rather than as table
    settings.org.branches_tree_view = True

    # -------------------------------------------------------------------------
    def customise_msg_rss_channel_resource(r, tablename):

        # @ToDo: We won't be able to automate this as we have 2 sorts, so will need the user to select manually
        # Can we add a component for the parser for S3CSV imports?

        # UX: separate menu items distinguished via get_var
        # @ToDo: Add menu entries for "Create RSS Feed for CAP" & "Create RSS Feed for CMS"
        type = current.request.get_vars.get("type", None)
        if type == "cap":
            fn = "parse_rss_2_cap"
        else:
            fn = "parse_rss_2_cms"

        s3db = current.s3db
        def onaccept(form):
            # Normal onaccept
            s3db.msg_channel_onaccept(form)
            _id = form.vars.id
            db = current.db
            table = db.msg_rss_channel
            channel_id = db(table.id == _id).select(table.channel_id,
                                                    limitby=(0, 1)).first().channel_id
            # Link to Parser
            table = s3db.msg_parser
            _id = table.insert(channel_id=channel_id, function_name=fn, enabled=True)
            s3db.msg_parser_enable(_id)

            async = current.s3task.async
            # Poll
            async("msg_poll", args=["msg_rss_channel", channel_id])

            # Parse
            async("msg_parse", args=[channel_id, fn])

        s3db.configure(tablename,
                       create_onaccept = onaccept,
                       )

    settings.customise_msg_rss_channel_resource = customise_msg_rss_channel_resource

    # -------------------------------------------------------------------------
    def customise_msg_twitter_channel_resource(r, tablename):

        s3db = current.s3db
        def onaccept(form):
            # Normal onaccept
            s3db.msg_channel_onaccept(form)
            _id = form.vars.id
            db = current.db
            table = db.msg_twitter_channel
            channel_id = db(table.id == _id).select(table.channel_id,
                                                    limitby=(0, 1)).first().channel_id
            # Link to Parser
            table = s3db.msg_parser
            _id = table.insert(channel_id=channel_id, function_name="parse_tweet", enabled=True)
            s3db.msg_parser_enable(_id)

            async = current.s3task.async
            # Poll
            async("msg_poll", args=["msg_twitter_channel", channel_id])

            # Parse
            async("msg_parse", args=[channel_id, "parse_tweet"])

        s3db.configure(tablename,
                       create_onaccept = onaccept,
                       )

    settings.customise_msg_twitter_channel_resource = customise_msg_twitter_channel_resource

    # -------------------------------------------------------------------------
    def customise_org_organisation_resource(r, tablename):

        from s3 import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineLink
        crud_form = S3SQLCustomForm("name",
                                    "acronym",
                                    S3SQLInlineLink("organisation_type",
                                                    field = "organisation_type_id",
                                                    label = T("Type"),
                                                    multiple = False,
                                                    #widget = "hierarchy",
                                                    ),
                                    S3SQLInlineComponent(
                                        "tag",
                                        label = T("CAP OID"),
                                        multiple = False,
                                        fields = [("", "value")],
                                        filterby = dict(field = "tag",
                                                        options = "cap_oid",
                                                        ),
                                        ),
                                    "website",
                                    "comments",
                                    )

        current.s3db.configure("org_organisation",
                               crud_form = crud_form,
                               )

    settings.customise_org_organisation_resource = customise_org_organisation_resource

    # -------------------------------------------------------------------------
    def customise_cap_alert_resource(r, tablename):

        s3db = current.s3db
        def onapprove(record):
            # Normal onapprove
            s3db.cap_alert_approve(record)

            # Sync FTP Repository
            current.s3task.async("cap_ftp_sync")

        s3db.configure(tablename,
                       onapprove = onapprove,
                       )

    settings.customise_cap_alert_resource = customise_cap_alert_resource

    # -------------------------------------------------------------------------
    def customise_sync_repository_controller(**attr):

        s3 = current.response.s3

        # Custom prep
        standard_prep = s3.prep
        def custom_prep(r):
            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
            else:
                result = True

            if r.representation == "popup":
                table = r.table
                table.apitype.default = "ftp"
                table.apitype.readable = table.apitype.writable = False
                table.accept_push.readable = table.accept_push.writable = False
                table.synchronise_uuids.readable = \
                                        table.synchronise_uuids.writable = False
                table.uuid.readable = table.uuid.writable = False

            return result
        s3.prep = custom_prep

        return attr

    settings.customise_sync_repository_controller = customise_sync_repository_controller

    # -------------------------------------------------------------------------
    def customise_cap_warning_priority_resource(r, tablename):

        s3db = current.s3db
        def onaccept(form):
            # Normal onaccept if any
            form_vars = form.vars
            color_code = form_vars.color_code
            if color_code:
                db = current.db
                stable = s3db.gis_style
                etable = s3db.gis_layer_entity
                rows = db(etable.instance_type == "gis_layer_feature"). \
                                                        select(etable.layer_id)
                query = (stable.layer_id.belongs([row.layer_id for row in rows]))
                rows = db(query).select(stable.id, stable.style)
                if rows:
                    from s3 import IS_JSONS3
                    name = form_vars.name
                    for row in rows:
                        style = row.style
                        if style:
                            if isinstance(style, basestring):
                                style = json.loads(style)
                            sdata = dict(prop = "priority",
                                         fill = color_code,
                                         fillOpacity = 0.4,
                                         cat = name,
                                         )
                            if sdata not in style:
                                style.append(sdata)
                                style = IS_JSONS3()(json.dumps(style))[0]
                                db(stable.id == row.id).update(style = style)

        s3db.configure(tablename,
                       create_onaccept = onaccept,
                       )

    settings.customise_cap_warning_priority_resource = customise_cap_warning_priority_resource

    # -------------------------------------------------------------------------
    # Comment/uncomment modules here to disable/enable them
    # @ToDo: Have the system automatically enable migrate if a module is enabled
    # Modules menu is defined in modules/eden/menu.py
    settings.modules = OrderedDict([
        # Core modules which shouldn't be disabled
        ("default", Storage(
            name_nice = T("Home"),
            restricted = False, # Use ACLs to control access to this module
            access = None,      # All Users (inc Anonymous) can see this module in the default menu & access the controller
            module_type = None  # This item is not shown in the menu
        )),
        ("admin", Storage(
            name_nice = T("Administration"),
            #description = "Site Administration",
            restricted = True,
            access = "|1|",     # Only Administrators can see this module in the default menu & access the controller
            module_type = None  # This item is handled separately for the menu
        )),
        ("appadmin", Storage(
            name_nice = T("Administration"),
            #description = "Site Administration",
            restricted = True,
            module_type = None  # No Menu
        )),
        ("errors", Storage(
            name_nice = T("Ticket Viewer"),
            #description = "Needed for Breadcrumbs",
            restricted = False,
            module_type = None  # No Menu
        )),
        ("sync", Storage(
            name_nice = T("Synchronization"),
            #description = "Synchronization",
            restricted = True,
            access = "|1|",     # Only Administrators can see this module in the default menu & access the controller
            module_type = None  # This item is handled separately for the menu
        )),
        #("tour", Storage(
        #    name_nice = T("Guided Tour Functionality"),
        #    module_type = None,
        #)),
        ("translate", Storage(
            name_nice = T("Translation Functionality"),
            #description = "Selective translation of strings based on module.",
            module_type = None,
        )),
        ("gis", Storage(
            name_nice = T("Mapping"),
            #description = "Situation Awareness & Geospatial Analysis",
            restricted = True,
            module_type = 6,     # 6th item in the menu
        )),
        ("pr", Storage(
            name_nice = T("Person Registry"),
            #description = "Central point to record details on People",
            restricted = True,
            access = "|1|",     # Only Administrators can see this module in the default menu (access to controller is possible to all still)
            module_type = 10
        )),
        ("org", Storage(
            name_nice = T("Organizations"),
            #description = 'Lists "who is doing what & where". Allows relief agencies to coordinate their activities',
            restricted = True,
            module_type = 10
        )),
        # All modules below here should be possible to disable safely
        #("hrm", Storage(
        #    name_nice = T("Staff"),
        #    #description = "Human Resources Management",
        #    restricted = True,
        #    module_type = 2,
        #)),
        ("cap", Storage(
            name_nice = T("Alerting"),
            #description = "Create & broadcast CAP alerts",
            restricted = True,
            module_type = 1,
        )),
        ("cms", Storage(
          name_nice = T("Content Management"),
          #description = "Content Management System",
          restricted = True,
          module_type = 10,
        )),
        ("doc", Storage(
            name_nice = T("Documents"),
            #description = "A library of digital resources, such as photos, documents and reports",
            restricted = True,
            module_type = 10,
        )),
        ("msg", Storage(
            name_nice = T("Messaging"),
            #description = "Sends & Receives Alerts via Email & SMS",
            restricted = True,
            # The user-visible functionality of this module isn't normally required. Rather it's main purpose is to be accessed from other modules.
            module_type = None,
        )),
        ("event", Storage(
            name_nice = T("Events"),
            #description = "Activate Events (e.g. from Scenario templates) for allocation of appropriate Resources (Human, Assets & Facilities).",
            restricted = True,
            module_type = 10,
        )),
    ])

# END =========================================================================


text:
package com.github.shredder121.gh_event_api.handler.gollum;

import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;

import com.github.shredder121.gh_event_api.GHEventApiServer;
import com.github.shredder121.gh_event_api.handler.AbstractHandlerTest;

@SpringApplicationConfiguration(classes = {GollumHandlerTest.class, GHEventApiServer.class})
public class GollumHandlerTest extends AbstractHandlerTest {

    public GollumHandlerTest() {
        super("gollum");
    }

    @Bean
    public TestHandler handlerBean() {
        return new TestHandler();
    }
}


text:
package com.dinglicom.pricepolicy.demain;

/**
 *
 * @author panzhen
 */
public class ProductRespItem {
    private Long id;
    private String name;

    /**
     * @return the id
     */
    public Long getId() {
        return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}


text:
import {magic_string_bundle} from '../../helpers';

export const component_filepath = 'src/some/deep/path/input.svelte';
export const component_file_basename = 'input.svelte';
export const css_file_basename = 'input.css';

const input_css = ' h1 {color: blue;}';

export default {
	preprocess: [
		{
			style: ({ content, filename }) => {
				const style_to_add = `/* Filename from preprocess: ${filename} */` + input_css;
				return  magic_string_bundle([
					{ code: content, filename: component_file_basename },
					{ code: style_to_add, filename: css_file_basename }
				],component_filepath);
			}
		}
	],
	js_map_sources: [component_file_basename],
	css_map_sources: [css_file_basename,component_file_basename],
	options: {
		filename: component_filepath
	},
	compile_options: {
		filename: component_filepath,
		// ../../index.ts initializes output filenames, reset to undefined for this test
		outputFilename: undefined,
		cssOutputFilename: undefined
	}
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:background="@drawable/start"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

</LinearLayout>


text:
template <typename T>
    class TYPESHARED_EXPORT Matrix
{
public:
    Matrix(void);
    Matrix(const QSize size, const T & t=T());
    Matrix(const QSize size, const QVector<T> tVector);
    Matrix(const Matrix<T> & other);

    void clear(void);
    void fill(const QSize size, const T & t=T());
    void fill(const T & t=T());
    void reset(void);
    void resize(const QSize size, const T & tNew=T());
    void set(const QSize size, const QVector<T> tVector);
    void set(const int row, const QVector<T> tVector);
    void set(const QPoint pt, const T & t);

    bool isNull(void) const;
    QSize size(void) const;
    QSize reserved(void) const;
    int reservedBytes(void) const;
    T at(const QPoint pt) const;
    QVector<T> rowData(const int row) const;

    T & operator = (const QPoint pt) const;
    T operator [](const QPoint pt) const;

    Integer index(const QPoint pt) const;

private:
    QSize mSize;
    QSize mReservedSize; // always a power of two on each dimension
    Integer mStrideShift;
    QVector<T> mVector;
};

#include "Matrix.cpp"

#endif // MATRIX_H


text:
/* Test file for syntactic errors. Contains exactly one error. */

foo(0);


text:
namespace SIS.WebServer
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Net.Sockets;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using SIS.HTTP.Common;
    using SIS.HTTP.Cookies;
    using SIS.HTTP.Enums;
    using SIS.HTTP.Requests;
    using SIS.HTTP.Requests.Contracts;
    using SIS.HTTP.Response;
    using SIS.HTTP.Response.Contracts;
    using SIS.HTTP.Sessions;
    using SIS.WebServer.Results;
    using SIS.WebServer.Routing;

    public class ConnectionHandler
    {
        private readonly Socket client;

        private readonly ServerRoutingTable serverRoutingTable;

        private const string RootDirectoryRelativePath = "../../../";

        public ConnectionHandler(Socket client, ServerRoutingTable serverRoutingTable)
        {
            this.client = client;
            this.serverRoutingTable = serverRoutingTable;
        }

        public async Task ProcessRequestAsync()
        {
            var httpRequest = await this.ReadRequest();

            if (httpRequest != null)
            {
                string sessionId = this.SetRequestSession(httpRequest);
                IHttpResponse httpResponse = this.HandleRequest(httpRequest);
                this.SetResponseSession(httpResponse, sessionId);
                await this.PrepareResponse(httpResponse);
            }

            this.client.Shutdown(SocketShutdown.Both);
        }

        private async Task PrepareResponse(IHttpResponse httpResponse)
        {
            byte[] byteSegments = httpResponse.GetBytes();

            WriteResponseToConsole(byteSegments);

            await this.client.SendAsync(byteSegments, SocketFlags.None);
        }

        private IHttpResponse HandleRequest(IHttpRequest httpRequest)
        {
            var isResourseRequest = this.IsResourseRequest(httpRequest);

            if (isResourseRequest)
            {
                return this.HandleRequestResponse(httpRequest.Path);
            }

            if (!this.serverRoutingTable.Routes.ContainsKey(httpRequest.RequestMethod)
               || !this.serverRoutingTable.Routes[httpRequest.RequestMethod].ContainsKey(httpRequest.Path))
            {
                return new HttpResponse(HttpResponseStatusCode.NotFound);
            }

            return this.serverRoutingTable.Routes[httpRequest.RequestMethod][httpRequest.Path].Invoke(httpRequest);
        }

        private IHttpResponse HandleRequestResponse(string httpRequestPath)
        {
            var indexOfStartOfExtention = httpRequestPath.LastIndexOf('.');
            var indexOfStartOfNameOfResource = httpRequestPath.LastIndexOf('/');

            //Example: .css
            var requestPathExtension = httpRequestPath.Substring(indexOfStartOfExtention);

            //Example: boostrap.css
            var resourceName = httpRequestPath.Substring(indexOfStartOfNameOfResource);

            var resourcePath = RootDirectoryRelativePath +
                "Resources" +
                $"/{requestPathExtension.Substring(1)}/" +
                resourceName;

            if (!File.Exists(resourcePath))
            {
                return new HttpResponse(HttpResponseStatusCode.NotFound);
            }

            var fileContent = File.ReadAllBytes(resourcePath);

            return new InlineResourceResult(fileContent, HttpResponseStatusCode.OK);
        }

        private bool IsResourseRequest(IHttpRequest httpRequest)
        {
            var requestPath = httpRequest.Path;

            if (requestPath.Contains('.'))
            {
                var requestPathExtension = requestPath.Substring(requestPath.LastIndexOf('.'));
                return GlobalConstants.ResourceExtensions.Contains(requestPathExtension);
            }

            return false;
        }

        private async Task<IHttpRequest> ReadRequest()
        {
            var result = new StringBuilder();

            ArraySegment<byte> data = new ArraySegment<byte>(new byte[1024]);

            while (true)
            {
                var numberOfBytesRead = await this.client.ReceiveAsync(data.Array, SocketFlags.None);

                if (numberOfBytesRead == 0)
                {
                    break;
                }

                string bytesAsString = Encoding.UTF8.GetString(data.Array, 0, numberOfBytesRead);

                result.Append(bytesAsString);

                if (numberOfBytesRead < 1023)
                {
                    break;
                }
            }

            if (result.Length == 0)
            {
                return null;
            }

            return new HttpRequest(result.ToString());
        }

        private string SetRequestSession(IHttpRequest httpRequest)
        {
            string sessionId = null;

            if (httpRequest.CookieCollection.ContainsCookie(HttpSessionStorage.SessionCookieKey))
            {
                var cookie = httpRequest.CookieCollection.GetCookie(HttpSessionStorage.SessionCookieKey);
                sessionId = cookie.Value;
                httpRequest.Session = HttpSessionStorage.GetSession(sessionId);
            }
            else
            {
                sessionId = Guid.NewGuid().ToString();
                httpRequest.Session = HttpSessionStorage.GetSession(sessionId);
            }
            return sessionId;
        }

        private void SetResponseSession(IHttpResponse httpResponse, string sessionId)
        {
            if (sessionId != null)
            {
                httpResponse
                    .AddCookie(new HttpCookie(HttpSessionStorage.SessionCookieKey, $"{sessionId}"));
            }
        }

        private void WriteResponseToConsole(byte[] byteSegments)
        {
            Console.WriteLine(new string('=', 10) + "RESPONSE" + new string('=', 10));
            Console.WriteLine(Encoding.UTF8.GetString(byteSegments, 0, byteSegments.Length));
        }

    }
}


text:
'use strict';

//Setting up route
angular.module('csvs').config(['$stateProvider',
	function($stateProvider) {
		// Csvs state routing
		$stateProvider.
		state('listCsvs', {
			url: '/csvs',
			templateUrl: 'modules/csvs/views/list-csvs.client.view.html'
		}).
		state('createCsv', {
			url: '/csvs/create',
			templateUrl: 'modules/csvs/views/create-csv.client.view.html'
		}).
		state('viewCsv', {
			url: '/csvs/:csvId',
			templateUrl: 'modules/csvs/views/view-csv.client.view.html'
		}).
		state('editCsv', {
			url: '/csvs/:csvId/edit',
			templateUrl: 'modules/csvs/views/edit-csv.client.view.html'
		});
	}
]);


text:
package org.zstack.test.virtualrouter;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.identity.SessionInventory;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmNicInventory;
import org.zstack.network.service.virtualrouter.VirtualRouterCommands.DhcpInfo;
import org.zstack.simulator.kvm.KVMSimulatorConfig;
import org.zstack.simulator.virtualrouter.VirtualRouterSimulatorConfig;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.concurrent.TimeUnit;

public class TestRemoveDhcpFromVirtualRouter2 {
    CLogger logger = Utils.getLogger(TestRemoveDhcpFromVirtualRouter2.class);
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;
    SessionInventory session;
    VirtualRouterSimulatorConfig vconfig;
    KVMSimulatorConfig kconfig;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/virtualRouter/removeDhcpFromVirtualRouter.xml", con);
        deployer.addSpringConfig("VirtualRouter.xml");
        deployer.addSpringConfig("VirtualRouterSimulator.xml");
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        vconfig = loader.getComponent(VirtualRouterSimulatorConfig.class);
        kconfig = loader.getComponent(KVMSimulatorConfig.class);
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
        session = api.loginAsAdmin();
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        VmInstanceInventory vm = deployer.vms.get("TestVm");
        api.destroyVmInstance(vm.getUuid());
        TimeUnit.SECONDS.sleep(1);

        VmNicInventory nic = vm.getVmNics().get(0);
        DhcpInfo info = vconfig.removedDhcp.get(0);
        Assert.assertEquals(nic.getMac(), info.getMac());
    }
}


text:
package org.jabref.model.openoffice;

import java.util.Optional;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CitationEntryTest {

    @Test
    void testCitationEntryInitialPageInfo() {
        CitationEntry citationEntry = new CitationEntry("RefMark", "Context", "Info");
        assertTrue(citationEntry.getPageInfo().isPresent());
        assertEquals("Info", citationEntry.getPageInfo().get());
        assertEquals("RefMark", citationEntry.getRefMarkName());
        assertEquals("Context", citationEntry.getContext());
    }

    @Test
    void testCitationEntryOptionalInitialPageInfo() {
        CitationEntry citationEntry = new CitationEntry("RefMark", "Context", Optional.of("Info"));

        assertEquals(Optional.of("Info"), citationEntry.getPageInfo());
        assertEquals("RefMark", citationEntry.getRefMarkName());
        assertEquals("Context", citationEntry.getContext());
    }

    @Test
    void testCitationEntryInitalPageInfoChanged() {
        CitationEntry citationEntry = new CitationEntry("RefMark", "Context", "Info");
        assertEquals(Optional.of("Info"), citationEntry.getPageInfo());
    }

    @Test
    void testCitationEntryNoInitialPageInfo() {
        CitationEntry citationEntry = new CitationEntry("RefMark", "Context");
        assertEquals(Optional.empty(), citationEntry.getPageInfo());
    }

    @Test
    void testCitationEntryEquals() {
        CitationEntry citationEntry1 = new CitationEntry("RefMark", "Context", "Info");
        CitationEntry citationEntry2 = new CitationEntry("RefMark2", "Context", "Info");
        CitationEntry citationEntry3 = new CitationEntry("RefMark", "Other Context", "Other Info");
        assertEquals(citationEntry1, citationEntry1);
        assertEquals(citationEntry1, citationEntry3);
        assertNotEquals(citationEntry1, citationEntry2);
        assertNotEquals(citationEntry1, "Random String");
    }

    @Test
    void testCitationEntryCompareTo() {
        CitationEntry citationEntry1 = new CitationEntry("RefMark", "Context", "Info");
        CitationEntry citationEntry2 = new CitationEntry("RefMark2", "Context", "Info");
        CitationEntry citationEntry3 = new CitationEntry("RefMark", "Other Context", "Other Info");
        assertEquals(0, citationEntry1.compareTo(citationEntry3));
        assertEquals(-1, citationEntry1.compareTo(citationEntry2));
        assertEquals(1, citationEntry2.compareTo(citationEntry1));
    }
}


text:
START_ATF_NAMESPACE
    struct _QUOTA_LIMITS
    {
        unsigned __int64 PagedPoolLimit;
        unsigned __int64 NonPagedPoolLimit;
        unsigned __int64 MinimumWorkingSetSize;
        unsigned __int64 MaximumWorkingSetSize;
        unsigned __int64 PagefileLimit;
        _LARGE_INTEGER TimeLimit;
    };
END_ATF_NAMESPACE


text:
import sys
import argparse
import pathlib
import logging
import subprocess

def main():
    parser = argparse.ArgumentParser("Check/rebuild extractor docker image")
    parser.add_argument('--force-rebuild', action='store_true')
    args = parser.parse_args()

    logging.basicConfig(format='%(levelname)s:%(asctime)s:%(message)s', level=logging.DEBUG)
    check_rebuild_docker_image(args.force_rebuild)

def check_rebuild_docker_image(force_rebuild: bool):
    logging.info("[+] Check if docker image is up-to-date")
    extractor_revision = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], cwd=pathlib.Path(__file__).absolute().parents[0]).strip().decode()
    image_name = "extractor_image:" + extractor_revision

    # Check if some extractor_image exists (all versions), if not build
    extractor_image_list = subprocess.check_output(["docker", "images", "-q", "extractor_image"], stderr=subprocess.DEVNULL).splitlines()

    if not extractor_image_list:
        logging.info("[+] Building docker image %s", image_name)
        subprocess.check_call(["docker", "build", ".", "-t", image_name])
    else:
        # If extractor_image already exists, check if we want to force rebuild
        if force_rebuild:
            # Delete all existing extractor_image images
            for image in extractor_image_list:
                subprocess.check_output(["docker", "rmi", image.decode()])
            # Build new image
            subprocess.check_call(["docker", "build", ".", "-t", image_name])
        else:
            # Stop in case we find multiple local images or an outdated image
            if len(extractor_image_list) != 1:
                logging.error("[!] Too many local extractor_images exist, please use ./docker_image.py --force-rebuild to cleanup and rebuild")
                sys.exit(1)
            elif subprocess.check_output(["docker", "images", "-q", image_name], stderr=subprocess.DEVNULL).strip() not in extractor_image_list:
                logging.error("[!] Your existing local image %s is outdated, please use ./docker_image.py --force-rebuild to rebuild", extractor_image_list[0].decode())
                sys.exit(1)

    return image_name

if __name__ == "__main__":
    main()


text:
package org.ebayopensource.turmeric.tools.codegen.builders;

import java.lang.reflect.Type;

import org.ebayopensource.turmeric.tools.codegen.exception.CodeGenFailedException;
import org.ebayopensource.turmeric.tools.codegen.util.CodeGenUtil;

import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JFieldVar;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;

/**
 * This class is responsible for generating Java Bean classes
 *
 * @author rmandapati
 */
public class JavaBeanGenerator extends BaseCodeGenerator  {

	private static final String FIELD_NAME_PREFIX = "m_";
	private static final String GET_METHOD_PREFIX = "get";
	private static final String SET_METHOD_PREIFX = "set";

	private static JavaBeanGenerator s_javaBeanGenerator  =
		new JavaBeanGenerator();

	private JavaBeanGenerator() {}

	public static JavaBeanGenerator getInstance() {
		return s_javaBeanGenerator;
	}

	public JDefinedClass generateBeanClass(
			String fullyQualifiedBeanName,
			Type[] fieldTypes,
			String[] fieldNames,
			String destLocation) throws CodeGenFailedException {

		JCodeModel jCodeModel = new JCodeModel();
		JDefinedClass beanClass =
			createNewClass(jCodeModel, fullyQualifiedBeanName);

		for (int i = 0; i < fieldTypes.length; i++) {
			Type fieldType = fieldTypes[i];
			addGetterAndSetter(jCodeModel, beanClass, fieldType, fieldNames[i]);
		}

		generateJavaFile(jCodeModel, destLocation);

		return beanClass;
	}

	private void addGetterAndSetter(
				JCodeModel jCodeModel,
				JDefinedClass beanClass,
				Type field,
				String fieldName) {

		JType fieldType = getJType(field, jCodeModel);
		String varName = FIELD_NAME_PREFIX+fieldName;
		JFieldVar fieldVar  =
				beanClass.field(JMod.PRIVATE, fieldType, varName);

		addGetter(beanClass, fieldType, fieldVar, fieldName);
		addSetter(beanClass, fieldType, fieldVar, fieldName);
	}

	private void addGetter(
			JDefinedClass beanClass,
			JType fieldType,
			JFieldVar fieldVar,
			String fieldName) {

		JMethod jGetMethod =
			beanClass.method(JMod.PUBLIC, fieldType, getterName(fieldName));
		jGetMethod.body()._return(fieldVar);
	}

	private void addSetter(
			JDefinedClass beanClass,
			JType fieldType,
			JFieldVar fieldVar,
			String fieldName) {

		JMethod jSetMethod =
			beanClass.method(JMod.PUBLIC, Void.TYPE, setterName(fieldName));
		JVar methodParamVar = jSetMethod.param(fieldType, fieldName);
		JBlock setMethodBody = jSetMethod.body();

		setMethodBody.assign(fieldVar, methodParamVar);
	}

	private String getterName(String methodName) {
		String getMethodName = GET_METHOD_PREFIX + CodeGenUtil.makeFirstLetterUpper(methodName);
		return getMethodName;
	}

	private String setterName(String methodName) {
		String setMethodName = SET_METHOD_PREIFX + CodeGenUtil.makeFirstLetterUpper(methodName);
		return setMethodName;
	}

}


text: Нийтийн домейны лиценз


text:
ActiveRecord::Schema.define(:version => 20130525163434) do

  create_table "subscribem_accounts", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

end


text:
port-forwarder-keepalive
========================


text:
using System;
using System.Linq;
using System.Threading.Tasks;

using LinqToDB;
using LinqToDB.Data;
using LinqToDB.Mapping;

using NUnit.Framework;

namespace Tests.xUpdate
{
	[TestFixture]
	[Order(10000)]
	public class CreateTableTests : TestBase
	{
		class TestTable
		{
			public int       ID;
			public string?   Field1;
			public string?   Field2;
			public DateTime? CreatedOn;
		}

		[Test]
		public void CreateTable1([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				db.MappingSchema.GetFluentMappingBuilder()
					.Entity<TestTable>()
						.Property(t => t.ID)
							.IsIdentity()
							.IsPrimaryKey()
						.Property(t => t.Field1)
							.HasLength(50);

				db.DropTable<TestTable>(throwExceptionIfNotExists:false);

				var table = db.CreateTable<TestTable>();
				var list = table.ToList();

				db.DropTable<TestTable>();
			}
		}

		[Test]
		public async Task CreateTable1Async([DataSources] string context)
		{
			using (var db = GetDataContext(context))
			{
				db.MappingSchema.GetFluentMappingBuilder()
					.Entity<TestTable>()
						.Property(t => t.ID)
							.IsIdentity()
							.IsPrimaryKey()
						.Property(t => t.Field1)
							.HasLength(50);

				await db.DropTableAsync<TestTable>(throwExceptionIfNotExists:false);

				var table = await db.CreateTableAsync<TestTable>();
				var list  = await table.ToListAsync();

				await db.DropTableAsync<TestTable>();
			}
		}

		[Test]
		public void CreateLocalTempTable1([IncludeDataSources(TestProvName.AllSqlServer2008Plus/*, ProviderName.DB2*/)] string context)
		{
			using (var db = GetDataContext(context))
			{
				db.MappingSchema.GetFluentMappingBuilder()
					.Entity<TestTable>()
						.Property(t => t.Field1)
							.HasLength(50);

				const string tableName = "TestTable";

				try
				{
					switch (context)
					{
						case string when context.IsAnyOf(TestProvName.AllSqlServer2008Plus) : db.DropTable<TestTable>("#" + tableName); break;
						default                                                             : db.DropTable<TestTable>(tableName);       break;
					}
				}
				catch
				{
				}

				ITable<TestTable> table;

				switch (context)
				{
					case string when context.IsAnyOf(TestProvName.AllSqlServer2008Plus):
						table = db.CreateTable<TestTable>("#" + tableName);
						break;
					case ProviderName.DB2                                 :
						table = db.CreateTable<TestTable>(statementHeader :"DECLARE GLOBAL TEMPORARY TABLE SESSION.{0}");
						break;
					default                                               :
						throw new InvalidOperationException();
				}

				var list = table.ToList();

				table.Drop();
			}
		}

		[ActiveIssue("https://github.com/Octonica/ClickHouseClient/issues/58", Configuration = ProviderName.ClickHouseOctonica)]
		[Test]
		public async Task CreateLocalTempTable1Async([IncludeDataSources(
			TestProvName.AllSQLite,
			TestProvName.AllClickHouse,
			TestProvName.AllSqlServer2008Plus /*, ProviderName.DB2*/)]
			string context)
		{
			using (var db = GetDataContext(context))
			{
				db.MappingSchema.GetFluentMappingBuilder()
					.Entity<TestTable>()
						.Property(t => t.Field1)
							.HasLength(50);

				const string tableName = "TestTable";

				try
				{
					switch (context)
					{
						case string when context.IsAnyOf(TestProvName.AllSqlServer2008Plus): await db.DropTableAsync<TestTable>("#" + tableName); break;
						default                                                            : await db.DropTableAsync<TestTable>(tableName);       break;
					}
				}
				catch
				{
				}

				ITable<TestTable> table;

				switch (context)
				{
					case string when context.IsAnyOf(TestProvName.AllSqlServer2008Plus):
						table = await db.CreateTableAsync<TestTable>("#" + tableName);
						break;
					case ProviderName.DB2                                           :
						table = await db.CreateTableAsync<TestTable>(statementHeader:"DECLARE GLOBAL TEMPORARY TABLE SESSION.{0}");
						break;
					default                                                         :
						table = await db.CreateTableAsync<TestTable>(tableName);
						break;
				}

				var list = await table.ToListAsync();

				await table.DropAsync();
			}
		}

		enum FieldType1
		{
			[MapValue(1)] Value1,
			[MapValue(2)] Value2,
		}

		enum FieldType2
		{
			[MapValue("A")]  Value1,
			[MapValue("AA")] Value2,
		}

		enum FieldType3 : short
		{
			Value1,
			Value2,
		}

		class TestEnumTable
		{
			public FieldType1 Field1;
			[Column(DataType=DataType.Int32)]
			public FieldType1? Field11;
			public FieldType2? Field2;
			[Column(DataType=DataType.VarChar, Configuration = ProviderName.ClickHouse)]
			[Column(DataType=DataType.Char, Length=2)]
			public FieldType2 Field21;
			public FieldType3 Field3;
		}

		[ActiveIssue("https://github.com/Octonica/ClickHouseClient/issues/58", Configuration = ProviderName.ClickHouseOctonica)]
		[Test]
		public void CreateTableWithEnum([IncludeDataSources(TestProvName.AllSqlServer2012, TestProvName.AllClickHouse)] string context)
		{
			using (var db = GetDataContext(context))
			{
				try
				{
					db.DropTable<TestEnumTable>();
				}
				catch (Exception)
				{
				}

				var table = db.CreateTable<TestEnumTable>();

				table.Insert(() => new TestEnumTable
				{
					Field1  = FieldType1.Value1,
					Field11 = FieldType1.Value1,
					Field2  = FieldType2.Value1,
					Field21 = FieldType2.Value1,
					Field3  = FieldType3.Value1,
				});

				var list = table.ToList();

				db.DropTable<TestEnumTable>();
			}
		}

		public enum Jjj
		{
			aa,
			bb,
		}
		public class base_aa
		{
			public Jjj dd { get; set; }
		}
		public class Aa : base_aa
		{
			public int     bb { get; set; }
			public string? cc { get; set; }
		}

		public class Qq
		{
			public int     bb { get; set; }
			public string? cc { get; set; }
		}

		[Test]
		public void TestIssue160([DataSources] string context)
		{
			using (var conn = GetDataContext(context))
			{
				conn.MappingSchema.GetFluentMappingBuilder()
					.Entity<Aa>()
						.HasTableName("aa")
						.Property(t => t.bb).IsPrimaryKey()
						.Property(t => t.cc)
						.Property(t => t.dd).IsNotColumn()

					.Entity<Qq>()
						.HasTableName("aa")
						.Property(t => t.bb).IsPrimaryKey()
						.Property(t => t.cc)
					;

				try
				{
					conn.CreateTable<Qq>();
				}
				catch
				{
					conn.DropTable<Qq>();
					conn.CreateTable<Qq>();
				}

				conn.Insert(new Aa
				{
					bb = 99,
					cc = "hallo",
					dd = Jjj.aa
				});

				var qq = conn.GetTable<Aa>().ToList().First();

				Assert.That(qq.bb, Is.EqualTo(99));
				Assert.That(qq.cc, Is.EqualTo("hallo"));

				conn.DropTable<Qq>();
			}
		}

		[Test]
		public void CreateTable2([IncludeDataSources(TestProvName.AllSqlServer2012)] string context)
		{
			using (var db = GetDataContext(context))
			{
				var table = db.CreateTable<TestEnumTable>("#TestTable");
				table.BulkCopy(new BulkCopyOptions { BulkCopyType = BulkCopyType.ProviderSpecific },
					new[]
				{
					new TestEnumTable
					{
						Field1  = FieldType1.Value1,
						Field11 = FieldType1.Value1,
						Field2  = FieldType2.Value1,
						Field21 = FieldType2.Value1,
						Field3  = FieldType3.Value1,
					}
				});
				table.DropTable();
			}
		}

		class TestCreateFormat
		{
			[Column(CreateFormat = "{0}{1}{2}{3}/* test */"), NotNull]
			public int Field1;
			[Column]
			public int Field2;
		}

		[Test]
		public void CreateFormatTest([IncludeDataSources(TestProvName.AllSqlServer2012)] string context)
		{
			using (var db = GetDataContext(context))
			{
				var table = db.CreateTable<TestCreateFormat>("#TestTable");
				table.DropTable();
			}
		}
	}
}


text:
describe('segmentEffortController', function () {
    var $scope, stravaSegmentResource, segmentDeferred;

    beforeEach(module('sputnikControllers'));

    beforeEach(inject(function ($rootScope, $q, $controller, _stravaSegmentResource_) {
        $scope = $rootScope.$new();
        stravaSegmentResource = _stravaSegmentResource_;

        segmentDeferred = $q.defer();
        $scope.segmentEffort = {segmentId: 17};

        spyOn(stravaSegmentResource, "get").and.returnValue({$promise: segmentDeferred.promise});

        $controller('segmentEffortController', {
            $scope: $scope,
            stravaSegmentResource: stravaSegmentResource
        });
    }));

    it('sets imageSource', function () {
        segmentDeferred.resolve("segment");
        $scope.$apply();

        expect(stravaSegmentResource.get).toHaveBeenCalledWith({segmentId: 17});
        expect($scope.segment).toEqual("segment");
    });
});


text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *  \brief Common definitions and declarations for the library USB Printer Class driver.
 *
 *  Common definitions and declarations for the library USB Printer Class driver.
 *
 *  \note This file should not be included directly. It is automatically included as needed by the USB module driver
 *        dispatch header located in LUFA/Drivers/USB.h.
 */

/** \ingroup Group_USBClassPrinter
 *  \defgroup Group_USBClassPrinterCommon  Common Class Definitions
 *
 *  \section Sec_ModDescription Module Description
 *  Constants, Types and Enum definitions that are common to both Device and Host modes for the USB
 *  Printer Class.
 *
 *  @{
 */

#ifndef _PRINTER_CLASS_COMMON_H_
#define _PRINTER_CLASS_COMMON_H_

	/* Includes: */
		#include "../../Core/StdDescriptors.h"

	/* Enable C linkage for C++ Compilers: */
		#if defined(__cplusplus)
			extern "C" {
		#endif

	/* Preprocessor Checks: */
		#if !defined(__INCLUDE_FROM_PRINTER_DRIVER)
			#error Do not include this file directly. Include LUFA/Drivers/USB.h instead.
		#endif

	/* Macros: */
		/** \name Virtual Printer Status Line Masks */
		//@{
		/** Port status mask for a printer device, indicating that an error has *not* occurred. */
		#define PRNT_PORTSTATUS_NOTERROR    (1 << 3)

		/** Port status mask for a printer device, indicating that the device is currently selected. */
		#define PRNT_PORTSTATUS_SELECT      (1 << 4)

		/** Port status mask for a printer device, indicating that the device is currently out of paper. */
		#define PRNT_PORTSTATUS_PAPEREMPTY  (1 << 5)
		//@}

	/* Enums: */
		/** Enum for possible Class, Subclass and Protocol values of device and interface descriptors relating to the Printer
		 *  device class.
		 */
		enum PRNT_Descriptor_ClassSubclassProtocol_t
		{
			PRNT_CSCP_PrinterClass          = 0x07, /**< Descriptor Class value indicating that the device or interface
			                                         *   belongs to the Printer class.
			                                         */
			PRNT_CSCP_PrinterSubclass       = 0x01, /**< Descriptor Subclass value indicating that the device or interface
			                                         *   belongs to the Printer subclass.
			                                         */
			PRNT_CSCP_BidirectionalProtocol = 0x02, /**< Descriptor Protocol value indicating that the device or interface
			                                         *   belongs to the Bidirectional protocol of the Printer class.
			                                         */
		};

		/** Enum for the Printer class specific control requests that can be issued by the USB bus host. */
		enum PRNT_ClassRequests_t
		{
			PRNT_REQ_GetDeviceID            = 0x00, /**< Printer class-specific request to retrieve the Unicode ID
			                                         *   string of the device, containing the device's name, manufacturer
			                                         *   and supported printer languages.
			                                         */
			PRNT_REQ_GetPortStatus          = 0x01, /**< Printer class-specific request to get the current status of the
			                                         *   virtual printer port, for device selection and ready states.
			                                         */
			PRNT_REQ_SoftReset              = 0x02, /**< Printer class-specific request to reset the device, ready for new
			                                         *   printer commands.
			                                         */
		};

	/* Disable C linkage for C++ Compilers: */
		#if defined(__cplusplus)
			}
		#endif

#endif

/** @} */


text:
High-Integrity Internet-Scale Device Authentication

For more information, please see the detailed walkthrough at http://www.jwsecure.com/2015/04/13/high-integrity-internet-scale-device-authentication/.


text:
namespace blink {

void NGMathMLPainter::PaintBar(const PaintInfo& info, const IntRect& bar) {
  if (bar.IsEmpty())
    return;

  GraphicsContextStateSaver state_saver(info.context);
  info.context.SetStrokeThickness(bar.Height());
  info.context.SetStrokeStyle(kSolidStroke);
  info.context.SetStrokeColor(
      box_fragment_.Style().VisitedDependentColor(GetCSSPropertyColor()));
  IntPoint line_end_point = {bar.Width(), 0};
  info.context.DrawLine(bar.Location(), bar.Location() + line_end_point);
}

void NGMathMLPainter::PaintFractionBar(const PaintInfo& info,
                                       PhysicalOffset paint_offset) {
  const DisplayItemClient& display_item_client =
      *box_fragment_.GetLayoutObject();
  if (DrawingRecorder::UseCachedDrawingIfPossible(
          info.context, display_item_client, info.phase))
    return;

  DrawingRecorder recorder(info.context, display_item_client, info.phase);

  DCHECK(box_fragment_.Style().IsHorizontalWritingMode());
  const ComputedStyle& style = box_fragment_.Style();
  LayoutUnit line_thickness = FractionLineThickness(style);
  if (!line_thickness)
    return;
  LayoutUnit axis_height = MathAxisHeight(style);
  if (auto baseline = box_fragment_.Baseline()) {
    auto borders = box_fragment_.Borders();
    auto padding = box_fragment_.Padding();
    PhysicalRect bar_rect = {
        borders.left + padding.left, *baseline - axis_height,
        box_fragment_.Size().width - borders.HorizontalSum() -
            padding.HorizontalSum(),
        line_thickness};
    bar_rect.Move(paint_offset);
    PaintBar(info, PixelSnappedIntRect(bar_rect));
  }
}

}  // namespace blink