text:
package org.spongepowered.common.mixin.core.entity.item;

import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityBoat;
import net.minecraft.nbt.NBTTagCompound;
import org.spongepowered.api.entity.vehicle.Boat;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.mixin.core.entity.MixinEntity;

@Mixin(EntityBoat.class)
public abstract class MixinEntityBoat extends MixinEntity implements Boat {

    @Shadow private double speedMultiplier;

    private double maxSpeed = 0.35D;
    private boolean moveOnLand = false;
    private double occupiedDecelerationSpeed = 0D;
    private double unoccupiedDecelerationSpeed = 0.8D;

    private double tempMotionX;
    private double tempMotionZ;
    private double tempSpeedMultiplier;
    private double initialDisplacement;

    @Inject(method = "onUpdate()V", at = @At(value = "INVOKE", target = "Lnet/minecraft/entity/item/EntityBoat;moveEntity(DDD)V"))
    public void implementLandBoats(CallbackInfo ci) {
        if (this.onGround && this.moveOnLand) {
            this.motionX /= 0.5;
            this.motionY /= 0.5;
            this.motionZ /= 0.5;
        }
    }

    @Inject(method = "onUpdate()V", at = @At(value = "INVOKE", target = "java.lang.Math.sqrt(D)D", ordinal = 0))
    public void beforeModifyMotion(CallbackInfo ci) {
        this.initialDisplacement = Math.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ);
    }

    @Inject(method = "onUpdate()V", at = @At(value = "INVOKE", target = "java.lang.Math.sqrt(D)D", ordinal = 1))
    public void beforeLimitSpeed(CallbackInfo ci) {
        this.tempMotionX = this.motionX;
        this.tempMotionZ = this.motionZ;
        this.tempSpeedMultiplier = this.speedMultiplier;
    }

    @Inject(method = "onUpdate()V", at = @At(value = "FIELD", target = "Lnet/minecraft/entity/item/EntityBoat;onGround:Z", ordinal = 1))
    public void afterLimitSpeed(CallbackInfo ci) {
        this.motionX = this.tempMotionX;
        this.motionZ = this.tempMotionZ;
        this.speedMultiplier = this.tempSpeedMultiplier;
        double displacement = Math.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ);

        if (displacement > this.maxSpeed) {
            double ratio = this.maxSpeed / displacement;
            this.motionX *= ratio;
            this.motionZ *= ratio;
            displacement = this.maxSpeed;
        }

        if ((displacement > this.initialDisplacement) && (this.speedMultiplier < this.maxSpeed)) {
            this.speedMultiplier += (this.maxSpeed - this.speedMultiplier) / this.maxSpeed * 100.0;
            this.speedMultiplier = Math.min(this.speedMultiplier, this.maxSpeed);
        } else {
            this.speedMultiplier -= (this.speedMultiplier - 0.07) / this.maxSpeed * 100.0;
            this.speedMultiplier = Math.max(this.speedMultiplier, 0.07);
        }
    }

    @Inject(method = "onUpdate()V",
            at = @At(value = "FIELD", target = "Lnet/minecraft/entity/item/EntityBoat;riddenByEntity:Lnet/minecraft/entity/Entity;", ordinal = 0))
    public void implementCustomDeceleration(CallbackInfo ci) {
        if (!(this.riddenByEntity instanceof EntityLivingBase)) {
            double decel = this.riddenByEntity == null ? this.unoccupiedDecelerationSpeed : this.occupiedDecelerationSpeed;
            this.motionX *= decel;
            this.motionZ *= decel;

            if (this.motionX < 0.00005) {
                this.motionX = 0.0;
            }

            if (this.motionZ < 0.00005) {
                this.motionZ = 0.0;
            }
        }
    }

    @Override
    public boolean isInWater() {
        return !this.onGround;
    }

    @Override
    public double getMaxSpeed() {
        return this.maxSpeed;
    }

    @Override
    public void setMaxSpeed(double maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    @Override
    public boolean canMoveOnLand() {
        return this.moveOnLand;
    }

    @Override
    public void setMoveOnLand(boolean moveOnLand) {
        this.moveOnLand = moveOnLand;
    }

    @Override
    public double getOccupiedDeceleration() {
        return this.occupiedDecelerationSpeed;
    }

    @Override
    public void setOccupiedDeceleration(double occupiedDeceleration) {
        this.occupiedDecelerationSpeed = occupiedDeceleration;
    }

    @Override
    public double getUnoccupiedDeceleration() {
        return this.unoccupiedDecelerationSpeed;
    }

    @Override
    public void setUnoccupiedDeceleration(double unoccupiedDeceleration) {
        this.unoccupiedDecelerationSpeed = unoccupiedDeceleration;
    }

    @Override
    public void readFromNbt(NBTTagCompound compound) {
        super.readFromNbt(compound);
        if (compound.hasKey(NbtDataUtil.BOAT_MAX_SPEED)) {
            this.maxSpeed = compound.getDouble(NbtDataUtil.BOAT_MAX_SPEED);
        }
        if (compound.hasKey(NbtDataUtil.BOAT_MOVE_ON_LAND)) {
            this.moveOnLand = compound.getBoolean(NbtDataUtil.BOAT_MOVE_ON_LAND);
        }
        if (compound.hasKey(NbtDataUtil.BOAT_OCCUPIED_DECELERATION_SPEED)) {
            this.occupiedDecelerationSpeed = compound.getDouble(NbtDataUtil.BOAT_OCCUPIED_DECELERATION_SPEED);
        }
        if (compound.hasKey(NbtDataUtil.BOAT_UNOCCUPIED_DECELERATION_SPEED)) {
            this.unoccupiedDecelerationSpeed = compound.getDouble(NbtDataUtil.BOAT_UNOCCUPIED_DECELERATION_SPEED);
        }
    }

    @Override
    public void writeToNbt(NBTTagCompound compound) {
        super.writeToNbt(compound);
        compound.setDouble(NbtDataUtil.BOAT_MAX_SPEED, this.maxSpeed);
        compound.setBoolean(NbtDataUtil.BOAT_MOVE_ON_LAND, this.moveOnLand);
        compound.setDouble(NbtDataUtil.BOAT_OCCUPIED_DECELERATION_SPEED, this.occupiedDecelerationSpeed);
        compound.setDouble(NbtDataUtil.BOAT_UNOCCUPIED_DECELERATION_SPEED, this.unoccupiedDecelerationSpeed);
    }
}


text:
		<title>Wisata </title>
		<link href="<?php echo URL; ?>public/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

						   <a href="<?php echo URL;?>home/news">Home

                                                    About

                                  Menu
                                  <a href="<?php echo URL;?>login" class="list-group-item" data-toggle="tooltip" data-placement="top" title="Login User">Login
                                  <a href="<?php echo URL;?>signup" class="list-group-item">Sign Up
                                  <a href="<?php echo URL;?>bukutamu" class="list-group-item">Buku Tamu

                                                                isi

                Copyright : Eticla21.com

redpajama_set_name: RedPajamaGithub


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct impl</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../basic_clock.html#idp55433672" title="Description">
<link rel="prev" href="../basic_clock.html" title="Class template basic_clock">
<link rel="next" href="../constant.html" title="Class template constant">

Struct impl

boost::log::attributes::basic_clock::impl — Attribute factory implementation.

Synopsis

// In header: <boost/log/attributes/clock.hpp>

// Attribute factory implementation.

struct impl : public attribute::impl {

  // public member functions
  attribute_value get_value();
};

Description

impl public member functions

attribute_value get_value();

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Returns:

The actual attribute value. It shall not return empty values (exceptions shall be used to indicate errors).

Copyright © 2007-2013 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


text:
classdef PCA < handle
    %PCA  Principal Component Analysis class
    %
    % The class is used to compute a special basis for a set of vectors.
    % The basis will consist of eigenvectors of the covariance matrix
    % computed from the input set of vectors. The class PCA can also
    % transform vectors to/from the new coordinate space defined by the
    % basis. Usually, in this new coordinate system, each vector from the
    % original set (and any linear combination of such vectors) can be
    % quite accurately approximated by taking its first few components,
    % corresponding to the eigenvectors of the largest eigenvalues of the
    % covariance matrix. Geometrically it means that you compute a
    % projection of the vector to a subspace formed by a few eigenvectors
    % corresponding to the dominant eigenvalues of the covariance matrix.
    % And usually such a projection is very close to the original vector.
    % So, you can represent the original vector from a high-dimensional
    % space with a much shorter vector consisting of the projected vector's
    % coordinates in the subspace. Such a transformation is also known as
    % Karhunen-Loeve Transform, or KLT. See
    % http://en.wikipedia.org/wiki/Principal_component_analysis
    %
    % The following shows a quick example of how to reduce dimensionality
    % of samples from 10 to 3.
    %
    %    Xtrain = randn(100,10);
    %    Xtest  = randn(100,10);
    %    pca = cv.PCA(Xtrain, 'MaxComponents', 3);
    %    Y = pca.project(Xtest);
    %    Xapprox = pca.backProject(Y);
    %
    % See also cv.PCA.PCA
    %

    properties (SetAccess = protected)
        % Object ID
        id
        % Eigenvectors
        eigenvectors
        % Eigenvalues
        eigenvalues
        % Sample mean
        mean
    end

    methods
        function this = PCA(varargin)
            %PCA  PCA constructors
            %
            %    pca = cv.PCA()
            %    pca = cv.PCA(X, 'OptionName', optionValue, ...)
            %    pca = cv.PCA(S)
            %
            % ## Input
            % * __X__ Vectors to be analyzed
            % * __S__ A scalar struct to be imported
            %
            % ## Options
            % * __DataAs__ Data layout option. One of 'row' or 'col'.
            %       default 'row'.
            % * __MaxComponents__ Maximum number of components that PCA
            %       should retain. By default, all the components are
            %       retained.
            % * __Mean__ Optional mean value. By default, the mean is
            %       computed from the data.
            %
            % The constructor creates an empty pca object without an
            % argument. Use pca.compute to analyze data samples. The second
            % form accepts data samples with the same argument to
            % pca.compute. The third form create a new pca object from a
            % scalar struct with 'eigenvectors', 'eigenvalues', and 'mean'
            % fields.
            %
            % See also cv.PCA cv.PCA.compute
            %
            this.id = PCA_(0,'new');
            if nargin==1 && isscalar(varargin{1}) && isstruct(varargin{1})
                s = varargin{1};
                props = intersect(fieldnames(s),properties(this));
                props = setdiff(props,'id');
                for i = 1:numel(props)
                    this.(props{i}) = s.(props{i});
                end
            else
                this.compute(varargin{:});
            end
        end

        function delete(this)
            %DELETE  PCA destructor
            %
            % See also cv.PCA
            %
            PCA_(this.id, 'delete');
        end

        function S = struct(this)
            %STRUCT  Converts to a struct array
            %
            %    S = this.struct
            %    S = struct(this)
            %
            %
            % ## Output
            % * __S__ struct array
            %
            % See also cv.PCA
            %
            S = struct('eigenvectors',{this.eigenvectors},...
                       'eigenvalues', {this.eigenvalues},...
                       'mean',        {this.mean});
        end

        function obj = saveobj(this)
            %SAVEOBJ  Serialization before save
            %
            % See also cv.PCA
            %
            obj = this.struct;
        end

        function compute(this, X, varargin)
            %COMPUTE  Performs Principal Component Analysis of the supplied dataset
            %
            %    pca.compute(X)
            %
            % ## Input
            % * __X__ Vectors to be analyzed
            %
            % ## Options
            % * __DataAs__ Data layout option. One of 'row' or 'col'.
            %       default 'row'.
            % * __MaxComponents__ Maximum number of components that PCA
            %       should retain. By default, all the components are
            %       retained.
            % * __Mean__ Optional mean value. By default, the mean is
            %       computed from the data.
            %
            % The method performs PCA of the supplied dataset. It is safe
            % to reuse the same PCA structure for multiple datasets. That
            % is, if the structure has been previously used with another
            % dataset, the existing internal data is reclaimed and the new
            % eigenvalues, eigenvectors, and mean are allocated and
            % computed.
            %
            % The computed eigenvalues are sorted from the largest to the
            % smallest and the corresponding eigenvectors are stored as
            % pca.eigenvectors rows.
            %
            % See also cv.PCA cv.PCA.project cv.PCA.backProject
            %
            PCA_(this.id, 'compute', X, varargin{:});
            this.eigenvectors = [];
            this.eigenvalues = [];
            this.mean = [];
        end

        function Y = project(this, X)
            %PROJECT  Projects vector(s) to the principal component subspace
            %
            %    Y = pca.project(X)
            %
            % ## Input
            % * __X__ Vectors to be projected
            %
            % ## Output
            % * __Y__ PC coefficients
            %
            % The methods project one or more vectors to the principal
            % component subspace, where each vector projection is
            % represented by coefficients in the principal component basis.
            % The first form of the method returns the matrix that the
            % second form writes to the result. So the first form can be
            % used as a part of expression while the second form can be
            % more efficient in a processing loop.
            %
            % See also cv.PCA cv.PCA.backProject
            %
            Y = PCA_(this.id, 'project', X);
        end

        function X = backProject(this, Y)
            %BACKPROJECT  Reconstructs vectors from their PC projections
            %
            %    X = pca.backProject(Y)
            %
            % ## Input
            % * __Y__ PC coefficients
            %
            % ## Output
            % * __X__ Reconstructed vectors
            %
            % The methods are inverse operations to pca.project. They
            % take PC coordinates of projected vectors and reconstruct the
            % original vectors. Unless all the principal components have
            % been retained, the reconstructed vectors are different from
            % the originals. But typically, the difference is small if the
            % number of components is large enough (but still much smaller
            % than the original vector dimensionality). As a result, PCA is
            % used.
            %
            % See also cv.PCA cv.PCA.project
            %
            X = PCA_(this.id, 'backProject', Y);
        end

        function value = get.eigenvectors(this)
            %GET.EIGENVECTORS
            if isempty(this.eigenvectors)
                this.eigenvectors = PCA_(this.id, 'eigenvectors');
            end
            value = this.eigenvectors;
        end

        function value = get.eigenvalues(this)
            %GET.EIGENVALUES
            if isempty(this.eigenvalues)
                this.eigenvalues = PCA_(this.id, 'eigenvalues');
            end
            value = this.eigenvalues;
        end

        function value = get.mean(this)
            %GET.MEAN
            if isempty(this.mean)
                this.mean = PCA_(this.id, 'mean');
            end
            value = this.mean;
        end
    end

    methods (Static)
        function this = loadobj(obj)
            %LOADOBJ  Deserialization after load
            %
            % See also cv.PCA
            %
            this = cv.PCA(obj);
        end
    end

end


text:
class AddFolderToRevisions < ActiveRecord::Migration[5.0]
  def change
    add_reference :ninetails_revisions, :folder
  end
end


text:
/*
 * Created on 21.07.2006 by leck
 *
 */
package de.devisnik.sliding.impl;

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

import de.devisnik.sliding.IFrame;
import de.devisnik.sliding.IFrameListener;
import de.devisnik.sliding.IHole;
import de.devisnik.sliding.IMove;
import de.devisnik.sliding.IPiece;
import de.devisnik.sliding.MoveFactory;
import de.devisnik.sliding.Point;
import de.devisnik.sliding.ShiftingEvent;

public class Frame implements IFrame {

	public static void main(String[] args) {
		Frame shiftingGame = new Frame(5, 5);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.UP);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.UP);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.LEFT);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.LEFT);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.UP);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.LEFT);
		System.out.println(shiftingGame.toString());
		shiftingGame.moveHole(MoveFactory.DOWN);
		System.out.println(shiftingGame.toString());
	}

	private int itsDimX;
	private int itsDimY;
	private Hole itsHole;
	private Piece[][] itsPieces;

	private List<IFrameListener> itsShiftingGameListeners = new ArrayList<IFrameListener>();

	public Frame(int x, int y) {
		itsDimX = x;
		itsDimY = y;
		createPieces(x, y);
	}

	public void addListener(IFrameListener listener) {
		if (listener == null)
			return;
		itsShiftingGameListeners.add(listener);
	}

	private Piece createPieceAt(int x, int y) {
		return new Piece(x, y, "" + (y * itsDimX + x + 1));
	}

	private void createPieces(int dimX, int dimY) {
		itsPieces = new Piece[dimX][dimY];
		for (int y = 0; y < dimY; y++)
			for (int x = 0; x < dimX; x++)
				itsPieces[x][y] = createPieceAt(x, y);
		itsHole = new Hole(dimX - 1, dimY - 1, " ");
		itsPieces[dimX - 1][dimY - 1] = itsHole;
	}

	private void exchange(Point first, Point second) {
		Piece buffer = itsPieces[first.x][first.y];
		putPieceAt(itsPieces[second.x][second.y], first.x, first.y);
		putPieceAt(buffer, second.x, second.y);
	}

	public boolean execute(IMove move) {
		ShiftingEvent[] event = moveHole(move);
//		fireShiftingEvent(event[1]);
		fireSwap(event[0].getPiece(), event[1].getPiece());
		return true;
	}

	protected final void fireSwap(IPiece left, IPiece right) {
		for (IFrameListener listener : itsShiftingGameListeners)
			listener.handleSwap(left, right);
	}

	protected final void fireShiftingEvents(final ShiftingEvent[] events) {
		for (IFrameListener listener : itsShiftingGameListeners)
			listener.handleShifting(events);
	}

	public IHole getHole() {
		return itsHole;
	}

	public IPiece getPieceAt(int posX, int posY) {
		return itsPieces[posX][posY];
	}

	public Point getSize() {
		return new Point(itsDimX, itsDimY);
	}

	protected final ShiftingEvent[] moveHole(IMove move) {
		Point holePosition = getHole().getPosition().copy();
		Point target = Point.sum(holePosition, move.getX(), move.getY());
		IPiece piece = getPieceAt(target.x, target.y);
		exchange(holePosition, target);
		Point oldPosition = holePosition;
		return new ShiftingEvent[] { new ShiftingEvent(piece, target, oldPosition),
				new ShiftingEvent(itsHole, oldPosition, target) };
	}

	protected final void putPieceAt(Piece piece, int x, int y) {
		itsPieces[x][y] = piece;
		piece.setPosition(x, y);
	}

	public void removeListener(IFrameListener listener) {
		itsShiftingGameListeners.remove(listener);
	}

	@Override
	public String toString() {
		StringBuffer stringBuffer = new StringBuffer();
		for (int y = 0; y < itsDimY; y++) {
			for (int x = 0; x < itsDimX; x++) {
				String label = itsPieces[x][y].getLabel();
				stringBuffer.append(label);
				stringBuffer.append(" ");
			}
			stringBuffer.append("\n");
		}
		return stringBuffer.toString();
	}

	public Iterator<IPiece> iterator() {
		return new PieceIterator(itsPieces);
	}
}


text:
using System;
using GgpGrpc;
using GgpGrpc.Cloud.Interceptors;
using Grpc.Core;
using Metrics.Shared;
using YetiCommon;

namespace YetiVSI.Metrics
{
    public static class ExceptionHelper
    {
        public static DeveloperLogEvent RecordException(Exception e)
        {
            if (e is RpcException)
            {
                return RecordRpcException((RpcException) e);
            }

            if (e is ProcessException)
            {
                return RecordProcessException((ProcessException)e);
            }

            var statusCode = ClassifyException(e);
            if (statusCode != DeveloperEventStatus.Types.Code.UnknownStatus)
            {
                return new DeveloperLogEvent {StatusCode = statusCode};
            }

            if (e.InnerException != null)
            {
                return RecordException(e.InnerException);
            }

            return new DeveloperLogEvent
            {
                StatusCode = DeveloperEventStatus.Types.Code.InternalError
            };
        }

        static DeveloperLogEvent RecordRpcException(RpcException e)
        {
            var logEvent = new DeveloperLogEvent();
            logEvent.StatusCode = ClassifyGrpcStatus(e.Status);

            var serviceName = e.Data[ErrorData.ServiceNameKey] as string;
            var methodName = e.Data[ErrorData.MethodNameKey] as string;
            var details =
                new GrpcServiceCallDetails
                {
                    Status = e.Status
                };
            if (!string.IsNullOrEmpty(serviceName))
            {
                details.ServiceName = serviceName;
            }
            if (!string.IsNullOrEmpty(methodName))
            {
                details.ServiceMethod = methodName;
            }
            logEvent.GrpcErrorDetails = details;
            return logEvent;
        }

        static DeveloperLogEvent RecordProcessException(ProcessException e)
        {
            var logEvent = new DeveloperLogEvent();
            if (e is ProcessExecutionException)
            {
                logEvent.StatusCode = DeveloperEventStatus.Types.Code.ExternalToolFailure;
                var externalError =
                    new DeveloperLogEvent.Types.ExternalToolError
                    {
                        ExitCode = ((ProcessExecutionException) e).ExitCode
                    };
                logEvent.ExternalToolError = externalError;
            }
            else
            {
                logEvent.StatusCode = DeveloperEventStatus.Types.Code.ExternalToolUnavailable;
            }
            return logEvent;
        }

        static DeveloperEventStatus.Types.Code ClassifyException(Exception e)
        {
            if (e is IInputError)
            {
                return DeveloperEventStatus.Types.Code.InvalidInput;
            }
            if (e is IConfigurationError || e is IGgpConfigurationError)
            {
                return DeveloperEventStatus.Types.Code.InvalidConfiguration;
            }
            if (e is IInvalidStateError)
            {
                return DeveloperEventStatus.Types.Code.InvalidObjectState;
            }
            if (e is OperationCanceledException)
            {
                return DeveloperEventStatus.Types.Code.CanceledSubTask;
            }
            if (e is TimeoutException)
            {
                return DeveloperEventStatus.Types.Code.Timeout;
            }
            if (e is IGameLaunchFailError)
            {
                return DeveloperEventStatus.Types.Code.GameLaunchFailure;
            }
            return DeveloperEventStatus.Types.Code.UnknownStatus;
        }

        static DeveloperEventStatus.Types.Code ClassifyGrpcStatus(Status status)
        {
            switch (status.StatusCode)
            {
                // Errors that are generated by API FE, either directly or from a backend.
                // They will be further classified by the exact status code during processing.
                case StatusCode.InvalidArgument:
                case StatusCode.DeadlineExceeded:
                case StatusCode.NotFound:
                case StatusCode.AlreadyExists:
                case StatusCode.PermissionDenied:
                case StatusCode.ResourceExhausted:
                case StatusCode.FailedPrecondition:
                case StatusCode.Aborted:
                case StatusCode.OutOfRange:
                case StatusCode.Unimplemented:
                case StatusCode.Internal:
                case StatusCode.DataLoss:
                    return DeveloperEventStatus.Types.Code.CommandFailure;

                // Unauthenticated is generated on the server, before API FE.
                case StatusCode.Unauthenticated:
                    return DeveloperEventStatus.Types.Code.AuthorizationFailure;

                // Unavailable is generated on the client on connection failure (network problem).
                case StatusCode.Unavailable:
                    return DeveloperEventStatus.Types.Code.ConnectionFailure;

                // Errors that imply we did something wrong locally.
                case StatusCode.Cancelled:
                case StatusCode.Unknown:
                    return DeveloperEventStatus.Types.Code.InternalError;
            }
            return DeveloperEventStatus.Types.Code.InternalError;
        }
    }
}


text:
import express from 'express';
import authController from '../controllers/auth';
import verifyRecoveryLink from '../middlewares/verifyRecoveryLink';

const router = express.Router();
router.route('/v1/user/signup')
/**
 * @swagger
 * /api/v1/user/signup:
 *   post:
 *     tags:
 *       - Authentication
 *     description: Register a new user
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: fullname
 *         description: User full name
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: username
 *         description: Username of the user
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: email
 *         description: User email
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: password
 *         description: User password
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: confirmPassword
 *         description: User confirm password
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: mobile
 *         description: User mobile number
 *         in: formData
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Token of authenticated user
 *         schema:
 *           properties:
 *             token:
 *               type: string
 */

    .post(authController.signup);
router.route('/v1/user/signin')
/**
 * @swagger
 * /api/v1/user/signin:
 *   post:
 *     tags:
 *       - Authentication
 *     description: Login a user
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: username
 *         description: Username of the user
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: password
 *         description: Password of the user
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Token of authenticated user
 *         schema:
 *           properties:
 *             token:
 *               type: string
 */
    .post(authController.signin);
router.route('/v1/user/recover-password')
/**
 * @swagger
 * /api/v1/user/recover-password:
 *   post:
 *     tags:
 *       - Authentication
 *     description: Recover password of a user
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: email
 *         description: Valid email of the user
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Message for recovery sent email
 *         schema:
 *           properties:
 *             message:
 *               type: string
 */
  .post(authController.passwordRecovery);
router.route('/v1/user/reset-password')
/**
 * @swagger
 * /api/v1/user/reset-password:
 *   post:
 *     tags:
 *       - Authentication
 *     description: Reset user password
 *     produces:
 *       - application/json
 *     parameters:
 *       - name: password
 *         description: New password of the user
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *       - name: confirmPassword
 *         description: Confirm new password of the user
 *         in: formData
 *         required: true
 *         schema:
 *           type: string
 *     responses:
 *       200:
 *         description: Password reset message
 *         schema:
 *           properties:
 *             message:
 *               type: string
 */
  .post(verifyRecoveryLink, authController.resetPasswordPost);
export default router;


text:
import requests
from models import DataFetchException

class DataFetcher(object):

    def __init__(self, data_url):
        self.data_url = data_url

    def get_studies_text(self):
        r = requests.get(self.data_url)

        if r.status_code != 200:
            raise DataFetchException(r.status_code, r.text)
        else:
            response_json = r.json()
            return [study["data"] for study in response_json]


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test.Framework.Data
{
    public interface IOrm : IDisposable
    {
        IDbConnection GetConnection();

        bool Execute(SqlDbCommand query);

        Task<bool> ExecuteAsync(SqlDbCommand query);

        bool Execute(IList<SqlDbCommand> queries);

        Task<bool> ExecuteAsync(IList<SqlDbCommand> queries);

        IEnumerable<T> Select<T>(SqlDbCommand query, ISelectable<T> traits = null)
            where T : class, new();

        Task<IEnumerable<T>> SelectAsync<T>(SqlDbCommand query, ISelectable<T> traits = null)
            where T : class, new();

        IEnumerable<T> Select<T>(SqlDbCommand query, Func<DataReader, T> readMapper)
            where T : class, new();

        Task<IEnumerable<T>> SelectAsync<T>(SqlDbCommand query, Func<DataReader, T> readMapper)
            where T : class, new();
    }
}


text:
Assume this is a real report...
Should after case.json


text:
<?php

/* forms/fields/hidden/hidden.html.twig */
class __TwigTemplate_18a05787e82b3a489838e822d7f856b329784ebcddb9fb2f4e1f063c8837c7ab extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $context["value"] = (((null === (isset($context["value"]) ? $context["value"] : null))) ? ((($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "evaluate", array())) ? ($this->env->getExtension('Grav\Common\Twig\TwigExtension')->evaluateFunc($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "default", array()))) : ($this->getAttribute((isset($context["field"]) ? $context["field"] : null), "default", array())))) : ((isset($context["value"]) ? $context["value"] : null)));
        // line 2
        echo "
<input data-grav-field=\"hidden\" data-grav-disabled=\"false\" type=\"hidden\" class=\"input\" name=\"";
        // line 3
        echo twig_escape_filter($this->env, $this->env->getExtension('Grav\Common\Twig\TwigExtension')->fieldNameFilter(((isset($context["scope"]) ? $context["scope"] : null) . $this->getAttribute((isset($context["field"]) ? $context["field"] : null), "name", array()))), "html", null, true);
        echo "\" value=\"";
        echo twig_escape_filter($this->env, twig_join_filter((isset($context["value"]) ? $context["value"] : null), ", "), "html", null, true);
        echo "\" />
";
    }

    public function getTemplateName()
    {
        return "forms/fields/hidden/hidden.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  24 => 3,  21 => 2,  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("{% set value = (value is null ? (field.evaluate ? evaluate(field.default) : field.default) : value) %}

<input data-grav-field=\"hidden\" data-grav-disabled=\"false\" type=\"hidden\" class=\"input\" name=\"{{ (scope ~ field.name)|fieldName }}\" value=\"{{ value|join(', ') }}\" />
", "forms/fields/hidden/hidden.html.twig", "/Users/emilkarlsson/Code/lundbergsab/user/plugins/form/templates/forms/fields/hidden/hidden.html.twig");
    }
}


text: <!DOCTYPE html>


text:
echo ""
echo "Starting Karma Server (http://karma-runner.github.io)"
echo $BASE_DIR
echo "-------------------------------------------------------------------"

karma start ../config/karma-e2e.conf.js $*


text:
package com.fqc;

import org.junit.Before;
import org.junit.Test;

/**
 * Created by fqc on 3/10/17.
 */
public class HelloLuceneTest {
    HelloLucene test;

    @Before
    public void setUp() throws Exception {
        test = new HelloLucene();
    }

    @Test
    public void testIndexFiles() {
        test.indexFiles("/usr/local/data/indexFiles", "/usr/local/data/example");
    }

    @Test
    public void testSearcher() {
        test.searcher("/usr/local/data/indexFiles", "fqc");
    }
}


text:
![Responsive Layouts for Email](http://internations.github.com/antwort/images/responsive-graphic-small.png "Responsive Layouts for Email")

Antwort offers responsive layouts for Email that both fits _and_ adapts to client widths. Don't underwhelm desktop users with single column layouts that work for mobile. Antwort offers columns on desktop that automatically become rows on mobile.

Author: Julie Ng ([@jng5](http://twitter.com/jng5))
Date: January 2013
Version: 0.1.2

## Features
* Works on mobile: Mail on iOS and Email on Android.
* Works in major clients like Hotmail, Gmail, Yahoo! and AOL.
* Even works in Outlook (2000+).
* Bulletproof layouts: made with dynamic content in mind.
* Minimalist in design for maximum customizability.
* [More details on Antwort site »](http://internations.github.com/antwort/)

## How to use
1. [Read tips and coding style guidelines](http://internations.github.com/antwort).
2. Test with [Litmus](https://litmus.com/).
3. Send!

## Tools and Resources
* [Campaign Monitor's Guide to CSS Support](http://www.campaignmonitor.com/css) - reference table for CSS support in major email clients.
* [CSS Inliner Tool](http://beaker.mailchimp.com/inline-css) from MailChimp.
* [Premailer](http://premailer.dialect.ca/) another CSS inline tool. Also generates text version.
* [Litmus](http://www.litmus.com/) for testing Emails across clients.

## Changelog

### 0.1.2
* Fixed issue #8 - headlines no longer centered in Outlook.com and older Outlook.
* Fixed issue #7 - moved padding overrides to parent `<td>` in mobile styles.

### 0.1.1
* Fixed column margin issue after [Hotmail/Outlook dropped margin support](https://litmus.com/blog/hotmail-and-outlook-com-drop-support-for-margin).
* Issue #5 fixed - Outlook.com parses HTML tags in comments.
* Issue #3 fixed - control characters removed from template.
* Added screenshots of current version from Litmus test.

### 0.1.0
* Hello open source world.

## Demo
* Download and resize your browser window to see its responsiveness.
* [View demo screenshots](https://github.com/InterNations/antwort/blob/gh-pages/screenshots-litmus/) to see *how it looks* in various Email clients, including Android 2.3, Outlook 2000, Apple Mail, etc.

[!["Email Client Compatibility Preview"](http://internations.github.com/antwort/images/compatability-preview.png "Email Client Compatibility Preview")](https://github.com/InterNations/antwort/blob/gh-pages/screenshots-litmus/)

*Screenshots generated by [Litmus](http://www.litmus.com/). Last updated 26 March 2013 (v0.1.1)*

## License
Antwort is provided under the MIT License - see LICENSE.md for full details.


text:
import $ from 'jquery';
import { config } from 'grav-config';
import request from '../utils/request';

class Packages {

    static getBackToList(type) {
        window.location.href = `${config.base_url_relative}/${type}s`;
    }

    static addDependencyToList(type, dependency, slug = '') {
        let container = $('.package-dependencies-container');
        let text = `${dependency} <a href="#" class="button" data-dependency-slug="${dependency}" data-${type}-action="remove-dependency-package">Remove</a>`;

        if (slug) {
            text += ` (was needed by ${slug})`;
        }

        container.append(`<li>${text}</li>`);
    }

    addDependenciesToList(dependencies, slug = '') {
        dependencies.forEach((dependency) => {
            Packages.addDependencyToList('plugin', dependency, slug);
        });
    }

    static getTaskUrl(type, task) {
        let url = `${config.base_url_relative}`;
        url += `/${type}s.json`;
        url += `/task${config.param_sep}${task}`;
        return url;
    }

    static getRemovePackageUrl(type) {
        return `${Packages.getTaskUrl(type, 'removePackage')}`;
    }

    static getGetPackagesDependenciesUrl(type) {
        return `${Packages.getTaskUrl(type, 'getPackagesDependencies')}`;
    }

    static getInstallDependenciesOfPackagesUrl(type) {
        return `${Packages.getTaskUrl(type, 'installDependenciesOfPackages')}`;
    }

    static getInstallPackageUrl(type) {
        return `${Packages.getTaskUrl(type, 'installPackage')}`;
    }

    removePackage(type, slug) {
        let url = Packages.getRemovePackageUrl(type);

        request(url, {
            method: 'post',
            body: {
                package: slug
            }
        }, (response) => {
            if (response.status === 'success') {
                $('.remove-package-confirm').addClass('hidden');

                if (response.dependencies.length > 0) {
                    this.addDependenciesToList(response.dependencies);
                    $('.remove-package-dependencies').removeClass('hidden');
                } else {
                    $('.remove-package-done').removeClass('hidden');
                }

                // The package was removed. When the modal closes, move to the packages list
                $(document).on('closing', '[data-remodal-id="remove-package"]', () => {
                    Packages.getBackToList(type);
                });
            } else {
                $('.remove-package-confirm').addClass('hidden');
                $('.remove-package-error').removeClass('hidden');
            }
        });
    }

    removeDependency(type, slug, button) {
        let url = Packages.getRemovePackageUrl(type);

        request(url, {
            method: 'post',
            body: {
                package: slug
            }
        }, (response) => {
            if (response.status === 'success') {
                button.removeClass('button');
                button.replaceWith($('Removed successfully'));

                if (response.dependencies.length > 0) {
                    this.addDependenciesToList(response.dependencies, slug);
                }
            }
        });
    }

    static addNeededDependencyToList(type, dependency) {
        $('.install-dependencies-package-container .type-' + type).removeClass('hidden');
        let list = $('.install-dependencies-package-container .type-' + type + ' ul');
        let text = `${dependency}`;
        list.append(`<li>${text}</li>`);
    }

    getPackagesDependencies(type, slugs, finishedLoadingCallback) {
        let url = Packages.getGetPackagesDependenciesUrl(type);

        request(url, {
            method: 'post',
            body: {
                packages: slugs
            }
        }, (response) => {

            finishedLoadingCallback();

            if (response.status === 'success') {
                if (response.dependencies) {
                    let hasDependencies = false;
                    for (var dependency in response.dependencies) {
                        if (response.dependencies.hasOwnProperty(dependency)) {
                            hasDependencies = true;
                            let dependencyName = dependency;
                            let dependencyType = response.dependencies[dependency];

                            Packages.addNeededDependencyToList(dependencyType, dependencyName);
                        }
                    }

                    if (hasDependencies) {
                        $('[data-packages-modal] .install-dependencies-package-container').removeClass('hidden');
                    } else {
                        $('[data-packages-modal] .install-package-container').removeClass('hidden');
                    }
                } else {
                    $('[data-packages-modal] .install-package-container').removeClass('hidden');
                }
            } else {
                $('[data-packages-modal] .install-package-error').removeClass('hidden');
            }
        });
    }

    installDependenciesOfPackages(type, slugs, callbackSuccess, callbackError) {
        let url = Packages.getInstallDependenciesOfPackagesUrl(type);

        request(url, {
            method: 'post',
            body: {
                packages: slugs
            }
        }, callbackSuccess);
    }

    installPackages(type, slugs, callbackSuccess) {
        let url = Packages.getInstallPackageUrl(type);

        slugs.forEach((slug) => {
            request(url, {
                method: 'post',
                body: {
                    package: slug,
                    type: type
                }
            }, callbackSuccess);
        });

    }

    static getSlugsFromEvent(event) {
        let slugs = '';
        if ($(event.target).is('[data-packages-slugs]')) {
            slugs = $(event.target).attr('data-packages-slugs');
        } else {
            slugs = $(event.target).parent('[data-packages-slugs]').attr('data-packages-slugs');
        }

        if (typeof slugs === 'undefined') {
            return null;
        }

        slugs = slugs.split(',');
        return typeof slugs === 'string' ? [slugs] : slugs;
    }

    handleGettingPackageDependencies(type, event) {
        let slugs = Packages.getSlugsFromEvent(event);

        if (!slugs) {
            alert('No slug set');
            return;
        }

        // Cleanup
        $('.packages-names-list').html('');
        $('.install-dependencies-package-container li').remove();

        slugs.forEach((slug) => {
            $('.packages-names-list').append(`<li>${slug}</li>`);
        });

        event.preventDefault();
        event.stopPropagation();

        // Restore original state
        $('[data-packages-modal] .loading').removeClass('hidden');
        $('[data-packages-modal] .install-dependencies-package-container').addClass('hidden');
        $('[data-packages-modal] .install-package-container').addClass('hidden');
        $('[data-packages-modal] .installing-dependencies').addClass('hidden');
        $('[data-packages-modal] .installing-package').addClass('hidden');
        $('[data-packages-modal] .installation-complete').addClass('hidden');
        $('[data-packages-modal] .install-package-error').addClass('hidden');

        this.getPackagesDependencies(type, slugs, () => {
            let slugs_string = slugs.join();
            $(`[data-packages-modal] [data-${type}-action="install-dependencies-and-package"]`).attr('data-packages-slugs', slugs_string);
            $(`[data-packages-modal] [data-${type}-action="install-package"]`).attr('data-packages-slugs', slugs_string);
            $('[data-packages-modal] .loading').addClass('hidden');
        });
    }

    handleInstallingDependenciesAndPackage(type, event) {
        let slugs = Packages.getSlugsFromEvent(event);
        event.preventDefault();
        event.stopPropagation();

        $('[data-packages-modal] .install-dependencies-package-container').addClass('hidden');
        $('[data-packages-modal] .installing-dependencies').removeClass('hidden');

        this.installDependenciesOfPackages(type, slugs, () => {
            $('[data-packages-modal] .installing-dependencies').addClass('hidden');
            $('[data-packages-modal] .installing-package').removeClass('hidden');
            this.installPackages(type, slugs, () => {
                $('[data-packages-modal] .installing-package').addClass('hidden');
                $('[data-packages-modal] .installation-complete').removeClass('hidden');

                if (slugs.length === 1) {
                    window.location.href = `${config.base_url_relative}/${type}s/${slugs[0]}`;
                } else {
                    window.location.href = `${config.base_url_relative}/${type}s`;
                }

            });
        });
    }

    handleInstallingPackage(type, event) {
        let slugs = Packages.getSlugsFromEvent(event);
        event.preventDefault();
        event.stopPropagation();

        $('[data-packages-modal] .install-package-container').addClass('hidden');
        $('[data-packages-modal] .installing-package').removeClass('hidden');

        this.installPackages(type, slugs, () => {
            $('[data-packages-modal] .installing-package').addClass('hidden');
            $('[data-packages-modal] .installation-complete').removeClass('hidden');

            if (slugs.length === 1) {
                window.location.href = `${config.base_url_relative}/${type}s/${slugs[0]}`;
            } else {
                window.location.href = `${config.base_url_relative}/${type}s`;
            }
        });
    }

    handleRemovingPackage(type, event) {
        let slug = $(event.target).attr('data-packages-slugs');
        event.preventDefault();
        event.stopPropagation();

        this.removePackage(type, slug);
    }

    handleRemovingDependency(type, event) {
        let slug = $(event.target).attr('data-dependency-slug');
        let button = $(event.target);
        event.preventDefault();
        event.stopPropagation();

        this.removeDependency(type, slug, button);
    }

}

export default new Packages();


text:
<bill session="110" type="hc" number="308" updated="2009-01-08T16:05:41-05:00">
	<status><vote2 date="1210132800" datetime="2008-05-07" where="s" result="pass" how="by Unanimous Consent" roll=""/></status>

	<introduced date="1204606800" datetime="2008-03-04"/>
	<titles>
		<title type="official" as="introduced">Authorizing the use of the Capitol Grounds for the National Peace Officers' Memorial Service.</title>
	</titles>
	<sponsor id="400295"/>
	<cosponsors>
		<cosponsor id="400098" joined="2008-03-04"/>
		<cosponsor id="400158" joined="2008-03-04"/>
		<cosponsor id="400189" joined="2008-03-04"/>
		<cosponsor id="400415" joined="2008-03-04"/>
		<cosponsor id="400283" joined="2008-03-04"/>
		<cosponsor id="400090" joined="2008-03-04"/>
		<cosponsor id="400438" joined="2008-03-04"/>
		<cosponsor id="400435" joined="2008-03-04"/>
	</cosponsors>
	<actions>
		<action date="1204606800" datetime="2008-03-04"><text>Referred to the House Committee on Transportation and Infrastructure.</text></action>
		<action date="1204693200" datetime="2008-03-05"><text>Referred to the Subcommittee on Economic Development, Public Buildings and Emergency Management.</text></action>
		<action date="1209573060" datetime="2008-04-30T13:31:00-04:00"><text>Mr. Carney moved to suspend the rules and agree to the resolution.</text></action>
		<action date="1209573060" datetime="2008-04-30T13:31:00-04:00"><text>Considered under suspension of the rules.</text><reference label="consideration" ref="CR H2885-2886"/></action>
		<action date="1209573060" datetime="2008-04-30T13:31:00-04:00"><text>DEBATE - The House proceeded with forty minutes of debate on H. Con. Res. 308.</text></action>
		<action date="1209573360" datetime="2008-04-30T13:36:00-04:00"><text>At the conclusion of debate, the Yeas and Nays were demanded and ordered. Pursuant to the provisions of clause 8, rule XX, the Chair announced that further proceedings on the motion would be postponed.</text></action>
		<action date="1209700680" datetime="2008-05-01T12:58:00-04:00"><text>Considered as unfinished business.</text><reference label="consideration" ref="CR H2981-2982"/></action>
		<vote date="1209657840" how="roll" roll="237" datetime="2008-05-01T13:04:00-04:00" where="h" type="vote" suspension="1" result="pass" ><text>On motion to suspend the rules and agree to the resolution Agreed to by the Yeas and Nays: (2/3 required): 412 - 0 (Roll no. 237). (text: CR 5/1/2008 H2885)</text></vote>
		<action date="1209700800" datetime="2008-05-02"><text>Received in the Senate.</text></action>
		<vote date="1210132800" how="by Unanimous Consent" datetime="2008-05-07" where="s" type="vote2" result="pass" ><text>Resolution agreed to in Senate without amendment by Unanimous Consent.</text><reference label="consideration" ref="CR S3930"/><reference label="text as passed Senate" ref="CR S3730"/></vote>
		<action date="1210219200" datetime="2008-05-08"><text>Message on Senate action sent to the House.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	5/7/2008--Passed Senate without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.) Permits the Grand Lodge of the Fraternal Order of Police and its auxiliary to sponsor a free public event, the 27th annual National Peace Officers' Memorial Service, on the Capitol grounds on May 15, 2008, to honor the law enforcement officers who died in the line of duty during 2007.<br/>
	</summary>
</bill>


text:
import os
import hashlib

from django.contrib.auth import models as auth_models
from django.core.files.base import ContentFile
from django.core import urlresolvers
from django.db import models
from django.utils.translation import ugettext_lazy as _

from django.conf import settings
from filer.models.foldermodels import Folder
from filer.models import mixins

from filer.fields.multistorage_file import MultiStorageFileField

class FileManager(models.Manager):
    def find_all_duplicates(self):
        r = {}
        for file in self.all():
            if file.sha1:
                q = self.filter(sha1=file.sha1)
                if len(q) > 1:
                    r[file.sha1] = [i.subtype() for i in q]
        return r
    def find_duplicates(self, file):
        return [i.subtype() for i in self.exclude(pk=file.pk).filter(sha1=file.sha1)]

class File(models.Model, mixins.IconsMixin):
    file_type = 'File'
    _icon = "file"
    folder = models.ForeignKey(Folder, related_name='all_files', null=True, blank=True)
    file = MultiStorageFileField(null=True, blank=True, max_length=255)
    _file_type_plugin_name = models.CharField("file_type_plugin_name", max_length=128, null=True, blank=True, editable=False)
    _file_size = models.IntegerField(null=True, blank=True)

    sha1 = models.CharField(max_length=40, blank=True, default='')

    has_all_mandatory_data = models.BooleanField(default=False, editable=False)

    original_filename = models.CharField(max_length=255, blank=True, null=True)
    name = models.CharField(max_length=255, null=True, blank=True, verbose_name=_('name'))
    description = models.TextField(null=True, blank=True, verbose_name=_('description'))

    owner = models.ForeignKey(auth_models.User, related_name='owned_%(class)ss', null=True, blank=True, verbose_name=_('owner'))

    uploaded_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    is_public = models.BooleanField(default=False)

    objects = FileManager()

    def __init__(self, *args, **kwargs):
        super(File, self).__init__(*args, **kwargs)
        self._old_is_public = self.is_public

    def _move_file(self):
        """
        Move the file from src to dst.
        """
        src_file_name = self.file.name
        dst_file_name = self._meta.get_field('file').generate_filename(self, self.original_filename)

        if self.is_public:
            src_storage = self.file.storages['private']
            dst_storage = self.file.storages['public']
        else:
            src_storage = self.file.storages['public']
            dst_storage = self.file.storages['private']

        # delete the thumbnail
        # We are toggling the is_public to make sure that easy_thumbnails can
        # delete the thumbnails
        self.is_public = not self.is_public
        self.file.delete_thumbnails()
        self.is_public = not self.is_public
        # This is needed because most of the remote File Storage backend do not
        # open the file.
        src_file = src_storage.open(src_file_name)
        src_file.open()
        self.file = dst_storage.save(dst_file_name, ContentFile(src_file.read()))
        src_storage.delete(src_file_name)

    def generate_sha1(self):
        sha = hashlib.sha1()
        self.file.seek(0)
        sha.update(self.file.read())
        self.sha1 = sha.hexdigest()

    def save(self, *args, **kwargs):
        # check if this is a subclass of "File" or not and set
        # _file_type_plugin_name
        if self.__class__ == File:
            # what should we do now?
            # maybe this has a subclass, but is being saved as a File instance
            # anyway. do we need to go check all possible subclasses?
            pass
        elif issubclass(self.__class__, File):
            self._file_type_plugin_name = self.__class__.__name__
        # cache the file size
        try:
            self._file_size = self.file.size
        except:
            pass
        if self._old_is_public != self.is_public and self.pk:
            self._move_file()
            self._old_is_public = self.is_public
        try:
            self.generate_sha1()
        except Exception, e:
            print e, type(3)
        super(File, self).save(*args, **kwargs)

    @property
    def label(self):
        if self.name in ['', None]:
            text = self.original_filename or 'unnamed file'
        else:
            text = self.name
        text = u"%s" % (text,)
        return text

    def has_edit_permission(self, request):
        return self.has_generic_permission(request, 'edit')
    def has_read_permission(self, request):
        return self.has_generic_permission(request, 'read')
    def has_add_children_permission(self, request):
        return self.has_generic_permission(request, 'add_children')
    def has_generic_permission(self, request, type):
        """
        Return true if the current user has permission on this
        image. Return the string 'ALL' if the user has all rights.
        """
        user = request.user
        if not user.is_authenticated():# or not user.is_staff:
            return False
        elif user.is_superuser:
            return True
        elif user == self.owner:
            return True
        elif self.folder:
            return self.folder.has_generic_permission(request, type)
        else:
            return False

    def __unicode__(self):
        if self.name in ('', None):
            text = u"%s" % (self.original_filename,)
        else:
            text = u"%s" % (self.name,)
        return text

    def subtype(self):
        #print "get subtype"
        if not self._file_type_plugin_name:
            r = self
        else:
            try:
                r = getattr(self, self._file_type_plugin_name.lower())
            except Exception, e:
                #print e
                r = self
        #print u"get subtype: %s %s" % (r, self._file_type_plugin_name)
        return r
    def get_admin_url_path(self):
        return urlresolvers.reverse('admin:filer_file_change', args=(self.id,))

    @property
    def url(self):
        '''
        to make the model behave like a file field
        '''
        try:
            r = self.file.url
        except:
            r = ''
        return r

    @property
    def path(self):
        try:
            return self.file.path
        except:
            return ""
    @property
    def size(self):
        return self._file_size or 0
    @property
    def extension(self):
        filetype = os.path.splitext(self.file.name)[1].lower()
        if len(filetype)>0:
            filetype = filetype[1:]
        return filetype

    @property
    def logical_folder(self):
        """
        if this file is not in a specific folder return the Special "unfiled"
        Folder object
        """
        if not self.folder:
            from filer.models.virtualitems import UnfiledImages
            return UnfiledImages()
        else:
            return self.folder
    @property
    def logical_path(self):
        """
        Gets logical path of the folder in the tree structure.
        Used to generate breadcrumbs
        """
        folder_path = []
        if self.folder:
            folder_path.extend(self.folder.get_ancestors())
        folder_path.append(self.logical_folder)
        return folder_path
    @property
    def duplicates(self):
        return File.objects.find_duplicates(self)

    class Meta:
        app_label = 'filer'
        verbose_name = _('file')
        verbose_name_plural = _('files')


text:
{{ msg('msgCampaign.messageCampaigns')}}

            {{error}}

            {{msg('msgCampaign.campaign.Name')}}
            {{msg('msgCampaign.campaign.type')}}
            {{msg('msgCampaign.actions')}}

            {{campaign.name}}
            {{campaign.type}}


text:
package com.intellij.debugger.ui.breakpoints;

import com.intellij.debugger.InstanceFilter;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.xdebugger.impl.XDebuggerHistoryManager;
import com.intellij.xdebugger.impl.breakpoints.XBreakpointBase;
import com.intellij.xdebugger.impl.breakpoints.ui.XLightBreakpointPropertiesPanel;
import com.sun.jdi.event.LocatableEvent;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

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

/*
 * Not used any more, since move to xBreakpoints
 */
public class FilteredRequestorImpl implements JDOMExternalizable, FilteredRequestor {

  public String  SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
  public boolean  SUSPEND = true;

  public boolean COUNT_FILTER_ENABLED     = false;
  public int COUNT_FILTER = 0;

  public boolean CONDITION_ENABLED        = false;
  private TextWithImports myCondition;

  public boolean CLASS_FILTERS_ENABLED    = false;
  private ClassFilter[] myClassFilters          = ClassFilter.EMPTY_ARRAY;
  private ClassFilter[] myClassExclusionFilters = ClassFilter.EMPTY_ARRAY;

  public boolean INSTANCE_FILTERS_ENABLED = false;
  private InstanceFilter[] myInstanceFilters  = InstanceFilter.EMPTY_ARRAY;

  @NonNls private static final String FILTER_OPTION_NAME = "filter";
  @NonNls private static final String EXCLUSION_FILTER_OPTION_NAME = "exclusion_filter";
  @NonNls private static final String INSTANCE_ID_OPTION_NAME = "instance_id";
  @NonNls private static final String CONDITION_OPTION_NAME = "CONDITION";
  protected final Project myProject;

  public FilteredRequestorImpl(@NotNull Project project) {
    myProject = project;
    myCondition = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "");
  }

  public InstanceFilter[] getInstanceFilters() {
    return myInstanceFilters;
  }

  public void setInstanceFilters(InstanceFilter[] instanceFilters) {
    myInstanceFilters = instanceFilters != null? instanceFilters : InstanceFilter.EMPTY_ARRAY;
  }

  public String getSuspendPolicy() {
    return SUSPEND? SUSPEND_POLICY : DebuggerSettings.SUSPEND_NONE;
  }

  public final ClassFilter[] getClassFilters() {
    return myClassFilters;
  }

  public final void setClassFilters(ClassFilter[] classFilters) {
    myClassFilters = classFilters != null? classFilters : ClassFilter.EMPTY_ARRAY;
  }

  public ClassFilter[] getClassExclusionFilters() {
    return myClassExclusionFilters;
  }

  public void setClassExclusionFilters(ClassFilter[] classExclusionFilters) {
    myClassExclusionFilters = classExclusionFilters != null? classExclusionFilters : ClassFilter.EMPTY_ARRAY;
  }

  public void readTo(Element parentNode, Breakpoint breakpoint) throws InvalidDataException {
    readExternal(parentNode);
    if (SUSPEND) {
      breakpoint.setSuspendPolicy(SUSPEND_POLICY);
    }
    else {
      breakpoint.setSuspendPolicy(DebuggerSettings.SUSPEND_NONE);
    }

    breakpoint.setCountFilterEnabled(COUNT_FILTER_ENABLED);
    breakpoint.setCountFilter(COUNT_FILTER);

    breakpoint.setCondition(myCondition);
    ((XBreakpointBase)breakpoint.myXBreakpoint).setConditionEnabled(CONDITION_ENABLED);
    if (myCondition != null && !myCondition.isEmpty()) {
      XDebuggerHistoryManager.getInstance(myProject).addRecentExpression(XLightBreakpointPropertiesPanel.CONDITION_HISTORY_ID, TextWithImportsImpl.toXExpression(myCondition));
    }

    breakpoint.setClassFiltersEnabled(CLASS_FILTERS_ENABLED);
    breakpoint.setClassFilters(getClassFilters());
    breakpoint.setClassExclusionFilters(getClassExclusionFilters());

    breakpoint.setInstanceFiltersEnabled(INSTANCE_FILTERS_ENABLED);
    breakpoint.setInstanceFilters(getInstanceFilters());
  }

  public void readExternal(Element parentNode) throws InvalidDataException {
    DefaultJDOMExternalizer.readExternal(this, parentNode);
    if (DebuggerSettings.SUSPEND_NONE.equals(SUSPEND_POLICY)) { // compatibility with older format
      SUSPEND = false;
      SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
    }
    String condition = JDOMExternalizerUtil.readField(parentNode, CONDITION_OPTION_NAME);
    if (condition != null) {
      setCondition(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition));
    }

    myClassFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(FILTER_OPTION_NAME));
    myClassExclusionFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(EXCLUSION_FILTER_OPTION_NAME));

    final ClassFilter [] instanceFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(INSTANCE_ID_OPTION_NAME));
    final List<InstanceFilter> iFilters = new ArrayList<>(instanceFilters.length);

    for (ClassFilter instanceFilter : instanceFilters) {
      try {
        iFilters.add(InstanceFilter.create(instanceFilter));
      }
      catch (Exception ignored) {
      }
    }
    myInstanceFilters = iFilters.isEmpty() ? InstanceFilter.EMPTY_ARRAY : iFilters.toArray(new InstanceFilter[iFilters.size()]);
  }

  public void writeExternal(Element parentNode) throws WriteExternalException {
    DefaultJDOMExternalizer.writeExternal(this, parentNode);
    JDOMExternalizerUtil.writeField(parentNode, CONDITION_OPTION_NAME, getCondition().toExternalForm());
    DebuggerUtilsEx.writeFilters(parentNode, FILTER_OPTION_NAME, myClassFilters);
    DebuggerUtilsEx.writeFilters(parentNode, EXCLUSION_FILTER_OPTION_NAME, myClassExclusionFilters);
    DebuggerUtilsEx.writeFilters(parentNode, INSTANCE_ID_OPTION_NAME, InstanceFilter.createClassFilters(myInstanceFilters));
  }

  public TextWithImports getCondition() {
    return myCondition;
  }

  public void setCondition(TextWithImports condition) {
    myCondition = condition;
  }

  public Project getProject() {
    return myProject;
  }

  public boolean isCountFilterEnabled() {
    return COUNT_FILTER_ENABLED;
  }

  public int getCountFilter() {
    return COUNT_FILTER;
  }

  public boolean isClassFiltersEnabled() {
    return CLASS_FILTERS_ENABLED;
  }

  public boolean isInstanceFiltersEnabled() {
    return INSTANCE_FILTERS_ENABLED;
  }

  @Override
  public boolean processLocatableEvent(SuspendContextCommandImpl action, LocatableEvent event)
    throws EventProcessingException {
    return false;
  }
}


text:
require "spec_helper"
require "async_helpers"
require File.dirname(__FILE__) + "/../lib/em/worker.rb"

describe "EM::Worker" do
  include AsyncHelpers

  before do
    @worker = EM::Worker.new
  end

  it "can enqueue a task" do
    async_wrapper do
      @worker.enqueue do
        puts "winning"
      end.should eql true
      async_done
    end
  end

  it "does work" do
    async_wrapper do
      task = Proc.new { "tiger blood" }
      callback = Proc.new do |result|
        result.should eql "tiger blood"
        async_done
      end
      @worker.enqueue(task, callback)
    end
  end

  it "will do a maximum of 12 tasks at a time by default" do
    @concurrency = Queue.new
    async_wrapper do
      24.times do
        @worker.enqueue do
          @concurrency << 1
          sleep 1000
        end
      end
      timer(1) do
        @concurrency.size.should eql 12
        async_done
      end
    end
  end

  it "will complete tasks" do
    @results = []
    async_wrapper do
      1000.times do |i|
        task = Proc.new { i }
        callback = Proc.new do |result|
          @results << result
        end
        @worker.enqueue(task, callback)
      end
      timer(2) do
        @results.size.should eql 1000
        async_done
      end
    end
  end
end


text: PERL module for createing unix installation packages(RPM for now).


text:
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using umbraco.interfaces;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Content = umbraco.cms.businesslogic.Content;

namespace umbraco.editorControls
{
    [ValidationProperty("IsValid")]
    [Obsolete("IDataType and all other references to the legacy property editors are no longer used this will be removed from the codebase in future versions")]
    public class uploadField : HtmlInputFile, IDataEditor
    {
        private const string Thumbnailext = ".jpg";
        private readonly cms.businesslogic.datatype.FileHandlerData _data;
        private readonly string _thumbnails;
        private string _text;
        private readonly MediaFileSystem _fs;
        private CustomValidator _customValidator;

        public uploadField(IData Data, string ThumbnailSizes)
        {
            _fs = FileSystemProviderManager.Current.GetFileSystemProvider<MediaFileSystem>();
            _data = (cms.businesslogic.datatype.FileHandlerData)Data; //this is always FileHandlerData
            _thumbnails = ThumbnailSizes;
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            _customValidator = new CustomValidator
                {
                    EnableClientScript = false,
                    Display = ValidatorDisplay.Dynamic,
                    ErrorMessage = ui.Text("errors", "dissallowedMediaType")
                };
            _customValidator.ErrorMessage += "
";

            //NOTE: it would be better to have this as a normal composite control but we don't want to
            // break compatibility so we cannot make this inherit from a different class than it already
            // is, so now we have to hack this together and add this directly to the page validators collection
            // since we cannot add it as a control to this one.
            Page.Validators.Add(_customValidator);
        }

        ///
        /// Internal logic for validation controls to detect whether or not it's valid (has to be public though)
        ///
        /// <value>Am I valid?</value>
        /// <remarks>
        /// This is used for the required and regex validation of a document type's property
        /// </remarks>
        public string IsValid
        {
            get
            {
                var tempText = Text;
                var isEmpty = PostedFile == null || string.IsNullOrEmpty(PostedFile.FileName);
                // checkbox, if it's used the file will be deleted and we should throw a validation error
                if (Page.Request[ClientID + "clear"] != null && Page.Request[ClientID + "clear"] != "")
                    return "";
                if (isEmpty == false)
                    return PostedFile.FileName;
                return string.IsNullOrEmpty(tempText) == false
                    ? tempText
                    : "";
            }
        }

        ///
        /// Checks if the file is valid based on our dissallowed file types
        ///
        /// <param name="postedFile"></param>
        /// <returns></returns>
        internal bool IsValidFile(HttpPostedFile postedFile)
        {
            //return true if there is no file
            if (postedFile == null) return true;
            if (postedFile.FileName.IsNullOrWhiteSpace()) return true;

            //now check the file type
            var extension = Path.GetExtension(postedFile.FileName).TrimStart(".");

            return UmbracoConfig.For.UmbracoSettings().Content.IsFileAllowedForUpload(extension);
        }

        public string Text
        {
            get { return _text; }
            set { _text = value; }
        }

        #region IDataEditor Members

        public Control Editor
        {
            get { return this; }
        }

        public virtual bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        public bool ShowLabel
        {
            get { return true; }
        }

        public void Save()
        {
            // Clear data
            if (helper.Request(ClientID + "clear") == "1")
            {
                // delete file
                DeleteFile(_text);

                // set filename in db to nothing
                _text = "";
                _data.Value = _text;

                var props = new[] { Constants.Conventions.Media.Bytes, Constants.Conventions.Media.Extension, Constants.Conventions.Media.Height, Constants.Conventions.Media.Width };
                foreach (var prop in props)
                {
                    try
                    {
                        var bytesControl = Page.FindControlRecursive<noEdit>("prop_" + prop);
                        if (bytesControl != null)
                        {
                            bytesControl.RefreshLabel(string.Empty);
                        }
                    }
                    catch
                    {
                        //if first one fails we can assume that props don't exist
                        break;
                    }
                }
            }

            if (PostedFile == null || PostedFile.FileName == string.Empty) return;

            //don't save if the file is invalid
            if (IsValidFile(PostedFile) == false)
            {
                //set the validator to not valid
                _customValidator.IsValid = false;
                return;
            }

            _data.Value = PostedFile;

            // we update additional properties post image upload
            if (_data.Value != DBNull.Value && string.IsNullOrEmpty(_data.Value.ToString()) == false)
            {
                //check the FileHandlerData to see if it already loaded in the content item and set it's properties.
                //if not, then the properties haven't changed so skip.
                if (_data.LoadedContentItem != null)
                {
                    var content = _data.LoadedContentItem;

                    // update extension in UI
                    UpdateLabelValue(Constants.Conventions.Media.Extension, "prop_umbracoExtension", Page, content);
                    // update file size in UI
                    UpdateLabelValue(Constants.Conventions.Media.Bytes, "prop_umbracoBytes", Page, content);
                    UpdateLabelValue(Constants.Conventions.Media.Width, "prop_umbracoWidth", Page, content);
                    UpdateLabelValue(Constants.Conventions.Media.Height, "prop_umbracoHeight", Page, content);
                }

            }
            Text = _data.Value.ToString();
        }

        #endregion

        private static void UpdateLabelValue(string propAlias, string controlId, Page controlPage, Content content)
        {
            var extensionControl = controlPage.FindControlRecursive<noEdit>(controlId);
            if (extensionControl != null)
            {
                if (content.getProperty(propAlias) != null && content.getProperty(propAlias).Value != null)
                {
                    extensionControl.RefreshLabel(content.getProperty(propAlias).Value.ToString());
                }
            }
        }

        [Obsolete("This method is now obsolete due to a change in the way that files are handled.  If you need to check if a URL for an uploaded file is safe you should implement your own as this method will be removed in a future version", false)]
        public string SafeUrl(string url)
        {
            return string.IsNullOrEmpty(url) == false
                ? Regex.Replace(url, @"[^a-zA-Z0-9\-\.\/\:]{1}", "_")
                : String.Empty;
        }

        protected override void OnInit(EventArgs e)
        {
            EnsureChildControls();
            base.OnInit(e);
            if (_data != null && _data.Value != null)
                Text = _data.Value.ToString();
        }

        private void DeleteFile(string fileUrl)
        {
            if (fileUrl.Length > 0)
            {
                var relativeFilePath = _fs.GetRelativePath(fileUrl);

                // delete old file
                if (_fs.FileExists(relativeFilePath))
                    _fs.DeleteFile(relativeFilePath);

                var extension = (relativeFilePath.Substring(relativeFilePath.LastIndexOf(".") + 1, relativeFilePath.Length - relativeFilePath.LastIndexOf(".") - 1));
                extension = extension.ToLower();

                //check for thumbnails
                if (",jpeg,jpg,gif,bmp,png,tiff,tif,".IndexOf("," + extension + ",") > -1)
                {
                    //delete thumbnails
                    string relativeThumbFilePath = relativeFilePath.Replace("." + extension, "_thumb");

                    try
                    {
                        if (_fs.FileExists(relativeThumbFilePath + Thumbnailext))
                            _fs.DeleteFile(relativeThumbFilePath + Thumbnailext);
                    }
                    catch
                    {
                    }

                    if (_thumbnails != "")
                    {
                        var thumbnailSizes = _thumbnails.Split(";".ToCharArray());
                        foreach (var thumb in thumbnailSizes)
                        {
                            if (thumb != "")
                            {
                                string relativeExtraThumbFilePath = relativeThumbFilePath + "_" + thumb + Thumbnailext;

                                try
                                {
                                    if (_fs.FileExists(relativeExtraThumbFilePath))
                                        _fs.DeleteFile(relativeExtraThumbFilePath);
                                }
                                catch
                                {
                                }
                            }
                        }
                    }
                }
            }
        }

        ///
        /// Render this control to the output parameter specified.
        ///
        /// <param name="output"> The HTML writer to write out to </param>
        protected override void Render(HtmlTextWriter output)
        {
            //render the validator if it is not valid
            //NOTE: it would be better to have this as a normal composite control but we don't want to
            // break compatibility so we cannot make this inherit from a different class than it already
            // is, so now we have to hack this together.
            if (_customValidator.IsValid == false)
            {
                _customValidator.RenderControl(output);
            }

            if (string.IsNullOrEmpty(Text) == false)
            {
                var relativeFilePath = _fs.GetRelativePath(_text);
                var ext = relativeFilePath.Substring(relativeFilePath.LastIndexOf(".") + 1, relativeFilePath.Length - relativeFilePath.LastIndexOf(".") - 1);
                var relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb." + ext);
                var hasThumb = false;
                try
                {
                    hasThumb = _fs.FileExists(relativeThumbFilePath);

                    // 7.4.0 generates thumbs with the correct file extension, but check for old possible extensions as well
                    if (hasThumb == false)
                    {
                        relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb.png");
                        hasThumb = _fs.FileExists(relativeThumbFilePath);
                    }

                    if (hasThumb == false)
                    {
                        relativeThumbFilePath = relativeFilePath.Replace("." + ext, "_thumb.jpg");
                        hasThumb = _fs.FileExists(relativeThumbFilePath);
                    }
                }
                catch
                {
                }
                if (hasThumb)
                {
                    var thumb = new Image
                    {
                        ImageUrl = _fs.GetUrl(relativeThumbFilePath),
                        BorderStyle = BorderStyle.None
                    };

                    output.WriteLine("");
                    thumb.RenderControl(output);
                    output.WriteLine("
");
                }
                else
                    output.WriteLine("" +
                                     _fs.GetUrl(relativeFilePath) + "
");

                output.WriteLine("<input type=\"checkbox\" id=\"" + ClientID + "clear\" name=\"" + ClientID +
                                 "clear\" value=\"1\"/> " + ui.Text("uploadClear") +
                                 "
");
            }
            base.Render(output);
        }
    }
}


text:
package test.utils.domain;

import org.springframework.data.annotation.Id;

import java.io.Serializable;

/**
 * <p>
 * An abstract base clase for key-value objects that have a string
 * key and another string field.
 * </P>
 *
 * @author Neil Stevenson
 * @see {@link Movie}
 * @see {@link Song}
 */
public abstract class MyTitle
        implements Comparable<MyTitle>, Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private String id;
    private String title;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        MyTitle other = (MyTitle) obj;
        if (id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!id.equals(other.id)) {
            return false;
        }
        if (title == null) {
            if (other.title != null) {
                return false;
            }
        } else if (!title.equals(other.title)) {
            return false;
        }
        return true;
    }

    // Sort by title only
    @Override
    public int compareTo(MyTitle that) {
        return this.title.compareTo(that.getTitle());
    }

}


text:
.microdata {
	font-weight: bolder;
	font-style : italic;
}


text:
ARG RUBY_VERSION=2.7
FROM ruby:${RUBY_VERSION} AS base

RUN apt-get update && apt-get -y upgrade && apt-get -y install git jq

FROM base AS builder

COPY Gemfile marc_to_argot.gemspec VERSION .

RUN gem install bundler

RUN bundle config set path /gems && bundle config set with production test development && bundle install

FROM base

COPY --from=builder /gems /gems

RUN bundle config set path /gems

RUN echo "cd /app" >> ~/.bashrc

CMD ["/bin/bash"]


text:
#ifndef __COMMON_HEADER_H_
#define __COMMON_HEADER_H_

#include <PiPei.h>
#include <Ioh.h>
#include <IohCommonDefinitions.h>

#include <Library/IohLib.h>
#include <Library/BaseLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/CpuLib.h>
#include <Library/PciCf8Lib.h>
#include <Library/IoLib.h>
#include <Library/PciLib.h>
#include <Library/PcdLib.h>
#include <Library/DebugLib.h>
#include <IndustryStandard/Pci22.h>

#endif


text:
/**
 * storage.js
 * @author Stéphan Zych <info@monkeymonk.be>
 * @copyriht 2010-2011 Stéphan Zych <info@monkeymonk.be>
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

if (!window.storage) {
	window.storage = {};
}

(function (window, document, undefined) {
	"use strict";

	var storage = {
		type: 'localStorage', // localStorage, sessionStorage

		enabled: function () {
			try {
				return storage.type in window && window[storage.type] !== null;
			} catch (e) {
				return false;
			}
		}, // enabled

		set: function (sName, mValue) {
			if (sName === Object(sName)) {
				for (var name in sName) {
					if (sName.hasOwnProperty(name)) {
						this.type.setItem(name, sName[name]);
					}
				}
			} else {
				this.type.setItem(sName, mValue);
			}

			return this;
		}, // set

		get: function (sName, fallback) {
			var values = storage.all();

			if (Object.prototype.toString.call(sName) === '[object Array]') {
				var result = {};

				for (var i = 0, length = sName.length; i < length; i++) {
					var val = sName[i];
					result[val] = values[val] || fallback;
				}

				return result;
			} else {
				return values[sName] || fallback;
			}
		}, // get

		del: function (sName) {
			sName = Object.prototype.toString.call(sName) === '[object Array]' ? sName : [sName];

			for (var i = 0, length = sName.length; i < length; i++) {
				this.type.removeItem(sName[i]);
			}

			return this;
		}, // del

		clear: function () {
			this.type.clear();

			return this;
		}, // clear

		all: function () {
			var result = {};

			for (var i = 0, max = this.type.length; i < max; i++) {
				var key = this.type.key(i), val = this.type.getItem(key);

				result[key] = val;
			}

			return result;
		}, // all

		change: function (callback) {
			var onStorageChange = function (e) {
				if (!e) {
					e = window.event;
				}

				callback.call(storage, storage.all());
			};

			if (window.addEventListener) {
				window.addEventListener('storage', onStorageChange, false);
			} else {
				window.attachEvent('onstorage', onStorageChange);
			}

			return this;
		} // change
	}; // storage

	window.storage = storage;

}(window, document)); // Copyright (c) 2012 Stéphan Zych (monkeymonk.be), https://github.com/monkeymonk https://github.com/monkeymonk/storage.js


text:
from desktop.lib.django_util import render
from django.http import HttpResponse
import logging
import simplejson
import shell.conf
import shell.constants as constants
import shell.utils as utils
from shell.shellmanager import ShellManager
import sys

SHELL_OUTPUT_LOGGER = logging.getLogger("shell_output")
SHELL_INPUT_LOGGER = logging.getLogger("shell_input")

def _running_with_spawning(request):
  return 'eventlet.input' in request.META

def index(request):
  if not _running_with_spawning(request):
    return render('not_running_spawning.mako', request, {})
  shell_manager = ShellManager.global_instance()
  result = shell_manager.available_shell_types(request.user)
  if result is None:
    return render('no_such_user.mako', request, {})
  return render('index.mako', request, {'shells':result})

def create(request):
  if not _running_with_spawning(request):
    if request.method == "POST":
      result = simplejson.dumps({ constants.NOT_RUNNING_SPAWNING : True })
      return HttpResponse(result, mimetype="application/json")
    else:
      return render('not_running_spawning.mako', request, {})
  shell_manager = ShellManager.global_instance()
  user = request.user
  if request.method == "POST":
    key_name = request.POST.get(constants.KEY_NAME, "")
  else:
    key_name = request.GET.get(constants.KEY_NAME, "")
  SHELL_INPUT_LOGGER.info("%s %s - Create '%s' shell" %
                (request.META.get('REMOTE_ADDR'), user.username, key_name))
  result = shell_manager.try_create(user, key_name)
  if request.method == "POST":
    return HttpResponse(simplejson.dumps(result), mimetype="application/json")
  else:
    if constants.SUCCESS in result:
      shell_types = shell_manager.available_shell_types(user)
      dict_for_template = { 'shells' : shell_types,
                            'shell_id' : result.get(constants.SHELL_ID) }
      return render('index.mako', request, dict_for_template)
    else:
      return render('failed_to_create.mako', request, {})

def kill_shell(request):
  if not _running_with_spawning(request):
    result = simplejson.dumps({ constants.NOT_RUNNING_SPAWNING : True })
    return HttpResponse(result, mimetype="application/json")
  shell_manager = ShellManager.global_instance()
  username = request.user.username
  shell_id = request.POST[constants.SHELL_ID]
  SHELL_INPUT_LOGGER.info("%s %s - shell_id:%s - Kill shell" %
                 (request.META.get('REMOTE_ADDR'), username, shell_id))
  result = shell_manager.kill_shell(username, shell_id)
  return HttpResponse(result)

def process_command(request):
  if not _running_with_spawning(request):
    result = simplejson.dumps({ constants.NOT_RUNNING_SPAWNING : True })
    return HttpResponse(result, mimetype="application/json")
  shell_manager = ShellManager.global_instance()
  username = request.user.username
  shell_id = request.POST[constants.SHELL_ID]
  command = request.POST.get(constants.COMMAND, "")
  SHELL_INPUT_LOGGER.info("%s %s - shell_id:%s - Command:'%s'" %
              (request.META.get('REMOTE_ADDR'), username, shell_id, command))
  result = shell_manager.process_command(username, shell_id, command)
  return HttpResponse(simplejson.dumps(result), mimetype="application/json")

def retrieve_output(request):
  if not _running_with_spawning(request):
    result = simplejson.dumps({ constants.NOT_RUNNING_SPAWNING : True })
    return HttpResponse(result, mimetype="application/json")
  shell_manager = ShellManager.global_instance()
  username = request.user.username
  hue_instance_id = request.META[constants.HUE_INSTANCE_ID]
  try:
    shell_pairs = utils.parse_shell_pairs(request)
  except ValueError:
    shell_pairs = []
  result = shell_manager.retrieve_output(username, hue_instance_id, shell_pairs)
  for key, value in result.iteritems():
    if isinstance(value, dict) and constants.OUTPUT in value:
      log_format = '%s %s - shell_id:%s - Output: "%s"'
      log_args = (request.META.get('REMOTE_ADDR'), username, key,
                                        repr(value[constants.OUTPUT]))
      SHELL_OUTPUT_LOGGER.info(log_format % log_args)
  return HttpResponse(simplejson.dumps(result), mimetype="application/json")

def add_to_output(request):
  if not _running_with_spawning(request):
    result = simplejson.dumps({ constants.NOT_RUNNING_SPAWNING : True })
    return HttpResponse(result, mimetype="application/json")
  shell_manager = ShellManager.global_instance()
  username = request.user.username
  hue_instance_id = request.META[constants.HUE_INSTANCE_ID]
  try:
    shell_pairs = utils.parse_shell_pairs(request)
  except ValueError:
    shell_pairs = []
  result = shell_manager.add_to_output(username, hue_instance_id, shell_pairs)
  return HttpResponse(simplejson.dumps(result), mimetype="application/json")


text:
extern "C" void _ReadWriteBarrier(void);
#pragma intrinsic(_ReadWriteBarrier)

namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost
{
    namespace detail
    {
        inline long interlocked_read_acquire(long volatile* x) BOOST_NOEXCEPT
        {
            long const res=*x;
            _ReadWriteBarrier();
            return res;
        }
        inline void* interlocked_read_acquire(void* volatile* x) BOOST_NOEXCEPT
        {
            void* const res=*x;
            _ReadWriteBarrier();
            return res;
        }

        inline void interlocked_write_release(long volatile* x,long value) BOOST_NOEXCEPT
        {
            _ReadWriteBarrier();
            *x=value;
        }
        inline void interlocked_write_release(void* volatile* x,void* value) BOOST_NOEXCEPT
        {
            _ReadWriteBarrier();
            *x=value;
        }
    }
}

#else

namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost
{
    namespace detail
    {
        inline long interlocked_read_acquire(long volatile* x) BOOST_NOEXCEPT
        {
            return BOOST_INTERLOCKED_COMPARE_EXCHANGE(x,0,0);
        }
        inline void* interlocked_read_acquire(void* volatile* x) BOOST_NOEXCEPT
        {
            return BOOST_INTERLOCKED_COMPARE_EXCHANGE_POINTER(x,0,0);
        }
        inline void interlocked_write_release(long volatile* x,long value) BOOST_NOEXCEPT
        {
            BOOST_INTERLOCKED_EXCHANGE(x,value);
        }
        inline void interlocked_write_release(void* volatile* x,void* value) BOOST_NOEXCEPT
        {
            BOOST_INTERLOCKED_EXCHANGE_POINTER(x,value);
        }
    }
}

#endif

#include <boost/config/abi_suffix.hpp>

#endif


text:
// create a firebase reference to the root
var ref = new Firebase('https://publicdata-parking.firebaseio.com');
var busRef = new Firebase('https://publicdata-transit.firebaseio.com');
var custRef = new Firebase('https://spaceteam.firebaseio.com');
var data;
var data1;
var data2;

// read data from the location san_francisco/garages, only once
function drawMap(){
	ref.child('san_francisco/garages').once('value', function(snapshot){
	  data = snapshot.val()

	  var garages = _.filter(data, function(d){
		  return _.has(d, 'open_spaces')
	  })

	  drawGarages(garages)
	})

}

function generateBus(bus_id){
	busRef.child('sf-muni/vehicles').on('value', function(snapshot){
		data1 = snapshot.val()
		drawBuses(data1, bus_id);
	})
}

	custRef.on('value', function(snapshot){
		data2 = snapshot.val()
    markersLayerGroupUser.clearLayers()
		drawCustomers(data2);
	})

var attributionText = 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox'

// create the map
var map = L.map($('#map')[0]).setView([37.78, -122.41], 13)
L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: attributionText,
    maxZoom: 18,
    id: 'doubleshow.noeko77m',
    accessToken: 'pk.eyJ1IjoiZG91Ymxlc2hvdyIsImEiOiJjaWZ5Y3B1eTE1MHRidWRtMG9uZXluajg4In0.u5ONW27Ly5cU7M5KYi6Y9Q'
}).addTo(map)

// create a layer group to hold all the markers
var markersLayerGroup = L.layerGroup()
var markersLayerGroupUser = L.layerGroup()
// add the makers layer group to the map
markersLayerGroup.addTo(map)
markersLayerGroupUser.addTo(map)

// visualize garages on a map
function drawGarages(garages){

  // clear all existing markers (if any)
  markersLayerGroup.clearLayers()

  _.forEach(garages, function(garage){
    var color_icon;
  var points = garage.points
    var latlng = [points[0], points[1]]
    // create a circle layer
    /*var circle = L.circle(latlng, 10, {
        color: 'red',
        fillColor: '#f03',
        fillOpacity: 0.5
    })*/
  var garage_name = garage.friendlyName;
  var open = garage.open_spaces;
  var total = garage.total_spaces;

  if (parseInt(open) < 100){
    color_icon = createIcon('img/redicon.png', latlng);
  }
  else if (parseInt(open) >= 100 && parseInt(open) < 300){
    color_icon = createIcon('img/bluedot.png', latlng);
  }
  else {
    color_icon = createIcon('img/greenicon.png', latlng);
  }

  var rate_data = getRate(garage);

  var button = "<button onclick='generate_modal(\"" + rate_data[0] + "\" , \"" + rate_data[1] + "\")' class='btn btn-primary' data-toggle='modal' data-target='#myModal'>Rates</button>"
  L.marker(latlng, {icon: color_icon}).bindPopup("" + garage_name + "
" + open + " open spaces
" + total + " total spaces
" +
                           "
" + button + "
").addTo(map);

    // add the circle layer to the makers layer group
    //markersLayerGroup.addLayer(circle)

  })

}

function drawBuses(bus_data, bus_id){
  // clear all existing markers (if any)
  var bool = 0;
  markersLayerGroup.clearLayers()
  	map.eachLayer(function (layer) {
		if (parseInt(layer._leaflet_id) == 22){
			bool = 1;
		}
		else{
			bool = 0;
		}
		if (bool == 0){
			map.removeLayer(layer);
		}
	});
  drawMap();
  console.log("method called");
  _.forEach(bus_data, function(bus){
	  var latlng = [bus.lat, bus.lon]
	  if (bus.vtype == 'bus'){
		  bus_val = parseInt(bus.id);
		  var busIcon = L.icon({
			iconUrl: 'img/busicon.png',
			iconSize: [20, 30],
			popupAnchor: [0, 0]
		  })
		  if (bus_val >= bus_id-2000 && bus_val <= bus_id){
			L.marker(latlng, {icon: busIcon}).addTo(map)
		  }
	  /*var circle = L.circle(latlng, 2, {
		color: 'red',
		fillColor: '#f03',
		fillOpacity: 0.5
	  }).addTo(map)*/
	  }
  })
}

function drawCustomers(data2){
  _.forEach(data2, function(users){
    var latlng = [users.lat, users.lon]
    var custIcon = L.icon({
			iconUrl: 'img/customer.png',
			iconSize: [20, 30],
			popupAnchor: [0, 0]
		  })
			L.marker(latlng, {icon: custIcon}).addTo(map)
  })
}

function createIcon(image, latlng){
  var colorcon = L.icon({
    iconUrl: image,
    iconSize: [30, 50],
    popupAnchor: [0, 0]
  });
  return colorcon;
}

function getRate(garage){
  var name = garage.friendlyName;
  var content = "";
  var garage_rate_info = [];
  for (var time in garage.rates){
    for (var ele in garage.rates[time]){
      content += ele + ':';
      content += garage.rates[time][ele] + "   ";
    }
    content += "
"
  }
  garage_rate_info[0] = name;
  garage_rate_info[1] = content;
  return garage_rate_info;
}

function generate_modal(rate0, rate1){
  //refresh
  document.getElementById('rate-title').innerHTML = rate0
  document.getElementById('content-stuff').innerHTML = rate1
}

drawMap();
generateBus(2000);