text:
package com.google.zxing.client.android.camera;

import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.client.android.camera.open.OpenCameraInterface;

import android.content.Context;
import android.graphics.Point;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;

import java.io.IOException;

/**
 * This object wraps the Camera service object and expects to be the only one
 * talking to it. The
 * implementation encapsulates the steps needed to take preview-sized images,
 * which are used for
 * both preview and decoding.
 *
 * @author dswitkin@google.com (Daniel Switkin)
 */
public final class CameraManager {

    private static final String TAG = CameraManager.class.getSimpleName();

    private static final int MIN_FRAME_WIDTH = 240;

    private static final int MIN_FRAME_HEIGHT = 240;

    private static final int MAX_FRAME_WIDTH = 1200; // = 5/8 * 1920

    private static final int MAX_FRAME_HEIGHT = 675; // = 5/8 * 1080

    private final Context context;

    private final CameraConfigurationManager configManager;

    /**
     * Preview frames are delivered here, which we pass on to the registered
     * handler. Make sure to
     * clear the handler so it will only receive one message.
     */
    private final PreviewCallback previewCallback;

    private Camera camera;

    private AutoFocusManager autoFocusManager;

    private Rect framingRect;

    private Rect framingRectInPreview;

    private boolean initialized;

    private boolean previewing;

    private int requestedFramingRectWidth;

    private int requestedFramingRectHeight;

    public CameraManager(Context context) {
        this.context = context;
        this.configManager = new CameraConfigurationManager(context);
        previewCallback = new PreviewCallback(configManager);
    }

    private static int findDesiredDimensionInRange(int resolution, int hardMin,
            int hardMax) {
        int dim = 5 * resolution / 8; // Target 5/8 of each dimension
        if (dim < hardMin) {
            return hardMin;
        }
        if (dim > hardMax) {
            return hardMax;
        }
        return dim;
    }

    /**
     * Opens the camera driver and initializes the hardware parameters.
     *
     * @param holder The surface object which the camera will draw preview frames
     *               into.
     * @throws java.io.IOException Indicates the camera driver failed to open.
     */
    public synchronized void openDriver(SurfaceHolder holder)
            throws IOException, InterruptedException {
        Camera theCamera = camera;
        if (theCamera == null) {
            theCamera = OpenCameraInterface.open();
            if (theCamera == null) {
                throw new IOException();
            }
            camera = theCamera;
        }
        theCamera.setPreviewDisplay(holder);

        if (!initialized) {
            initialized = true;
            configManager.initFromCameraParameters(theCamera);
            if (requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0) {
                setManualFramingRect(requestedFramingRectWidth,
                        requestedFramingRectHeight);
                requestedFramingRectWidth = 0;
                requestedFramingRectHeight = 0;
            }
        }

        Camera.Parameters parameters = theCamera.getParameters();
        String parametersFlattened = parameters == null ? null : parameters
                .flatten(); // Save these, temporarily
        try {
            configManager.setDesiredCameraParameters(theCamera, false);
        } catch (RuntimeException re) {
            // Driver failed
            Log.w(TAG,
                    "Camera rejected parameters. Setting only minimal safe-mode parameters");
            Log.i(TAG, "Resetting to saved camera params: "
                    + parametersFlattened);
            // Reset:
            if (parametersFlattened != null) {
                parameters = theCamera.getParameters();
                parameters.unflatten(parametersFlattened);
                try {
                    theCamera.setParameters(parameters);
                    configManager.setDesiredCameraParameters(theCamera, true);
                } catch (RuntimeException re2) {
                    // Well, darn. Give up
                    Log.w(TAG,
                            "Camera rejected even safe-mode parameters! No configuration");
                }
            }
        }

    }

    public synchronized boolean isOpen() {
        return camera != null;
    }

    /**
     * Closes the camera driver if still in use.
     */
    public synchronized void closeDriver() {
        if (camera != null) {
            camera.release();
            camera = null;
            // Make sure to clear these each time we close the camera, so that any scanning rect
            // requested by intent is forgotten.
            framingRect = null;
            framingRectInPreview = null;
        }
    }

    /**
     * Asks the camera hardware to begin drawing preview frames to the screen.
     */
    public synchronized void startPreview() {
        Camera theCamera = camera;
        if (theCamera != null && !previewing) {

            theCamera.startPreview();
            previewing = true;
            autoFocusManager = new AutoFocusManager(context, camera);
        }
    }

    /**
     * Tells the camera to stop drawing preview frames.
     */
    public synchronized void stopPreview() {
        if (autoFocusManager != null) {
            autoFocusManager.stop();
            autoFocusManager = null;
        }
        if (camera != null && previewing) {
            camera.stopPreview();
            previewCallback.setHandler(null, 0);
            previewing = false;
        }
    }

    public synchronized void setTorch(boolean newSetting) {
        if (newSetting != configManager.getTorchState(camera)) {
            if (camera != null) {
                if (autoFocusManager != null) {
                    autoFocusManager.stop();
                }
                configManager.setTorch(camera, newSetting);
                if (autoFocusManager != null) {
                    autoFocusManager.start();
                }
            }
        }
    }

    /**
     * A single preview frame will be returned to the handler supplied. The data
     * will arrive as byte[] in the message.obj field,
     * with width and height encoded as message.arg1 and message.arg2, respectively.
     *
     * @param handler The handler to send the message to.
     * @param message The what field of the message to be sent.
     */
    public synchronized void requestPreviewFrame(Handler handler, int message) {
        Camera theCamera = camera;
        if (theCamera != null && previewing) {
            previewCallback.setHandler(handler, message);
            theCamera.setOneShotPreviewCallback(previewCallback);
        }
    }

    /**
     * Calculates the framing rect which the UI should draw to show the user
     * where to place the
     * barcode. This target helps with alignment as well as forces the user to
     * hold the device
     * far enough away to ensure the image will be in focus.
     *
     * @return The rectangle to draw on screen in window coordinates.
     */
    public synchronized Rect getFramingRect() {
        if (framingRect == null) {
            if (camera == null) {
                return null;
            }
            Point screenResolution = configManager.getScreenResolution();
            if (screenResolution == null) {
                // Called early, before init even finished
                return null;
            }

            int width = findDesiredDimensionInRange(screenResolution.x,
                    MIN_FRAME_WIDTH, MAX_FRAME_WIDTH);
            int height = findDesiredDimensionInRange(screenResolution.y,
                    MIN_FRAME_HEIGHT, MAX_FRAME_HEIGHT);

            int leftOffset = (screenResolution.x - width) / 2;
            int topOffset = (screenResolution.y - height) / 2;
            framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
                    topOffset + height);
            Log.d(TAG, "Calculated framing rect: " + framingRect);
        }
        return framingRect;
    }

    /**
     * Like {@link #getFramingRect} but coordinates are in terms of the preview
     * frame,
     * not UI / screen.
     */
    public synchronized Rect getFramingRectInPreview() {
        if (framingRectInPreview == null) {
            Rect framingRect = getFramingRect();
            if (framingRect == null) {
                return null;
            }
            Rect rect = new Rect(framingRect);
            Point cameraResolution = configManager.getCameraResolution();
            Point screenResolution = configManager.getScreenResolution();
            if (cameraResolution == null || screenResolution == null) {
                // Called early, before init even finished
                return null;
            }
            rect.left = rect.left * cameraResolution.x / screenResolution.x;
            rect.right = rect.right * cameraResolution.x / screenResolution.x;
            rect.top = rect.top * cameraResolution.y / screenResolution.y;
            rect.bottom = rect.bottom * cameraResolution.y / screenResolution.y;
            framingRectInPreview = rect;
        }
        return framingRectInPreview;
    }

    /**
     * Allows third party apps to specify the scanning rectangle dimensions,
     * rather than determine
     * them automatically based on screen resolution.
     *
     * @param width  The width in pixels to scan.
     * @param height The height in pixels to scan.
     */
    public synchronized void setManualFramingRect(int width, int height) {
        if (initialized) {
            Point screenResolution = configManager.getScreenResolution();
            if (width > screenResolution.x) {
                width = screenResolution.x;
            }
            if (height > screenResolution.y) {
                height = screenResolution.y;
            }
            int leftOffset = (screenResolution.x - width) / 2;
            int topOffset = (screenResolution.y - height) / 2;
            framingRect = new Rect(leftOffset, topOffset, leftOffset + width,
                    topOffset + height);
            Log.d(TAG, "Calculated manual framing rect: " + framingRect);
            framingRectInPreview = null;
        } else {
            requestedFramingRectWidth = width;
            requestedFramingRectHeight = height;
        }
    }

    /**
     * A factory method to build the appropriate LuminanceSource object based on
     * the format
     * of the preview buffers, as described by Camera.Parameters.
     *
     * @param data   A preview frame.
     * @param width  The width of the image.
     * @param height The height of the image.
     * @return A PlanarYUVLuminanceSource instance.
     */
    public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data,
            int width, int height) {
        Rect rect = getFramingRectInPreview();
        if (rect == null) {
            return null;
        }
        // Go ahead and assume it's YUV rather than die.
        return new PlanarYUVLuminanceSource(data, width, height, rect.left,
                rect.top, rect.width(), rect.height(), false);
    }

}


text:
extern "C" {
#endif

BOOL Mhook_SetHook(PVOID *ppSystemFunction, PVOID pHookFunction);
BOOL Mhook_Unhook(PVOID *ppHookedFunction);

#ifdef __cplusplus
}
#endif

#define MHOOKS_MAX_SUPPORTED_HOOKS	512

redpajama_set_name: RedPajamaGithub


text:
from django.contrib import admin
from rest_api.models import Product, Enterprise, Reliability

admin.site.register(Product)
admin.site.register(Enterprise)
admin.site.register(Reliability)


text:
package org.darkphoenixs.pool.socket;

import org.darkphoenixs.pool.ConnectionPool;
import org.darkphoenixs.pool.PoolBase;
import org.darkphoenixs.pool.PoolConfig;

import java.net.Socket;
import java.util.Properties;

/**
 *
SocketConnectionPool

 *
Socket连接池

 *
 * @author Victor.Zxy
 * @see PoolBase
 * @see ConnectionPool
 * @since 1.2.1
 */
public class SocketConnectionPool extends PoolBase<Socket> implements ConnectionPool<Socket> {

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

    /**
     * 默认构造方法
     */
    public SocketConnectionPool() {

        this(new PoolConfig(), SocketConfig.DEFAULT_HOST, SocketConfig.DEFAULT_PORT);
    }

    /**
     * @param properties 参数配置
     */
    public SocketConnectionPool(final Properties properties) {

        this(new PoolConfig(), properties);
    }

    /**
     * @param poolConfig 池配置
     * @param properties 参数配置
     */
    public SocketConnectionPool(final PoolConfig poolConfig, final Properties properties) {

        super(poolConfig, new SocketConnectionFactory(properties));
    }

    /**
     * @param poolConfig 池配置
     * @param host       地址
     * @param port       端口
     */
    public SocketConnectionPool(final PoolConfig poolConfig, final String host, final int port) {

        this(poolConfig, host, port, SocketConfig.DEFAULT_BUFFERSIZE, SocketConfig.DEFAULT_TIMEOUT);
    }

    /**
     * @param poolConfig 池配置
     * @param host       地址
     * @param port       端口
     * @param bufferSize 缓存大小
     * @param timeout    超时时间
     */
    public SocketConnectionPool(final PoolConfig poolConfig, final String host, final int port, final int bufferSize, final int timeout) {

        this(poolConfig, host, port, bufferSize, timeout, SocketConfig.DEFAULT_LINGER);
    }

    /**
     * @param poolConfig 池配置
     * @param host       地址
     * @param port       端口
     * @param bufferSize 缓存大小
     * @param timeout    超时时间
     * @param linger     逗留时间
     */
    public SocketConnectionPool(final PoolConfig poolConfig, final String host, final int port, final int bufferSize, final int timeout, final int linger) {

        this(poolConfig, host, port, bufferSize, timeout, linger, SocketConfig.DEFAULT_KEEPALIVE, SocketConfig.DEFAULT_TCPNODELAY);
    }

    /**
     * @param poolConfig 池配置
     * @param host       地址
     * @param port       端口
     * @param bufferSize 缓存大小
     * @param timeout    超时时间
     * @param linger     逗留时间
     * @param keepAlive  保持活动
     * @param tcpNoDelay 不延迟
     */
    public SocketConnectionPool(final PoolConfig poolConfig, final String host, final int port, final int bufferSize, final int timeout, final int linger, final boolean keepAlive, final boolean tcpNoDelay) {

        this(poolConfig, host, port, bufferSize, timeout, linger, keepAlive, tcpNoDelay, SocketConfig.DEFAULT_PERFORMANCE);
    }

    /**
     * @param poolConfig  池配置
     * @param host        地址
     * @param port        端口
     * @param bufferSize  缓存大小
     * @param timeout     超时时间
     * @param linger      逗留时间
     * @param keepAlive   保持活动
     * @param tcpNoDelay  不延迟
     * @param performance 性能属性
     */
    public SocketConnectionPool(final PoolConfig poolConfig, final String host, final int port, final int bufferSize, final int timeout, final int linger, final boolean keepAlive, final boolean tcpNoDelay, final String[] performance) {

        super(poolConfig, new SocketConnectionFactory(host, port, bufferSize, bufferSize, timeout, timeout, linger, keepAlive, tcpNoDelay, performance));
    }

    @Override
    public Socket getConnection() {

        return super.getResource();
    }

    @Override
    public void returnConnection(Socket conn) {

        super.returnResource(conn);
    }

    @Override
    public void invalidateConnection(Socket conn) {

        super.invalidateResource(conn);
    }

}


text:
<?php

/**
 * User client service class
 *
 * @category   Firal
 * @package    Default_Services
 * @copyright  Copyright (c) 2009-2010 Firal (http://firal.org/)
 * @license    http://firal.org/licenses/new-bsd    New BSD License
 */
class Default_Service_UserClient implements Default_Service_UserInterface
{

    /**
     * RPC client
     *
     * @var Firal_Service_Client_ClientInterface
     */
    protected $_client;

    /**
     * Login form instance
     *
     * @var Default_Form_UserLogin
     */
    protected $_loginForm;

    /**
     * Register form instance
     *
     * @var Default_Form_UserRegister
     */
    protected $_registerForm;

    /**
     * Constructor
     *
     * @param Firal_Service_Client_ClientInterface $client
     *
     * @return void
     */
    public function __construct(Firal_Service_Client_ClientInterface $client)
    {
        $this->_client = $client;
    }

    /**
     * Log the user in
     *
     * @param array $data
     *
     * @return bool
     */
    public function login(array $data)
    {
        $form = $this->getLoginForm();

        if (!$form->isValid($data)) {
            return false;
        }

        return $this->_client->login($form->getValues());
    }

    /**
     * Register a user
     *
     * @param array $data
     *
     * @return bool
     */
    public function register(array $data)
    {
        $form = $this->getRegisterForm();

        if (!$form->isValid($data)) {
            return false;
        }

        return $this->_client->register($form->getValues());
    }

    /**
     * Log the user out
     *
     * @return void
     */
    public function logout()
    {
        Zend_Auth::getInstance()->clearIdentity();
    }

    /**
     * Get the login form
     *
     * @return Default_Form_Login
     */
    public function getLoginForm()
    {
        if (null === $this->_loginForm) {
            $this->_loginForm = new Default_Form_UserLogin();
        }

        return $this->_loginForm;
    }

    /**
     * Get the register form
     *
     * @return Default_Form_UserRegister
     */
    public function getRegisterForm()
    {
        if (null === $this->_registerForm) {
            $this->_registerForm = new Default_Form_UserRegister();
        }

        return $this->_registerForm;
    }
}


text:
This page is deprecated. It's contents have been moved to [Mozilla Developer Network](https://developer.mozilla.org/en-US/)

# unicode-bidi

Support unprefixed property. [MDN documentation is already available](https://developer.mozilla.org/en-US/docs/Web/CSS/unicode-bidi) for this feature.


text:
const subNotes = require('./sub-notes')

const argv = require('./argv')

const json = require('./json')

// console.log(`Yor age is ${subNotes.age}`)

/**
 * При обычном присваивании переменная передается по ссылке
 * Демонстрация внизу:
 */
var _notes = subNotes.notes

console.log('_notes: ',_notes)

subNotes.addNote({
    id: 1,
    title: 'Note 1',
    flag: false
})

console.log('_notes after addNote: ',_notes)

// _notes = null

// console.log( 'subNotes.notes after addNote local _notes = null: ', subNotes.notes) // [ { id: 1, title: 'Note 1', flag: false } ]

subNotes.notes = null

console.log('subNotes.notes: ', subNotes.notes) // null
console.log('_notes: ', _notes) // [ { id: 1, title: 'Note 1', flag: false } ]

/**
 * Но при использовании паттерна "модуль" все инкапсулировано в combiner:
 */
// К массиву notes доступа нет
// console.log(subNotes.combiner.notes) // undefined

console.log(subNotes.combiner.getNotes())

console.log(subNotes.combiner.addNote({
    id: 1,
    title: 'Note 1',
    flag: false
}))

var __Notes = subNotes.combiner.getNotes()

console.log(__Notes) // [ { id: 1, title: 'Note 1', flag: false } ]

subNotes.combiner.addNote({
    id: 2,
    title: 'Note 2',
    flag: false
})

console.log(__Notes) // [ { id: 1, title: 'Note 1', flag: false },{ id: 2, title: 'Note 2', flag: false } ]

__Notes = null

console.log( subNotes.combiner.getNotes() ) //  [ { id: 1, title: 'Note 1', flag: false },{ id: 2, title: 'Note 2', flag: false } ]
console.log( __Notes ) // null

/**
 * Вывод последнего аргумента, переданного в консоли
 * node node-samples/notes arg_1 arg_2 --key "some string" --another_key="asd"
 * // arg_2
 */
// console.log( argv.getLastArg() )

/**
 * Вывод аргумента по имени
 * node node-samples/notes arg_1 arg_2 --key "some string" --another_key="asd"
 * // some string
 */
// console.log( argv.getAtrByName('title') )

// Построить объект note из аргументов консоли
var getNote = function () {
    var note = {}
    try {
         note.title = argv.getAtrByName('title')
         note.description = argv.getAtrByName('desc')
    } catch (err){
    }

    return note
}

/**
 * Код управления заметками
 * Заметки создаются из командной строки
 * node node-samples/notes addNote --title=TITLE --desc="new description"
 * node node-samples/notes dropNote --title=TITLE --desc="new description"
 *
 * node node-samples/notes -h
 */

// todo доработать, чтобы брать команду и ключи из consoleArgs
const consoleArgs = argv.getHelp()

// console.log(consoleArgs['addNote'], "aaaa")
// console.log(consoleArgs['a'], "vvvvvv")

switch( argv.getFirstArg() ){
    case 'addNote':
        json.addNote( getNote() )
        break;

    case 'dropNote':
        json.removeNote( getNote() )
        break;
}


text:
<!DOCTYPE html>

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

one two three

[ONE TWO THREE]


text:
var canvasBg = document.getElementById("canvasBg"),
    ctxBg = canvasBg.getContext("2d"),
    canvasEntities = document.getElementById("canvasEntities"),
    ctxEntities = canvasEntities.getContext("2d"),
    canvasWidth = canvasBg.width,
    canvasHeight = canvasBg.height,
    player1 = new Player(),
    enemies = [],
    numEnemies = 5,
    obstacles = [],
    isPlaying = false,
    // AnimationFrame for various browsers
    requestAnimFrame =  window.requestAnimationFrame ||
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.oRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        function(callback) {
                            window.setTimeout(callback, 1000 / 60);
                        },
    // game sprites
    imgSprite = new Image();
imgSprite.src = "images/sprite.png";
imgSprite.addEventListener("load", init, false);

// initialize game
function init() {
    document.addEventListener("keydown", function(e) {checkKey(e, true);}, false);
    document.addEventListener("keyup", function(e) {checkKey(e, false);}, false);
    defineObstacles();
    initEnemies();
    begin();
}

// let's do this!
function begin() {
    ctxBg.drawImage(imgSprite, 0, 0, canvasWidth, canvasHeight, 0, 0, canvasWidth, canvasHeight);
    isPlaying = true;
    requestAnimFrame(loop);
}

// update game logic
function update() {
    clearCtx(ctxEntities);
    updateAllEnemies();
    player1.update();
}

// draw player and enemies
function draw() {
    drawAllEnemies();
    player1.draw();
}

// if our player is alive, keep playing!
function loop() {
    if (isPlaying) {
        update();
        draw();
        requestAnimFrame(loop);
    }
}

function clearCtx(ctx) {
    ctx.clearRect(0, 0, canvasWidth, canvasHeight);
}

// random function for random play
function randomRange (min, max) {
    return Math.floor(Math.random() * (max + 1 - min)) + min;
}

// Player object (constructor function).
// Player prototypes follow.
function Player() {
    this.srcX = 0;
    this.srcY = 600;
    this.width = 35;
    this.height = 54;
    this.drawX = 400;
    this.drawY = 300;
    this.centerX = this.drawX + (this.width / 2);
    this.centerY = this.drawY + (this.height / 2);
    this.speed = 2;
    this.isUpKey = false;
    this.isRightKey = false;
    this.isDownKey = false;
    this.isLeftKey = false;
    this.isSpacebar = false;
    this.isShooting = false;
    var numBullets = 10;
    this.bullets = [];
    this.currentBullet = 0;
    for (var i = 0; i < numBullets; i++) {
        this.bullets[this.bullets.length] = new Bullet();
    }
}

Player.prototype.update = function () {
    this.centerX = this.drawX + (this.width / 2);
    this.centerY = this.drawY + (this.height / 2);
    this.checkDirection();
    this.checkShooting();
    this.updateAllBullets();
};

// draw our hero
Player.prototype.draw = function () {
    this.drawAllBullets();
    ctxEntities.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height);
};

// Which way is Player facing?
// e.g. running north, facing north
Player.prototype.checkDirection = function () {
    var newDrawX = this.drawX,
        newDrawY = this.drawY,
        obstacleCollision = false;
    if (this.isUpKey) {
        newDrawY -= this.speed;
        this.srcX = 35; // Facing north
    } else if (this.isDownKey) {
        newDrawY += this.speed;
        this.srcX = 0; // Facing south
    } else if (this.isRightKey) {
        newDrawX += this.speed;
        this.srcX = 105; // Facing east
    } else if (this.isLeftKey) {
        newDrawX -= this.speed;
        this.srcX = 70; // Facing west
    }

    // did Player collide with an obstacle (tree or rock, etc)?
    obstacleCollision = this.checkObstacleCollide(newDrawX, newDrawY);

    // if our Player hasn't collided AND he's in bounds- set his new position
    if (!obstacleCollision && !outOfBounds(this, newDrawX, newDrawY)) {
        this.drawX = newDrawX;
        this.drawY = newDrawY;
    }
};

// Loop through obstacles array to check for Player collision
// return a true or false value
Player.prototype.checkObstacleCollide = function (newDrawX, newDrawY) {
    var obstacleCounter = 0,
        newCenterX = newDrawX + (this.width / 2),
        newCenterY = newDrawY + (this.height / 2);
    for (var i = 0; i < obstacles.length; i++) {
        if (obstacles[i].leftX < newCenterX && newCenterX < obstacles[i].rightX && obstacles[i].topY - 20 < newCenterY && newCenterY < obstacles[i].bottomY - 20) {
            obstacleCounter = 0;
        } else {
            obstacleCounter++;
        }
    }

    if (obstacleCounter === obstacles.length) {
        return false;
    } else {
        return true;
    }
};

// Is Player shooting?
// If user presses the spacebar, then yes he is!
// Pause between shots. It's a single-shooter. Chill, man.
Player.prototype.checkShooting = function () {
    if (this.isSpacebar && !this.isShooting) {
        this.isShooting = true;
        this.bullets[this.currentBullet].fire(this.centerX, this.centerY);
        this.currentBullet++;
        if (this.currentBullet >= this.bullets.length) {
            this.currentBullet = 0;
        }
    } else if (!this.isSpacebar) {
        this.isShooting = false;
    }
};

// Make sure Player has enough bullets to keep fighting.
// Update his arsenal.
Player.prototype.updateAllBullets = function () {
    for (var i = 0; i < this.bullets.length; i++) {
        if (this.bullets[i].isFlying) {
            this.bullets[i].update();
        }
    }
};

// If the bullet isFlying, draw it.
Player.prototype.drawAllBullets = function () {
    for (var i = 0; i < this.bullets.length; i++) {
        if (this.bullets[i].isFlying) {
            this.bullets[i].draw();
        }
    }
};

// Bullet object. (constructor function)
function Bullet() {
    this.radius = 2;
    this.width = this.radius * 2;
    this.height = this.radius * 2;
    this.drawX = 0;
    this.drawY = 0;
    this.isFlying = false;
    this.xVel = 0;
    this.yVel = 0;
    this.speed = 6;
}

// update the bullet's position as it darts across the board
// did it hit an enemy? obstacle? or fly out of bounds?
Bullet.prototype.update = function () {
    this.drawX += this.xVel;
    this.drawY += this.yVel;
    this.checkHitEnemy();
    this.checkHitObstacle();
    this.checkOutOfBounds();
};

// draw white bullet(s)
Bullet.prototype.draw = function () {
    ctxEntities.fillStyle = "white";
    ctxEntities.beginPath();
    ctxEntities.arc(this.drawX, this.drawY, this.radius, 0, Math.PI * 2, false);
    ctxEntities.closePath();
    ctxEntities.fill();
};

// play sound when bullet is fired.
// user input (arrow keys) determine Player direction.
Bullet.prototype.fire = function (startX, startY) {
    var soundEffect = new Audio("audio/shooting.wav");
    soundEffect.play();
    this.drawX = startX;
    this.drawY = startY;
    if (player1.srcX === 0) { // Facing south
        this.xVel = 0;
        this.yVel = this.speed;
    } else if (player1.srcX === 35) { // Facing north
        this.xVel = 0;
        this.yVel = -this.speed;
    } else if (player1.srcX === 70) { // Facing west
        this.xVel = -this.speed;
        this.yVel = 0;
    } else if (player1.srcX === 105) { // Facing east
        this.xVel = this.speed;
        this.yVel = 0;
    }
    this.isFlying = true;
};

Bullet.prototype.recycle = function () {
    this.isFlying = false;
};

// loop through enemies array to see if
// any of the enemies have been hit by a bullet
// if the enemy is already dead, another bullet hit doesn't count
Bullet.prototype.checkHitEnemy = function () {
    for (var i = 0; i < enemies.length; i++) {
        if (collision(this, enemies[i]) && !enemies[i].isDead) {
            this.recycle();
            enemies[i].die();
        }
    }
};

// loop through obstacles array to
// see if the bullet hit a lonely tree or rock
Bullet.prototype.checkHitObstacle = function () {
    for (var i = 0; i < obstacles.length; i++) {
        if (collision(this, obstacles[i])) {
            this.recycle();
        }
    }
};

// did a stray bullet leave our board?
Bullet.prototype.checkOutOfBounds = function () {
    if (outOfBounds(this, this.drawX, this.drawY)) {
        this.recycle();
    }
};

function Obstacle(x, y, w, h) {
    this.drawX = x;
    this.drawY = y;
    this.width = w;
    this.height = h;
    this.leftX = this.drawX;
    this.rightX = this.drawX + this.width;
    this.topY = this.drawY;
    this.bottomY = this.drawY + this.height;
}

function defineObstacles() {
    var treeWidth = 65,
        treeHeight = 90,
        rockDimensions = 30,
        bushHeight = 28;

    obstacles = [new Obstacle(78, 360, treeWidth, treeHeight),
        new Obstacle(390, 395, treeWidth, treeHeight),
        new Obstacle(415, 102, treeWidth, treeHeight),
        new Obstacle(619, 184,treeWidth, treeHeight),
        new Obstacle(97, 63, rockDimensions, rockDimensions),
        new Obstacle(296, 379, rockDimensions, rockDimensions),
        new Obstacle(295, 25, 150, bushHeight),
        new Obstacle(570, 138, 150, bushHeight),
        new Obstacle(605, 492, 90, bushHeight)];
}

// Enemy object. (constructor function)
function Enemy() {
    this.srcX = 140;
    this.srcY = 600;
    this.width = 45;
    this.height = 54;
    this.drawX = randomRange(0, canvasWidth - this.width);
    this.drawY = randomRange(0, canvasHeight - this.height);
    this.centerX = this.drawX + (this.width / 2);
    this.centerY = this.drawY + (this.height / 2);
    this.targetX = this.centerX;
    this.targetY = this.centerY;
    this.randomMoveTime = randomRange(4000, 10000);
    this.speed = 1;
    var that = this;
    this.moveInterval = setInterval(function() {that.setTargetLocation();}, that.randomMoveTime);
    this.isDead = false;
}

// which direction is Enemy facing?
Enemy.prototype.update = function () {
    this.centerX = this.drawX + (this.width / 2);
    this.centerY = this.drawY + (this.height / 2);
    this.checkDirection();
};

// draw Enemy
Enemy.prototype.draw = function () {
    ctxEntities.drawImage(imgSprite, this.srcX, this.srcY, this.width, this.height, this.drawX, this.drawY, this.width, this.height);
};

// Set Enemy movement limits.
// Can't go more than 50 in any direction. (per move)
// Can't exit canvas width or height.
Enemy.prototype.setTargetLocation = function () {
    this.randomMoveTime = randomRange(4000, 10000);
    var minX = this.centerX - 50,
        maxX = this.centerX + 50,
        minY = this.centerY - 50,
        maxY = this.centerY + 50;
    if (minX < 0) {
        minX = 0;
    }
    if (maxX > canvasWidth) {
        maxX = canvasWidth;
    }
    if (minY < 0) {
        minY = 0;
    }
    if (maxY > canvasHeight) {
        maxY = canvasHeight;
    }
    this.targetX = randomRange(minX, maxX);
    this.targetY = randomRange(minY, maxY);
};

// Update Enemy position based on direction facing
Enemy.prototype.checkDirection = function () {
    if (this.centerX < this.targetX) {
        this.drawX += this.speed;
    } else if (this.centerX > this.targetX) {
        this.drawX -= this.speed;
    }
    if (this.centerY < this.targetY) {
        this.drawY += this.speed;
    } else if (this.centerY > this.targetY) {
        this.drawY -= this.speed;
    }
};

// When Enemy dies, play dying sound.
Enemy.prototype.die = function () {
    var soundEffect = new Audio("audio/dying.wav");
    soundEffect.play();
    clearInterval(this.moveInterval);
    this.srcX = 185;
    this.isDead = true;
};

// Generate an array of enemies
function initEnemies() {
    for (var i = 0; i < numEnemies; i++) {
        enemies[enemies.length] = new Enemy();
    }
}

function updateAllEnemies() {
    for (var i = 0; i < enemies.length; i++) {
        enemies[i].update();
    }
}

// draw Enemies
function drawAllEnemies() {
    for (var i = 0; i < enemies.length; i++) {
        enemies[i].draw();
    }
}

// User input (arrow keys) determine keyboard value
function checkKey(e, value) {
    var keyID = e.keyCode || e.which;
    if (keyID === 38) { // Up arrow
        player1.isUpKey = value;
        e.preventDefault();
    }
    if (keyID === 39) { // Right arrow
        player1.isRightKey = value;
        e.preventDefault();
    }
    if (keyID === 40) { // Down arrow
        player1.isDownKey = value;
        e.preventDefault();
    }
    if (keyID === 37) { // Left arrow
        player1.isLeftKey = value;
        e.preventDefault();
    }
    if (keyID === 32) { // Spacebar
        player1.isSpacebar = value;
        e.preventDefault();
    }
}
// Is Player out of bounds?
// Did he run into a tree?
function outOfBounds(a, x, y) {
    var newBottomY = y + a.height,
        newTopY = y,
        newRightX = x + a.width,
        newLeftX = x,
        treeLineTop = 5,
        treeLineBottom = 570,
        treeLineRight = 750,
        treeLineLeft = 65;
    return newBottomY > treeLineBottom ||
        newTopY < treeLineTop ||
        newRightX > treeLineRight ||
        newLeftX < treeLineLeft;
}

// Did Player's bullet collide with an enemy
// or obstacle? (tree, rock, etc)?
function collision(a, b) {
    return a.drawX <= b.drawX + b.width &&
        a.drawX >= b.drawX &&
        a.drawY <= b.drawY + b.height &&
        a.drawY >= b.drawY;
}


text:
var riot = require('riot');
var page = require('page');
var authStore = require('stores/auth.js');
var spuTypeStore = require('stores/spu-type.js');
var spuStore = require('stores/spu.js');
var assetStore = require('stores/asset.js');
var vendorStore = require('stores/vendor.js');
var retailerStore = require('stores/retailer.js');
var skuStore = require('stores/sku.js');
var bus = require('riot-bus');
var camelCase = require('camelcase');
var config = require('config');
require('semantic-ui/semantic.js');
require('tags/login-app.tag');
require('tags/spu-type-list-app.tag');
require('tags/spu-type-app.tag');
require('tags/nav-bar.tag');
require('tags/spu-list-app.tag');
require('tags/spu-app.tag');
require('tags/vendor-list-app.tag');
require('tags/retailer-list-app.tag');
require('tags/sku-list-app.tag');
require('tags/vendor-app.tag');
require('tags/sku-app.tag');
require('tags/upload-sku-app.tag');
require('tags/retailer-app.tag');

var swal = require('sweetalert/sweetalert.min.js');
require('sweetalert/sweetalert.css');
var principal = require('principal');

// see https://github.com/riot/riot/issues/871
if (config.env === 'development') {
    riot.util.tmpl.errorHandler = function (err) {
        // console.error(err);
    };
}

var workspace = {
    stores: [],
};

riot.observable(workspace);

workspace.on('login.required logout.done', function () {
    page('/auth/login');
}).on('go', function (target) {
    page.show(target);
}).on('error', function (err) {
    console.error(err);
});

// VIEWS
//
var setTitle = function (title) {
    return function (ctx, next) {
        document.title = title;
        next();
    };
};

var resetStores = function (ctx, next) {
    bus.clear();
    bus.register(workspace);
    next();
};

var loginRequired = function (ctx, next) {
    if (authStore.authenticated()) {
        ctx.user = authStore.user();
        bus.register(authStore);
        principal.resetIdentity(ctx);
        next();
    } else {
        bus.trigger('login.required', ctx);
    }
};

var login = function (ctx, next) {
    riot.mount('#main', 'login-app');
    bus.register(authStore);
    next();
};

var spuTypeList = function (ctx, next) {
    bus.register(spuTypeStore);
    workspace.app = riot.mount('#main', 'spu-type-list-app', { ctx: ctx })[0];
    workspace.appName = 'spu-type-list';
    bus.trigger('spuType.list.fetch', ctx.query);
};

var spuList = function (ctx, next) {
    bus.register(spuStore);
    workspace.app = riot.mount('#main', 'spu-list-app', { ctx: ctx })[0];
    workspace.appName = 'spu-list';
    spuStore.fetchList(ctx.query);
    vendorStore.fetchList();
    spuTypeStore.fetchList({});
};

var vendorList = function (ctx, next) {
    bus.register(vendorStore);
    workspace.app = riot.mount('#main', 'vendor-list-app', { ctx: ctx })[0];
    workspace.appName = 'vendor-list';
    vendorStore.fetchList(ctx.query);
};

var retailerList = function (ctx, next) {
    bus.register(retailerStore);
    workspace.app = riot.mount('#main', 'retailer-list-app', { ctx: ctx })[0];
    workspace.appName = 'retailer-list';
    retailerStore.fetchList(ctx.query);
};

var skuList = function (ctx, next) {
    bus.register(skuStore);
    _.assign(ctx.query, {
        page: 1,
        perPage: 16,
    });
    workspace.app = riot.mount('#main', 'sku-list-app', {
        ctx: ctx
    })[0];
    workspace.appName = 'sku-list';
    skuStore.fetchList(ctx.query).done(function () {
        spuStore.fetchList();
    });
};

var uploadSKU = function (ctx, next) {
    bus.register(skuStore);
    bus.register(vendorStore);
    bus.register(spuStore);
    workspace.app = riot.mount('#main', 'upload-sku-app', { ctx: ctx })[0];
    workspace.appName = 'upload-sku';
    vendorStore.fetchList();
};

var navBar = function (ctx, next) {
    riot.mount('#nav-bar', 'nav-bar', {
        ctx: ctx
    });
    next();
};

var spuType = function (ctx, next) {
    bus.register(spuTypeStore);
    bus.register(assetStore);
    workspace.app = riot.mount('#main', 'spu-type-app', {
        ctx: ctx,
    })[0];
    workspace.appName = 'spu-type';
    ctx.params.id && bus.trigger('spuType.fetch', ctx.params.id);
};

var spu = function (ctx, next) {
    bus.register(spuStore);
    bus.register(spuTypeStore);
    bus.register(vendorStore);
    bus.register(assetStore);
    bus.register(retailerStore);
    workspace.app = riot.mount('#main', 'spu-app', { ctx: ctx })[0];
    workspace.appName = 'spu';
    if (ctx.params.id) {
        // must ensure spu is fetched first
        spuStore.fetch(ctx.params.id).then(function () {
            ['spuType', 'vendor', 'retailer'].forEach(function (store) {
                bus.trigger(store + '.list.fetch');
            });
        });
    } else {
        ['spuType', 'vendor', 'retailer'].forEach(function (store) {
            bus.trigger(store + '.list.fetch');
        });
    }
};

var vendor = function (ctx, next) {
    bus.register(vendorStore);
    workspace.app = riot.mount('#main', 'vendor-app', {ctx: ctx})[0];
    workspace.appName = 'vendor';
    ctx.params.id && bus.trigger('vendor.fetch', ctx.params.id);
};

var sku = function (ctx, next) {
    bus.register(skuStore);
    bus.register(spuStore);
    workspace.app = riot.mount('#main', 'sku-app', {
        ctx: ctx
    })[0];
    workspace.appName = 'sku';
    ctx.params.id && bus.trigger('sku.fetch', ctx.params.id);
    bus.trigger('spu.list.fetch');
};

var retailer = function (ctx, next) {
    bus.register(retailerStore);
    bus.register(assetStore);
    workspace.app = riot.mount('#main', 'retailer-app', { ctx: ctx })[0];
    workspace.appName = 'retailer';
    ctx.params.id && bus.trigger('retailer.fetch', ctx.params.id);
};

page(function (ctx, next) {
    var qs = ctx.querystring;
    ctx.query = {};

    if (qs) {
        // there's a potential bug, see https://github.com/visionmedia/page.js/issues/216
        qs.split('&').forEach(function(v) {
            var c = v.split('=');
            ctx.query[camelCase(c[0])] = decodeURIComponent(Array.prototype.concat.apply([], c.slice(1)).join('='));
        });
    }
    next();
});
page('/auth/login', resetStores, navBar, login);
page('/spu-type-list', function (ctx, next) {
    if (workspace.appName === 'spu-type-list') {
        // only update
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        bus.trigger('spuType.list.fetch', ctx.query);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, setTitle('乐鉴-SPU分类列表'), spuTypeList);
page('/spu-list', function (ctx, next) {
    ctx.query = ctx.query || {};
    ctx.query.page = ctx.query.page || 1;
    ctx.query.perPage = ctx.query.perPage || 12;
    if (workspace.appName === 'spu-list') {
        // only update
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        bus.trigger('spu.list.fetch', ctx.query);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, setTitle('乐鉴-SPU列表'), spuList);
page('/vendor-list', function (ctx, next) {
    if (workspace.appName === 'vendor-list') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        bus.trigger('vendor.list.fetch', ctx.query);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, setTitle('乐鉴-厂商列表'), vendorList);
page('/retailer-list', function (ctx, next) {
    ctx.query = ctx.query || {};
    ctx.query.page = ctx.query.page || 1;
    ctx.query.perPage = ctx.query.perPage || 12;
    if (workspace.appName === 'retailer-list') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        bus.trigger('retailer.list.fetch', ctx.query);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, setTitle('乐鉴-零售商列表'), retailerList);
page('/sku-list', function (ctx, next) {
    ctx.query = ctx.query || {};
    ctx.query.page = ctx.query.page || 1;
    ctx.query.perPage = ctx.query.perPage || 16;
    if (workspace.appName === 'sku-list') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        bus.trigger('sku.list.fetch', ctx.query);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, setTitle('乐鉴-SKU列表'), skuList);
page('/spu-type/:id?', function (ctx, next) {
    if (workspace.appName === 'spu-type') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        // 只有在没有获取对象数据的情况下, 才要重新获取数据
        ctx.params.id && !workspace.app.item && bus.trigger('spuType.fetch', ctx.params.id);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, spuType);
page('/spu/:id?', function (ctx, next) {
    if (workspace.appName === 'spu') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        ctx.params.id && !workspace.app.item && bus.trigger('spu.fetch', ctx.params.id);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, spu);
page('/vendor/:id?', function (ctx, next) {
    if (workspace.appName === 'spu') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        ctx.params.id && !workspace.app.item && bus.trigger('vendor.fetch', ctx.params.id);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, vendor);
page('/sku/:id?', function (ctx, next) {
    if (workspace.appName === 'sku') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        ctx.params.id && !workspace.app.item && bus.trigger('sku.fetch', ctx.params.id);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, sku);
page('/retailer/:id?', function (ctx, next) {
    if (workspace.appName === 'retailer') {
        workspace.app.opts = { ctx: ctx };
        workspace.app.update();
        ctx.params.id && !workspace.app.item && bus.trigger('retailer.fetch', ctx.params.id);
    } else {
        next();
    }
}, resetStores, loginRequired, navBar, retailer);
page('/upload-sku', resetStores, loginRequired, navBar, uploadSKU);
page('/', '/spu-list');

page();


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 6: 70 (1918)

#### Original name
Tulasnella tremelloides Wakef. & A. Pearson, 1918

### Remarks
null


text:
export { default as AppsDropdown } from './AppsDropdown';
export { default as ErrorBoundary } from './ErrorBoundary';
export { default as LocationErrorBoundary } from './LocationErrorBoundary';
export { default as LoaderPage } from './LoaderPage';
export { default as ProtonApp } from './ProtonApp';
export { default as StandalonePublicApp } from './StandalonePublicApp';
export { default as StandardLoadErrorPage } from './StandardLoadErrorPage';
export { default as StandardErrorPage } from './StandardErrorPage';
export { default as PrivateAppContainer } from './PrivateAppContainer';
export { default as StandardPrivateApp } from './StandardPrivateApp';
export { default as StandardPublicApp } from './StandardPublicApp';
export { default as SSOForkProducer } from './SSOForkProducer';
export { default as Signout } from './Signout';
export { default as StandardSetup } from './StandardSetup';
export { default as useOnLogout } from './useOnLogout';
export { default as EmptyViewContainer } from './EmptyViewContainer';
export * from './helper';

export * from './interface';


text:
package com.streamsets.pipeline.lib.el;

import com.streamsets.pipeline.api.ElFunction;
import com.streamsets.pipeline.api.ElParam;

//Mimics all record: EL functions returning '*'
public class FakeRecordEL {

  public static final String RECORD_EL_PREFIX = "record";

  private FakeRecordEL() {}

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "type",
    description = "Returns the type of the field represented by path 'fieldPath' for the record in context")
  public static String getType(
    @ElParam("fieldPath") String fieldPath) {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "value",
    description = "Returns the value of the field represented by path 'fieldPath' for the record in context")
  public static String getValue(
    @ElParam("fieldPath") String fieldPath) {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "valueOrDefault",
    description = "Returns the value of the field represented by path 'fieldPath' for the record in context or "
      + "the default value if the field is not present")
  public static String getValueOrDefault(
    @ElParam("fieldPath") String fieldPath, @ElParam("defaultValue") String defaultValue) {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "exists",
    description = "Checks if the field represented by path 'fieldPath' exists in the record")
  public static String exists(
    @ElParam("fieldPath") String fieldPath) {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "id",
    description = "Returns the id of the record in context")
  public static String getId() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "creator",
    description = "Returns the id of the record in context")
  public static String getStageCreator() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "path",
    description = "Returns the stage path for the record in context")
  public static String getStagesPath() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "errorStage",
    description = "Returns the error stage for the record in context")
  public static String getErrorStage() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "errorCode",
    description = "Returns the error code for the record in context")
  public static String getErrorCode() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "errorMessage",
    description = "Returns the error message for the record in context")
  public static String getErrorMessage() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "errorCollectorId",
    description = "Returns the error data collector id for the record in context")
  public static String getErrorDataCollectorId() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "errorPipeline",
    description = "Returns the error pipeline name for the record in context")
  public static String getErrorPipelineName() {
    return "*";
  }

  @ElFunction(
    prefix = RECORD_EL_PREFIX,
    name = "errorTime",
    description = "Returns the error time for the record in context")
  public static String getErrorTime() {
    return "*";
  }

}


text:
package li.strolch.xmlpers.test.impl;

import li.strolch.xmlpers.api.PersistenceContext;
import li.strolch.xmlpers.api.PersistenceContextFactory;
import li.strolch.xmlpers.objref.IdOfSubTypeRef;
import li.strolch.xmlpers.objref.ObjectRef;
import li.strolch.xmlpers.objref.ObjectReferenceCache;
import li.strolch.xmlpers.test.model.MyModel;

public class MyModelContextFactory implements PersistenceContextFactory<MyModel> {

	@Override
	public PersistenceContext<MyModel> createCtx(ObjectReferenceCache objectRefCache, MyModel t) {
		IdOfSubTypeRef objectRef = objectRefCache.getIdOfSubTypeRef(TestConstants.TYPE_RES, t.getType(), t.getId());
		PersistenceContext<MyModel> ctx = createCtx(objectRef);
		ctx.setObject(t);
		return ctx;
	}

	@Override
	public PersistenceContext<MyModel> createCtx(ObjectRef objectRef) {
		PersistenceContext<MyModel> ctx = new PersistenceContext<>(objectRef);
		ctx.setParserFactory(new MyModelParserFactory());
		return ctx;
	}

}


text:
SpecBegin(NSControlRACSupport)

describe(@"NSButton", ^{
	__block NSButton *button;

	void (^activate)(NSControl *) = ^(id _) {
		[button performClick:self];
	};

	beforeEach(^{
		button = [[NSButton alloc] initWithFrame:NSZeroRect];
		expect(button).notTo.beNil();
	});

	it(@"should send on rac_actionSignal", ^{
		RACSignal *actionSignal = button.rac_actionSignal;
		expect(button.target).to.beNil();
		expect(button.action).to.beNil();

		__block id value = nil;
		[actionSignal subscribeNext:^(id x) {
			value = x;
		}];

		expect(button.target).notTo.beNil();
		expect(button.action).notTo.beNil();
		expect(value).to.beNil();

		activate(button);
		expect(value).to.beIdenticalTo(button);
	});

	itShouldBehaveLike(RACControlActionExamples, ^{
		return @{
			RACControlActionExampleControl: button,
			RACControlActionExampleActivateBlock: activate
		};
	});
});

describe(@"NSTextField", ^{
	__block NSTextField *field;
	__block NSWindow *window;

	void (^activate)(NSControl *) = ^(id _) {
		expect([window makeFirstResponder:nil]).to.beTruthy();
		expect(window.firstResponder).to.equal(window);
	};

	beforeEach(^{
		field = [[NSTextField alloc] initWithFrame:NSZeroRect];
		expect(field).notTo.beNil();

		[field.cell setSendsActionOnEndEditing:YES];

		window = [[NSWindow alloc] initWithContentRect:NSZeroRect styleMask:NSTitledWindowMask backing:NSBackingStoreBuffered defer:NO];
		expect(window).notTo.beNil();

		[window.contentView addSubview:field];

		expect([window makeFirstResponder:field]).to.beTruthy();
		expect(window.firstResponder).notTo.equal(window);
	});

	it(@"should send on rac_actionSignal", ^{
		RACSignal *actionSignal = field.rac_actionSignal;
		expect(field.target).to.beNil();
		expect(field.action).to.beNil();

		__block id value = nil;
		[actionSignal subscribeNext:^(id x) {
			value = x;
		}];

		expect(field.target).notTo.beNil();
		expect(field.action).notTo.beNil();
		expect(value).to.beNil();

		activate(field);
		expect(value).to.beIdenticalTo(field);
	});

	itShouldBehaveLike(RACControlActionExamples, ^{
		return @{
			RACControlActionExampleControl: field,
			RACControlActionExampleActivateBlock: activate
		};
	});

	describe(@"-rac_textSignal", ^{
		it(@"should send changes", ^{
			NSMutableArray *strings = [NSMutableArray array];
			[field.rac_textSignal subscribeNext:^(NSString *str) {
				[strings addObject:str];
			}];

			expect(strings).to.equal(@[ @"" ]);

			NSText *fieldEditor = (id)window.firstResponder;
			expect(fieldEditor).to.beKindOf(NSText.class);

			[fieldEditor insertText:@"f"];
			[fieldEditor insertText:@"o"];
			[fieldEditor insertText:@"b"];

			NSArray *expected = @[ @"", @"f", @"fo", @"fob" ];
			expect(strings).to.equal(expected);
		});

		it(@"shouldn't give the text field eternal life", ^{
			__block BOOL dealloced = NO;
			@autoreleasepool {
				NSTextField *field __attribute__((objc_precise_lifetime)) = [[NSTextField alloc] initWithFrame:CGRectZero];
				[field.rac_deallocDisposable addDisposable:[RACDisposable disposableWithBlock:^{
					dealloced = YES;
				}]];
				[field.rac_textSignal subscribeNext:^(id x) {

				}];
			}

			expect(dealloced).will.beTruthy();
		});
	});
});

SpecEnd


text:
from django.db import models
from django.conf import settings
import os, copy
from cropduster import utils
from PIL import Image as pil
# from south.modelsinspector import add_introspection_rules
from django.core.exceptions import ValidationError

CROPDUSTER_UPLOAD_PATH = getattr(settings, "CROPDUSTER_UPLOAD_PATH", settings.MEDIA_ROOT)

IMAGE_SAVE_PARAMS =  {
	"quality" :95
}

MANUALLY_CROP = 0
AUTO_CROP = 1
AUTO_SIZE = 2

GENERATION_CHOICES = (
	(MANUALLY_CROP, "Manually Crop"),
	(AUTO_CROP, "Auto-Crop"),
	(AUTO_SIZE, "Auto-Size"),
)

RETINA_POSTFIX = "@2x"

class CachingMixin(object):
	pass
CachingManager = models.Manager

class SizeSet(CachingMixin, models.Model):
	objects = CachingManager()

	name = models.CharField(max_length=255, db_index=True)

	slug = models.SlugField(max_length=50, null=False,)

	def __unicode__(self):
		return u"%s" % self.name

	def get_unique_ratios(self, created=True):
		"""
			Shorthand to get all the unique ratios rather than show every possible thumbnail
		"""
		create_on_request =  not created

		size_query = Size.objects.all().filter(size_set__id=self.id, create_on_request=create_on_request)

		size_query.query.group_by = ["aspect_ratio"]
		try:
			return size_query
		except ValueError:
			return None

class SizeManager(CachingManager):

	def get_size_by_ratio(self, size_set, aspect_ratio_id):
		""" Gets the largest image of a certain ratio in this size set """

		size_query = self.all().only("aspect_ratio").filter(size_set=size_set, auto_size=MANUALLY_CROP).order_by("-aspect_ratio")

		size_query.query.group_by = ["aspect_ratio"]

		try:
			size = size_query[aspect_ratio_id]

			# get the largest size with this aspect ratio
			return self.all().filter(size_set=size_set, aspect_ratio=size.aspect_ratio, auto_size=MANUALLY_CROP).order_by("-width")[0]
		except IndexError:
			return None

class Size(CachingMixin, models.Model):

	objects = SizeManager()

	name = models.CharField(max_length=255, db_index=True)

	slug = models.SlugField(max_length=50, null=False,)

	height = models.PositiveIntegerField(blank=True, null=True)

	width = models.PositiveIntegerField(blank=True, null=True)

	auto_size = models.PositiveIntegerField("Thumbnail Generation", default=0, choices=GENERATION_CHOICES)

	size_set = models.ForeignKey(SizeSet)

	aspect_ratio = models.FloatField(default=1)

	create_on_request = models.BooleanField("Crop on request", default=False)

	retina = models.BooleanField("Auto-create retina thumb", default=False,)

	def clean(self):
		if not (self.width or self.height):
			raise ValidationError("Size requires either a width, a height, or both")

		elif self.auto_size != AUTO_SIZE and not (self.width and self.height):
			# Raise a validation error if one of the sizes is not set for cropping.
			# Auto-crop is the only one that can take a missing size.
			raise ValidationError("Auto-crop requires both sizes be specified")

	def save(self, *args, **kwargs):
		self.aspect_ratio = utils.aspect_ratio(self.width, self.height)
		super(Size, self).save(*args, **kwargs)

	class Meta:
		db_table = "cropduster_size"

	def __unicode__(self):
		return u"%s: %sx%s" % (self.name, self.width, self.height)

	@property
	def retina_size(self):
		""" Returns a Size object based on the current object but for the retina size """
		retina_size = copy.copy(self)
		retina_size.width = retina_size.width * 2
		retina_size.height = retina_size.height * 2
		retina_size.slug = u"%s%s" % (retina_size.slug, RETINA_POSTFIX)

		return retina_size

class Crop(CachingMixin, models.Model):
	class Meta:
		db_table = "cropduster_crop"
		unique_together = (("size", "image"),)

	objects = CachingManager()

	crop_x = models.PositiveIntegerField(default=0, blank=True, null=True)
	crop_y = models.PositiveIntegerField(default=0, blank=True, null=True)
	crop_w = models.PositiveIntegerField(default=0, blank=True, null=True)
	crop_h = models.PositiveIntegerField(default=0, blank=True, null=True)

	size = models.ForeignKey(
		"cropduster.Size",
		related_name = "size",
		verbose_name = "sizes",
	)
	image = models.ForeignKey(
		"cropduster.Image",
		related_name = "images",
		verbose_name = "images",
	)

	def __unicode__(self):
		return u"%s: %sx%s" % (self.image.image, self.size.width, self.size.height)

	def save(self, *args, **kwargs):
		"""
		Save the Crop object, and create the thumbnails by creating
		one rescaled version for each ratio and then resizing for each
		thumbnail within that ratio
		"""
		super(Crop, self).save(*args, **kwargs)

		if self.size:
			# get all the manually cropped sizes with the same aspect ratio as this crop/size
			sizes = Size.objects.all().filter(
				aspect_ratio=self.size.aspect_ratio,
				size_set=self.size.size_set,
				auto_size=0,
			).order_by("-width")

			if sizes:
				# create the cropped image
				cropped_image = utils.create_cropped_image(
					self.image.path,
					self.crop_x,
					self.crop_y,
					self.crop_w,
					self.crop_h
				)

				# loop through the other sizes of the same aspect ratio, and create those crops
				for size in sizes:
					self.image.rescale(cropped_image, size=size)
	def clean(self):

		if not hasattr(self, "crop_x") or not hasattr(self, "crop_y"):
			raise ValidationError("Missing crop values")

		if self.crop_x < 0 or self.crop_y < 0:
			raise ValidationError("Crop positions must be non-negative")

		if self.crop_w <= 0 or self.crop_h <= 0:
			raise ValidationError("Crop measurements must be greater than zero")

class Image(CachingMixin, models.Model):

	objects = CachingManager()

	validate_image_size = True

	image = models.ImageField(
		upload_to=CROPDUSTER_UPLOAD_PATH + "%Y/%m/%d",
		max_length=255,
		db_index=True
	)

	size_set = models.ForeignKey(
		SizeSet,
	)

	attribution = models.CharField(max_length=255, blank=True, null=True)

	caption = models.CharField(max_length=255, blank=True, null=True)

	class Meta:
		db_table = "cropduster_image"
		verbose_name = "Image"
		verbose_name_plural = "Image"

	def __init__(self, *args, **kwargs):
		if "validate_image_size" in kwargs:
			self.validate_image_size = kwargs["validate_image_size"]
		super(Image, self).__init__(*args, **kwargs)

	def __unicode__(self):
		if self.image:
			return u"%s" % self.image.url
		else:
			return ""

	@property
	def extension(self):
		if hasattr(self.image, "url"):
			file_root, extension = os.path.splitext(self.image.path)
			return extension
		else:
			return ""
	@property
	def path(self):
		""" Path to the original image file """
		return self.image.path

	@property
	def folder_path(self):
		""" System path to the folder containing the thumbnails """
		file_path, file_name = os.path.split(self.image.path)
		file_root, extension = os.path.splitext(file_name)
		return u"%s" % os.path.join(file_path, file_root)

	def thumbnail_path(self, size_slug, retina=False):
		""" System path to the image file for a thumbnail based on the slug """
		format = u"%s%s"
		if retina:
			format = u"%s" + RETINA_POSTFIX + "%s"

		return format % (os.path.join(self.folder_path, size_slug), self.extension)

	def retina_thumbnail_path(self, size_slug):
		""" System path to the image file for a retina thumbnail based on the slug """
		return self.thumbnail_path(size_slug, retina=True)

	@property
	def folder_url(self):
		""" Web URL for the folder containing the thumbs """
		if hasattr(self.image, "url"):
			file_path, file_name = os.path.split(self.image.url)
			file_root, extension = os.path.splitext(file_name)
			return u"%s" % os.path.join(file_path, file_root)
		else:
			return ""

	def thumbnail_url(self, size_slug, retina=False):
		""" Web URL for a thumbnail based on the size slug """
		format = u"%s%s"
		if retina:
			format = u"%s" + RETINA_POSTFIX + "%s"
		return format % (os.path.join(self.folder_url, size_slug), self.extension)

	def retina_thumbnail_url(self, size_slug):
		""" Web URL for a thumbnail based on the size slug """
		return self.thumbnail_url(size_slug, retina=True)

	def has_size(self, size_slug):
		return self.size_set.size_set.filter(slug=size_slug).exists()

	def get_absolute_url(self):
		return settings.STATIC_URL + self.image

	def get_crop(self, size):
		"""  Gets the crop for this image and size based on size set and aspect ratio """

		return Crop.objects.filter(size__size_set=size.size_set, size__aspect_ratio=size.aspect_ratio, image=self).order_by("-crop_w")[0]

	def save(self, *args, **kwargs):
		"""
		Save the image object and create any auto-sized thumbnails that don't need crops
		Also, delete any old thumbs that aren't being written over
		"""
		super(Image, self).save(*args, **kwargs)

		# get all the auto sized thumbnails and create them
		sizes = self.size_set.size_set.all().filter(
			auto_size__in=[AUTO_CROP, AUTO_SIZE],
			create_on_request=False
		)
		for size in sizes:
			self.create_thumbnail(size)

		# get all of the create on request sizes and delete the thumbnails
		# in anticipation of them being rewritten
		create_on_request_sizes = self.size_set.size_set.all().filter(
			auto_size__in=[AUTO_CROP, AUTO_SIZE],
			create_on_request=True
		)
		for size in create_on_request_sizes:
			if os.path.exists(self.thumbnail_path(size.slug)):
				os.remove(self.thumbnail_path(size.slug))

	def clean(self):
		""" Additional file validation for saving """

		if self.image:
			# Check for valid file extension
			if os.path.splitext(self.image.name)[1] == '':
				raise ValidationError("Please make sure images have file extensions before uploading")

			# Check for valid file
			try:
				pil_image = pil.open(self.image)
			except:
				raise ValidationError("Unable to open image file")

			# Check for minimum size requirement
			if self.validate_image_size:
				for size in self.size_set.size_set.all().order_by("-width"):
					if size.width > pil_image.size[0] or size.height > pil_image.size[1]:
						raise ValidationError("Uploaded image (%s x %s) is smaller than a required thumbnail size: %s" % (pil_image.size[0], pil_image.size[1], size))

		return super(Image, self).clean()

	def create_thumbnail(self, size, force_crop=False):
		""" Creates a thumbnail for an image at the specified size """

		if not size.auto_size:
			try:
				crop = self.get_crop(size)

				cropped_image = utils.create_cropped_image(
					self.image.path,
					crop.crop_x,
					crop.crop_y,
					crop.crop_w,
					crop.crop_h
				)
			except Crop.DoesNotExist:
				# auto-crop if no crop is defined
				cropped_image = pil.open(self.image.path)
		else:
			cropped_image = pil.open(self.image.path)

		self.rescale(cropped_image=cropped_image, size=size, force_crop=force_crop)

	def rescale(self, cropped_image, size, force_crop=False):
		""" Resizes and saves the image to other sizes of the same aspect ratio from a given cropped image """

		if force_crop or not size.create_on_request:
			auto_crop = (size.auto_size == AUTO_CROP)
			thumbnail = utils.rescale(cropped_image, size.width, size.height, auto_crop=auto_crop)

			# In case the thumbnail path hasn't been created yet
			if not os.path.exists(self.folder_path):
				try:
					os.makedirs(self.folder_path)
				except OSError:
					# Handles weird race conditions if the path wasn't created just yet
					if os.path.exists(self.folder_path):
						pass
					else:
						os.makedirs(self.folder_path)

			thumbnail.save(self.thumbnail_path(size.slug), **IMAGE_SAVE_PARAMS)

			# Create retina image
			if size.retina:
				retina_size = size.retina_size

				# Only create retina image if cropped image is large enough
				# If retina size is required, make a separate size
				if retina_size.width <= cropped_image.size[0] and retina_size.height <= cropped_image.size[1]:
					retina_thumbnail = utils.rescale(cropped_image, retina_size.width, retina_size.height, crop=retina_size.auto_size)
					retina_thumbnail.save(self.thumbnail_path(retina_size.slug), **IMAGE_SAVE_PARAMS)

	def tag(self, **kwargs):
		from cropduster.templatetags.images import get_image
		return get_image(self, **kwargs)

class CropDusterField(models.ForeignKey):
	pass

try:
	from south.modelsinspector import add_introspection_rules
except ImportError:
	pass
else:
	add_introspection_rules([], ["^cropduster\.models\.CropDusterField"])


text:
package org.springframework.security.config.annotation.web;

import org.junit.Test;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

/**
 * Tests for {@link AbstractRequestMatcherRegistry}.
 *
 * @author Ankur Pathak
 */
public class AbstractRequestMatcherRegistryAnyMatcherTests{

	@EnableWebSecurity
	static class AntMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
				.anyRequest().authenticated()
				.antMatchers("/demo/**").permitAll();

		}
	}

	@Test(expected = BeanCreationException.class)
	public void antMatchersCanNotWorkAfterAnyRequest(){
		loadConfig(AntMatchersAfterAnyRequestConfig.class);
	}

	@EnableWebSecurity
	static class MvcMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
				.anyRequest().authenticated()
				.mvcMatchers("/demo/**").permitAll();

		}
	}

	@Test(expected = BeanCreationException.class)
	public void mvcMatchersCanNotWorkAfterAnyRequest() {
		loadConfig(MvcMatchersAfterAnyRequestConfig.class);
	}

	@EnableWebSecurity
	static class RegexMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
				.anyRequest().authenticated()
				.regexMatchers(".*").permitAll();

		}
	}

	@Test(expected = BeanCreationException.class)
	public void regexMatchersCanNotWorkAfterAnyRequest() {
		loadConfig(RegexMatchersAfterAnyRequestConfig.class);
	}

	@EnableWebSecurity
	static class AnyRequestAfterItselfConfig extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
				.anyRequest().authenticated()
				.anyRequest().permitAll();

		}
	}

	@Test(expected = BeanCreationException.class)
	public void anyRequestCanNotWorkAfterItself() {
		loadConfig(AnyRequestAfterItselfConfig.class);
	}

	@EnableWebSecurity
	static class RequestMatchersAfterAnyRequestConfig extends WebSecurityConfigurerAdapter {
		protected void configure(HttpSecurity http) throws Exception {
			http
				.authorizeRequests()
				.anyRequest().authenticated()
				.requestMatchers(new AntPathRequestMatcher("/**")).permitAll();

		}
	}

	@Test(expected = BeanCreationException.class)
	public void requestMatchersCanNotWorkAfterAnyRequest() {
		loadConfig(RequestMatchersAfterAnyRequestConfig.class);
	}

	private void loadConfig(Class<?>... configs) {
		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
		context.setAllowCircularReferences(false);
		context.register(configs);
		context.setServletContext(new MockServletContext());
		context.refresh();
	}
}


text:
from __future__ import unicode_literals

import swapper
from factory import (
    Sequence,
    SubFactory,
)
from factory.django import DjangoModelFactory

from accelerator.tests.factories.criterion_factory import (
    CriterionFactory
)
CriterionOptionSpec = swapper.load_model('accelerator', 'CriterionOptionSpec')

class CriterionOptionSpecFactory(DjangoModelFactory):
    class Meta:
        model = CriterionOptionSpec

    option = Sequence(lambda n: "CriterionOptionSpec {0}".format(n))
    count = CriterionOptionSpec.DEFAULT_COUNT
    weight = CriterionOptionSpec.DEFAULT_WEIGHT
    criterion = SubFactory(CriterionFactory)


text:
# column-count

작성자 : 김동일

작성일 : 2015-09-14

css 레퍼런스 설명:
 - column-count : div 내 텍스트를 분할한다.

 - syntax :
```sh
column-count: length|auto|initial|inherit;
```

length:column 개수를 명시한다.

auto:기본 값, column-width에 따라 컬럼 수가 결정된다.

initial:기본 값으로 set되어 있는 값을 불러온다.

inherit:부모 element에 설정되어 있는 값을 상속 받는다.

sample code :
```html
<!DOCTYPE html>
<html>
<head>
<style>
.newspaper {
    -webkit-column-count: 3; /* Chrome, Safari, Opera에서 사용하는 css (반드시 앞에 -webkit-을 붙여야함)*/
    -moz-column-count: 3; /* Firefox에서 사용하는 css (반드시 앞에 -moz-을 붙여야함)*/
    column-count: 3; /*IE 10.0 이후 에서 사용하는 css (이전 버전은 지원 안함)*/
}
</style>
</head>
<body>

<p><strong>Note:</strong> The column-count property is not supported in Internet Explorer 9 and earlier versions.</p>

<div class="newspaper">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius.
</div>

</body>
</html>
```

결과

![column_count](../images/column-count.JPG)

-----

* [CSS3 README](../README.md)

* [column-count](column-count.md)
* [column-gap](column-gap.md)
* [column-rule](column-rule.md)
* [column-rule-color](column-rule-color.md)
* [column-rule-style](column-rule-style.md)
* [column-rule-width](column-rule-width.md)
* [column-span](column-span.md)
* [column-width](column-width.md)
* [columns](columns.md)


text:
<ion-header>
  <ion-navbar color="danger">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
  </ion-navbar>
</ion-header>

<ion-content>

    <ion-card>
      <ion-card-header>
        Bar Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #barCanvas></canvas>
      </ion-card-content>
    </ion-card>

    <ion-card>
      <ion-card-header>
        Doughnut Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #doughnutCanvas></canvas>
      </ion-card-content>
    </ion-card>

    <ion-card>
      <ion-card-header>
        Line Chart
      </ion-card-header>
      <ion-card-content>
        <canvas #lineCanvas></canvas>
      </ion-card-content>
    </ion-card>

</ion-content>


text:
using namespace chrono;

int main(int argc, char* argv[]) {
    //
    // EXAMPLE 1: create a ramp ChFunction, set properties, evaluate it.
    //

    GetLog() << "Chrono revision: " << CHRONOENGINE_VCS_REVISION << "\n";
    GetLog() << "Chrono version: " << CHRONOENGINE_VERSION << "\n";

    GetLog() << "==== Test 1...\n\n";

    ChFunction_Ramp f_ramp;

    f_ramp.Set_ang(0.1);  // set angular coefficient;
    f_ramp.Set_y0(0.4);   // set y value for x=0;

    // Evaluate y=f(x) function at a given x value, using Get_y() :
    double y = f_ramp.Get_y(10);
    // Evaluate derivative df(x)/dx at a given x value, using Get_y_dx() :
    double ydx = f_ramp.Get_y_dx(10);

    GetLog() << "   ChFunction_Ramp at x=0: y=" << y << "  dy/dx=" << ydx << "\n\n";

    //
    // EXAMPLE 2: save values of a sine ChFunction  into a file
    //

    GetLog() << "==== Test 2...\n\n";

    ChFunction_Sine f_sine;

    f_sine.Set_amp(2);     // set amplitude;
    f_sine.Set_freq(1.5);  // set frequency;

    ChStreamOutAsciiFile file_f_sine("f_sine_out.dat");

    // Evaluate y=f(x) function along 100 x points, and its derivatives,
    // and save to file (later it can be loaded, for example, in Matlab using the 'load()' command)
    for (int i = 0; i < 100; i++) {
        double x = (double)i / 50.0;
        double y = f_sine.Get_y(x);
        double ydx = f_sine.Get_y_dx(x);
        double ydxdx = f_sine.Get_y_dxdx(x);
        file_f_sine << x << " " << y << " " << ydx << " " << ydxdx << "\n";
    }

    //
    // EXAMPLE 3: use a custom function (see class at the beginning of this file)
    //

    GetLog() << "==== Test 3...\n\n";

    // The following class will be used as an example of how
    // how you can create custom functions based on the ChFunction interface.
    // There is at least one mandatory member function to implement:  Get_y().
    // [Note that the base class implements a default computation of derivatives
    // Get_ydx() and Get_ydxdx() by using a numerical differentiation, however
    // if you know the analytical expression of derivatives, you can override
    // the base Get_ydx() and Get_ydxdx() too, for higher precision.]

    class ChFunction_MyTest : public ChFunction {
      public:
        ChFunction* new_Duplicate() { return new ChFunction_MyTest; }

        double Get_y(double x) { return cos(x); }  // just for test: simple cosine
    };

    ChFunction_MyTest f_test;

    ChStreamOutAsciiFile file_f_test("f_test_out.dat");

    // Evaluate y=f(x) function along 100 x points, and its derivatives,
    // and save to file (later it can be loaded, for example, in Matlab using the 'load()' command)
    for (int i = 0; i < 100; i++) {
        double x = (double)i / 50.0;
        double y = f_test.Get_y(x);
        double ydx = f_test.Get_y_dx(x);
        double ydxdx = f_test.Get_y_dxdx(x);
        file_f_test << x << " " << y << " " << ydx << " " << ydxdx << "\n";
    }

    //
    // EXAMPLE 4: mount some functions in a sequence using ChFunction_Sequence
    //

    GetLog() << "==== Test 4...\n\n";

    ChFunction_Sequence f_sequence;

    ChSharedPtr<ChFunction_ConstAcc> f_constacc1(new ChFunction_ConstAcc);
    f_constacc1->Set_end(0.5);  // length of ramp
    f_constacc1->Set_h(0.3);    // height of ramp
    f_sequence.InsertFunct(f_constacc1, 0.5, 1, false, false, false, 0);

    ChSharedPtr<ChFunction_Const> f_const(new ChFunction_Const);
    f_sequence.InsertFunct(f_const, 0.4, 1, true, false, false, -1);

    ChSharedPtr<ChFunction_ConstAcc> f_constacc2(new ChFunction_ConstAcc);
    f_constacc2->Set_end(0.6);  // length of ramp
    f_constacc2->Set_av(0.3);   // acceleration ends after 30% length
    f_constacc2->Set_aw(0.7);   // deceleration starts after 70% length
    f_constacc2->Set_h(-0.2);   // height of ramp
    f_sequence.InsertFunct(f_constacc2, 0.6, 1, true, false, false, -1);

    f_sequence.Setup();

    ChStreamOutAsciiFile file_f_sequence("f_sequence_out.dat");

    // Evaluate y=f(x) function along 100 x points, and its derivatives,
    // and save to file (later it can be loaded, for example, in Matlab using the 'load()' command)
    for (int i = 0; i < 100; i++) {
        double x = (double)i / 50.0;
        double y = f_sequence.Get_y(x);
        double ydx = f_sequence.Get_y_dx(x);
        double ydxdx = f_sequence.Get_y_dxdx(x);
        file_f_sequence << x << " " << y << " " << ydx << " " << ydxdx << "\n";
    }

    return 0;
}


text:
package org.elasticsearch.xpack.sql.type;

import org.elasticsearch.xpack.sql.SqlIllegalArgumentException;

import java.util.Objects;

import static java.util.Collections.emptyMap;

/**
 * Representation of field mapped differently across indices.
 * Used during mapping discovery only.
 */
public class InvalidMappedField extends EsField {

    private final String errorMessage;

    public InvalidMappedField(String name, String errorMessage) {
        super(name, DataType.UNSUPPORTED, emptyMap(), false);
        this.errorMessage = errorMessage;
    }

    public String errorMessage() {
        return errorMessage;
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), errorMessage);
    }

    @Override
    public boolean equals(Object obj) {
        if (super.equals(obj)) {
            InvalidMappedField other = (InvalidMappedField) obj;
            return Objects.equals(errorMessage, other.errorMessage);
        }

        return false;
    }

    @Override
    public EsField getExactField() {
        throw new SqlIllegalArgumentException("Field [" + getName() + "] is invalid, cannot access it");

    }

    @Override
    public Exact getExactInfo() {
        return new Exact(false, "Field [" + getName() + "] is invalid, cannot access it");
    }
}


text:
A command line podcast client written in golang.

## Usage

Usage of `podcasts`:

  `-days=1`: Number of days back to download an episode

  `-output=/tmp/output.sh`: Path of the output file

  `-add=http://feed.thisamericanlife.org/talpodcast`: Add feed url to the list of podcasts

Example:

```./podcasts -output=/tmp/podcast.sh -days=3```

The list of podcasts is stored in the home directory of the current user. The file name is `~/.podcasts/feeds.txt`


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// temp_table.h
//
// Identification: /peloton/src/include/storage/temp_table.h
//
// Copyright (c) 2015, 2016 Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#pragma once

#include "common/logger.h"
#include "common/macros.h"
#include "storage/abstract_table.h"

namespace peloton {

namespace catalog {
class Schema;
}

namespace storage {

class Tuple;
class TileGroup;
class TileGroupHeader;

// FIXME
const size_t TEMPTABLE_DEFAULT_SIZE = 100;  // # of tuples

// FIXME
const oid_t TEMPTABLE_TILEGROUP_ID = 99999;

//===--------------------------------------------------------------------===//
// TempTable
//===--------------------------------------------------------------------===//

/**
 * A TempTable is a non-thread-safe place to store tuples that don't
 * need to be durable, don't need indexes, don't need constraints.
 * This is designed to be faster than DataTable.
 */
class TempTable : public AbstractTable {
  TempTable() = delete;

 public:
  // Table constructor
  TempTable(const oid_t &table_oid, catalog::Schema *schema,
            const bool own_schema,
            const peloton::LayoutType layout_type = peloton::LayoutType::ROW);

  ~TempTable();

  //===--------------------------------------------------------------------===//
  // TUPLE OPERATIONS
  //===--------------------------------------------------------------------===//

  // insert tuple in table. the pointer to the index entry is returned as
  // index_entry_ptr.
  ItemPointer InsertTuple(const Tuple *tuple,
                          concurrency::TransactionContext *transaction,
                          ItemPointer **index_entry_ptr = nullptr,
                          bool check_fk = true) override;

  // designed for tables without primary key. e.g., output table used by
  // aggregate_executor.
  ItemPointer InsertTuple(const Tuple *tuple) override;

  //===--------------------------------------------------------------------===//
  // TILE GROUP
  //===--------------------------------------------------------------------===//

  // Offset is a 0-based number local to the table
  std::shared_ptr<storage::TileGroup> GetTileGroup(
      const std::size_t &tile_group_offset) const override ;

  std::shared_ptr<storage::TileGroup> GetTileGroupById(
      const oid_t &tile_group_id) const override;

  // Number of TileGroups that the table has
  inline size_t GetTileGroupCount() const override {
    return tile_groups_.size();
  }

  //===--------------------------------------------------------------------===//
  // UTILITIES
  //===--------------------------------------------------------------------===//

  std::string GetName() const override;

  //===--------------------------------------------------------------------===//
  // STATS
  //===--------------------------------------------------------------------===//

  inline void IncreaseTupleCount(const size_t &amount) override {
    number_of_tuples_ += amount;
  }

  inline void DecreaseTupleCount(const size_t &amount) override {
    number_of_tuples_ -= amount;
  }

  inline void SetTupleCount(const size_t &num_tuples) override {
    number_of_tuples_ = num_tuples;
  }

  inline size_t GetTupleCount() const override { return number_of_tuples_; }

 protected:
  //===--------------------------------------------------------------------===//
  // INTERNAL METHODS
  //===--------------------------------------------------------------------===//

  oid_t AddDefaultTileGroup();

 private:
  // This is where we're actually going to store the data for this table
  std::vector<std::shared_ptr<storage::TileGroup>> tile_groups_;

  // Counter for the # of tuples that this TempTable currently holds.
  // We don't need to protect this because a TempTable is not meant to be
  // concurrent.
  size_t number_of_tuples_ = 0;
};

}  // namespace storage
}  // namespace peloton


text:
/*! D3punchcard v0.1.0 - MIT license */
/*eslint no-unused-vars: [2, { "args": "none" }]*/
/*global define*/

(function (global) {
  'use strict';

  function moduleDefinition(d3) {

  function D3punchcard(options) {

    // Reverse the data as we draw
    // from the bottom up.
    this.data = options.data.reverse();
    this.element = options.element;

    // Find the max value to normalize the size of the circles.
    this.max = d3.max(this.data, function(array) {

      // we ignore the first element as it is metadata
      return d3.max(array.slice(1), function ( obj ) {

        // and we only return the interger verion of the value, not the key
        return parseFloat( obj.value );
      });
    });

    // set the upperlimit if we have it
    // otherwise use the max
    if( options.upperLimit ){
      this.upperLimit = options.upperLimit;
    } else {
      this.upperLimit = this.max;
    }

    return this;
  }

D3punchcard.prototype.draw = function( options ){

  var margin = 10,
      lineHeight = 5,
      width = options.width,
      paneLeft = 80,
      paneRight = width - paneLeft,
      sectionHeight = 35,
      height = (sectionHeight * this.data.length),
      sectionWidth = paneRight / this.data[0].length,
      circleRadius = 14,
      x,
      y,
      punchcard,
      punchcardRow,
      xAxis,
      rScale;

  // X-Axis.
  x = d3.scale.linear().domain([0, this.data[0].length - 1])
    .range([ paneLeft + (sectionWidth / 2), paneRight + (sectionWidth / 2)]);

  // Y-Axis.
  y = d3.scale.linear().domain([0, this.data.length - 1])
    .range([0, height - sectionHeight]);

  rScale = d3.scale.linear()
    .domain([0, this.upperLimit, this.max])
    .range([0, circleRadius, circleRadius]);

  // these functions hide and show the circles and text values
  function handleRowMouseover(){
    var g = d3.select(this).node().parentNode;
    d3.select(g).selectAll('circle').style('display', 'none');
    d3.select(g).selectAll('text.value').style('display', 'block');
  }

  function handleRowMouseout(){
    var g = d3.select(this).node().parentNode;
    d3.select(g).selectAll('circle').style('display', 'block');
    d3.select(g).selectAll('text.value').style('display', 'none');
  }

  // The main SVG element.
  punchcard = d3.select(this.element)
    .html('')
    .append('svg')
      .attr('width', width)
      .attr('height', height + (margin * 3))
      .append('g');

  // create the x axis holder
  xAxis = punchcard.selectAll('.row')
    .data([this.data[0].slice(1)])
    .enter()
    .append('g')
    .attr('class', 'xaxis');

  // create the x axis line
  xAxis.
    append('line').
    attr('x1', 0).
    attr('x2', width).
    attr('y1', (margin * 3)).
    attr('y2', (margin * 3)).
    style('stroke-width', 1).
    style('stroke', '#efefef');

  // create x-axis ticks
  xAxis.
    selectAll('line.tick').
    data(function(d, i) {
      return d;
    }).
    enter().
    append('line').
    attr('class', 'tick').
    attr('x1', function(d, i) { return paneLeft + x(i); }).
    attr('x2', function(d, i) { return paneLeft + x(i); }).
    attr('y1', function(d, i) {
      return margin * 2;
    }).
    attr('y2', function(d, i) {
      return (margin * 3);
    }).
    style('stroke-width', 1).
    style('stroke', '#efefef');

  // create x-axis tick text.
  xAxis.
    selectAll('.rule').
    data(function(d, i) {
      return d;
    }).
    enter().
    append('text').
    attr('class', 'rule').
    attr('x', function(d, i) {
      return paneLeft + x(i);
    }).
    attr('y', margin + lineHeight).
    attr('text-anchor', 'middle').
    text(function(d) {
      return d.key;
    });

  // create rows
  punchcardRow = punchcard.selectAll('.row')
    .data( this.data )
    .enter()
    .append('g')
    .attr('class', 'row')
    .attr('transform', function(d, i) {
      var ty = height - y(i) - (sectionHeight / 2) + (margin * 3);
      return 'translate(0, ' + ty + ')';
    });

  // create row divinding lines
  punchcardRow.
    selectAll('line').
    data([0]).
    enter().
    append('line').
    attr('x1', 0).
    attr('x2', width).
    attr('y1', (sectionHeight / 2)).
    attr('y2', (sectionHeight / 2)).
    style('stroke-width', 1).
    style('stroke', '#efefef');

  // create row headers
  punchcardRow.
    selectAll('.textheader').
    data( function(d, i ) {

      // we only return the first element of each array
      // which contains the header text
      return [d[0]];
    } ).
    enter().
    append('text').
    attr('x', 0).
    attr('y', function (d, i) {
      return lineHeight;
    }).
    attr('class', 'textheader').
    attr('text-anchor', 'left').
    text(function (d, i) {
      return d.value;
    })
    .on('mouseover', handleRowMouseover)
    .on('mouseout', handleRowMouseout);

  // draw circles for each row
  punchcardRow.
    selectAll('circle').
    data( function(d, i) {
      return d.slice(1);
    } ).
    enter().
    append('circle').
    style('fill', '#888').
    attr('r', function(d, i) {
      return rScale( parseFloat( d.value ) );
    }).
    attr('transform', function(d, i) {
      var tx = paneLeft + x(i);
      return 'translate(' + tx + ', 0)';
    });

  // draw text values for each row
  punchcardRow.
    selectAll('text.value').
    data(function(d, i) {
      return d.slice(1);
    }).
    enter().
    append('text').
    attr('class', 'value').
    style('display', 'none').
    text(function(d, i) {
      return d.value;
    }).
    attr('text-anchor', 'middle').
    attr('x', function(d, i) {
      return paneLeft + x(i);
    }).
    attr('y', function(d, i) {
      return lineHeight;
    });

  return this;
};

// to be called when closing a view
// in which this object has been created
D3punchcard.prototype.destroy = function() {
  // remove event listeners
  d3.select(this.element)
    .selectAll('text.textheader')
    .on('mouseover', null)
    .on('mouseout', null);
};

/**
 * Expose D3punchcard
 */

return D3punchcard;

// ---------------------------------------------------------------------------

} if (typeof exports === 'object') {
    // node export
    module.exports = moduleDefinition(require('d3'));
} else if (typeof define === 'function' && define.amd) {
    // amd anonymous module registration
    define(['d3'], moduleDefinition);
} else {
    // browser global
    global.D3punchcard = moduleDefinition(global.d3);
}}(this));


text:
package advancedhud.client.huditems;

import advancedhud.api.Alignment;
import advancedhud.api.HUDRegistry;
import advancedhud.api.HudItem;
import advancedhud.api.RenderAssist;
import advancedhud.client.ui.GuiAdvancedHUDConfiguration;
import advancedhud.client.ui.GuiScreenHudItem;
import advancedhud.client.ui.GuiScreenReposition;
import aurelienribon.tweenengine.Tween;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.MathHelper;
import org.lwjgl.opengl.GL11;

public class HudItemAir extends HudItem {

    private boolean wasInWater = true;

    public HudItemAir() {
        // If we override the constructor, we should ALWAYS call super()! It's important!
        super();
        // Set up tweening for opacity
        Tween.registerAccessor(HudItemAir.class, new HudItemAir.Engine());
    }

    @Override
    public String getName() {
        return "air";
    }

    @Override
    public String getButtonLabel() {
        return "AIR";
    }

    @Override
    public Alignment getDefaultAlignment() {
        if (rotated)
            return Alignment.CENTERRIGHT;
        return Alignment.BOTTOMCENTER;
    }

    @Override
    public int getDefaultPosX() {
        if (rotated)
            return HUDRegistry.screenWidth - 49;
        return HUDRegistry.screenWidth / 2 + 10;
    }

    @Override
    public int getDefaultPosY() {
        if (rotated)
            return HUDRegistry.screenHeight / 2 + 10;
        return HUDRegistry.screenHeight - 49;
    }

    @Override
    public int getWidth() {
        if (rotated)
            return 9;
        return 81;
    }

    @Override
    public int getHeight() {
        if (rotated)
            return 81;
        return 9;
    }

    @Override
    public int getDefaultID() {
        return 3;
    }

    @Override
    public void render(float paramFloat) {
        GL11.glEnable(GL11.GL_BLEND);
        GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
        Minecraft mc = Minecraft.getMinecraft();
        RenderAssist.bindTexture(Gui.icons);
        int left = posX + 81;
        int top = posY;

        if (mc.thePlayer.isInsideOfMaterial(Material.water) || mc.currentScreen instanceof GuiAdvancedHUDConfiguration || mc.currentScreen instanceof GuiScreenReposition) {
            if (!wasInWater) {
                Tween.to(this, Engine.OPACITY, 0.1f).target(1.0f).start(manager);
                wasInWater = true;
            }
        }
        if (!mc.thePlayer.isInsideOfMaterial(Material.water) && wasInWater) {
            Tween.to(this, Engine.OPACITY, 1.0f).delay(1.0f).target(0.0f).start(manager);
            wasInWater = false;
        }

        GL11.glColor4f(1.0f, 1.0f, 1.0f, this.getOpacity());
        int air = mc.thePlayer.getAir();
        int full = MathHelper.ceiling_double_int((air - 2) * 10.0D / 300.0D);
        int partial = MathHelper.ceiling_double_int(air * 10.0D / 300.0D) - full;

        for (int i = 0; i < full + partial; ++i) {
            if (!rotated)
                RenderAssist.drawTexturedModalRect(left - i * 8 - 9, top, i < full ? 16 : 25, 18, 9, 9);
            else
                RenderAssist.drawTexturedModalRect(left - 81, top + 72 - i * 8, i < full ? 16 : 25, 18, 9, 9);
        }
    }

    @Override
    public boolean needsTween() {
        return true;
    }

    @Override
    public boolean isRenderedInCreative() {
        return false;
    }

    @Override
    public GuiScreen getConfigScreen() {
        return new GuiScreenHudItem(Minecraft.getMinecraft().currentScreen, this);
    }

    // This is the tweening engine's interface. Here we register any tween actions we might want to perform.
    public static class Engine implements TweenEngine<HudItemAir> {

        // For HudItemAir we really only need opacity, so we only register this action.
        public static final int OPACITY = 1;

        @Override
        public int getValues(HudItemAir target, int tweenType, float[] returnValues) {
            switch (tweenType) {
                case OPACITY: returnValues[0] = target.getOpacity(); return 1;
                default: assert false; return -1;
            }
        }

        @Override
        public void setValues(HudItemAir target, int tweenType, float[] newValues) {
            switch (tweenType) {
                case OPACITY: target.setOpacity(newValues[0]); break;
                default: assert false; break;
            }

        }
    }

}


text:
<?php
namespace Chamilo\Application\Weblcms\Storage\DataClass;

use Chamilo\Application\Weblcms\Storage\DataManager;
use Chamilo\Libraries\Storage\DataClass\DataClass;
use Chamilo\Libraries\Storage\DataClass\Listeners\DataClassListener;
use Chamilo\Libraries\Storage\DataClass\Listeners\DisplayOrderDataClassListener;
use Chamilo\Libraries\Storage\DataClass\Listeners\DisplayOrderDataClassListenerSupport;
use Chamilo\Libraries\Storage\Query\Condition\AndCondition;
use Chamilo\Libraries\Storage\Query\Condition\EqualityCondition;
use Chamilo\Libraries\Storage\Query\Variable\PropertyConditionVariable;
use Chamilo\Libraries\Storage\Query\Variable\StaticConditionVariable;

/**
 * $Id: course_type_user_category.class.php 216 2009-11-13 14:08:06Z Tristan $
 *
 * @package application.lib.weblcms.course_type
 */
class CourseTypeUserCategoryRelCourse extends DataClass implements DisplayOrderDataClassListenerSupport
{
    const PROPERTY_COURSE_TYPE_USER_CATEGORY_ID = 'course_type_user_category_id';
    const PROPERTY_COURSE_ID = 'course_id';
    const PROPERTY_USER_ID = 'user_id';
    const PROPERTY_SORT = 'sort';

    public function __construct($default_properties = array(), $optional_properties = array())
    {
        parent::__construct($default_properties = $optional_properties);
        $this->add_listener(new DisplayOrderDataClassListener($this));
    }

    /**
     * Get the default properties of all user course user categories.
     *
     * @return array The property names.
     */
    public static function get_default_property_names($extended_property_names = array())
    {
        return array(
            self::PROPERTY_COURSE_TYPE_USER_CATEGORY_ID,
            self::PROPERTY_COURSE_ID,
            self::PROPERTY_USER_ID,
            self::PROPERTY_SORT);
    }

    public function get_course_type_user_category_id()
    {
        return $this->get_default_property(self::PROPERTY_COURSE_TYPE_USER_CATEGORY_ID);
    }

    public function get_course_id()
    {
        return $this->get_default_property(self::PROPERTY_COURSE_ID);
    }

    public function get_user_id()
    {
        return $this->get_default_property(self::PROPERTY_USER_ID);
    }

    public function get_sort()
    {
        return $this->get_default_property(self::PROPERTY_SORT);
    }

    public function set_course_type_user_category_id($course_type_user_category_id)
    {
        $this->set_default_property(self::PROPERTY_COURSE_TYPE_USER_CATEGORY_ID, $course_type_user_category_id);
    }

    public function set_course_id($course_id)
    {
        $this->set_default_property(self::PROPERTY_COURSE_ID, $course_id);
    }

    public function set_user_id($user_id)
    {
        $this->set_default_property(self::PROPERTY_USER_ID, $user_id);
    }

    public function set_sort($sort)
    {
        $this->set_default_property(self::PROPERTY_SORT, $sort);
    }

    public function update()
    {
        $this->notify(DataClassListener::BEFORE_UPDATE);
        $success = DataManager::getInstance()->update($this, $this->get_primary_key_conditions());
        $this->notify(DataClassListener::AFTER_UPDATE, array($success));

        return $success;
    }

    public function delete()
    {
        $this->notify(DataClassListener::BEFORE_DELETE);
        $success = DataManager::deletes(self::class_name(), $this->get_primary_key_conditions());
        $this->notify(DataClassListener::AFTER_DELETE, array($success));

        return $success;
    }

    /**
     * Returns the primary key condition
     *
     * @return \libraries\storage\Condition
     */
    protected function get_primary_key_conditions()
    {
        $conditions = array();

        $conditions[] = new EqualityCondition(
            new PropertyConditionVariable(
                CourseTypeUserCategoryRelCourse::class_name(),
                CourseTypeUserCategoryRelCourse::PROPERTY_COURSE_ID),
            new StaticConditionVariable($this->get_course_id()));

        $conditions[] = new EqualityCondition(
            new PropertyConditionVariable(
                CourseTypeUserCategoryRelCourse::class_name(),
                CourseTypeUserCategoryRelCourse::PROPERTY_COURSE_TYPE_USER_CATEGORY_ID),
            new StaticConditionVariable($this->get_course_type_user_category_id()));

        return new AndCondition($conditions);
    }

    /**
     * Returns the property for the display order
     *
     * @return string
     */
    public function get_display_order_property()
    {
        return new PropertyConditionVariable(self::class_name(), self::PROPERTY_SORT);
    }

    /**
     * Returns the properties that define the context for the display order (the properties on which has to be limited)
     *
     * @return Condition
     */
    public function get_display_order_context_properties()
    {
        return array(
            new PropertyConditionVariable(self::class_name(), self::PROPERTY_COURSE_TYPE_USER_CATEGORY_ID),
            new PropertyConditionVariable(self::class_name(), self::PROPERTY_USER_ID));
    }
}