text:
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/

// .NAME vtkBSPCuts - This class represents an axis-aligned Binary Spatial
//    Partitioning of a 3D space.
//
// .SECTION Description
//    This class converts between the vtkKdTree
//    representation of a tree of vtkKdNodes (used by vtkDistributedDataFilter)
//    and a compact array representation that might be provided by a
//    graph partitioning library like Zoltan.  Such a representation
//    could be used in message passing.
//
// .SECTION See Also
//      vtkKdTree vtkKdNode vtkDistributedDataFilter

#ifndef __vtkBSPCuts_h
#define __vtkBSPCuts_h

#include "vtkCommonDataModelExport.h" // For export macro
#include "vtkDataObject.h"

class vtkKdNode;

class VTKCOMMONDATAMODEL_EXPORT vtkBSPCuts : public vtkDataObject
{
public:
  static vtkBSPCuts *New();
  vtkTypeMacro(vtkBSPCuts, vtkDataObject);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  //   Initialize the cuts with arrays of information.  This type of
  //   information would be obtained from a graph partitioning software
  //   package like Zoltan.
  //
  //   bounds - the bounds (xmin, xmax, ymin, ymax, zmin, zmax) of the
  //             space being partitioned
  //   ncuts - the number cuts, also the size of the following arrays
  //   dim   - the dimension along which the cut is made (x/y/z - 0/1/2)
  //   coord - the location of the cut along the axis
  //   lower - array index for the lower region bounded by the cut
  //   upper - array index for the upper region bounded by the cut
  //   lowerDataCoord - optional upper bound of the data in the lower region
  //   upperDataCoord - optional lower bound of the data in the upper region
  //   npoints - optional number of points in the spatial region

  void CreateCuts(double *bounds,
                  int ncuts, int *dim, double *coord,
                  int *lower, int *upper,
                  double *lowerDataCoord, double *upperDataCoord,
                  int *npoints);

  // Description:
  //   Initialize the cuts from a tree of vtkKdNode's

  void CreateCuts(vtkKdNode *kd);

  // Description:
  //   Return a tree of vtkKdNode's representing the cuts specified
  //   in this object.  This is our copy, don't delete it.

  vtkKdNode *GetKdNodeTree(){return this->Top;}

  // Description:
  //   Get the number of cuts in the partitioning, which also the size of
  //   the arrays in the array representation of the partitioning.

  vtkGetMacro(NumberOfCuts, int);

  // Description:
  //   Get the arrays representing the cuts in the partitioning.

  int GetArrays(int len, int *dim, double *coord, int *lower, int *upper,
                double *lowerDataCoord, double *upperDataCoord, int *npoints);

  // Description:
  // Compare these cuts with those of the other tree.  Returns true if
  // the two trees are the same.
  int Equals(vtkBSPCuts *other, double tolerance = 0.0);

  void PrintTree();
  void PrintArrays();

  //BTX
  // Description:
  // Retrieve an instance of this class from an information object.
  static vtkBSPCuts* GetData(vtkInformation* info);
  static vtkBSPCuts* GetData(vtkInformationVector* v, int i=0);
  //ETX

  // Description:
  // Restore data object to initial state,
  virtual void Initialize();

  // Description:
  // Shallow copy.  These copy the data, but not any of the
  // pipeline connections.
  virtual void ShallowCopy(vtkDataObject *src);
  virtual void DeepCopy(vtkDataObject *src);

protected:

  vtkBSPCuts();
  ~vtkBSPCuts();

  static void DeleteAllDescendants(vtkKdNode *kd);

  static int CountNodes(vtkKdNode *kd);
  static void SetMinMaxId(vtkKdNode *kd);
  static void _PrintTree(vtkKdNode *kd, int depth);

  void BuildTree(vtkKdNode *kd, int idx);
  int WriteArray(vtkKdNode *kd, int loc);

  void ResetArrays();
  void AllocateArrays(int size);

  vtkKdNode *Top;

  // required cut information

  int NumberOfCuts;// number of cuts, also length of each array
  int *Dim;        // dimension (x/y/z - 0/1/2) where cut occurs
  double *Coord;   // location of cut along axis
  int *Lower;               // location in arrays of left (lower) child info
  int *Upper;               // location in arrays of right (lower) child info

  // optional cut information

  double *LowerDataCoord;   // coordinate of uppermost data in lower half
  double *UpperDataCoord;   // coordinate of lowermost data in upper half
  int *Npoints;             // number of data values in partition

  double Bounds[6];

  vtkBSPCuts(const vtkBSPCuts&); // Not implemented
  void operator=(const vtkBSPCuts&); // Not implemented
};

#endif


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.CodeGeneration;

namespace Orleans.Runtime
{
    /// <summary>
    /// The IRuntimeClient interface defines a subset of the runtime API that is exposed to both silo and client.
    /// </summary>
    internal interface IRuntimeClient
    {
        /// <summary>
        /// Grain Factory to get and cast grain references.
        /// </summary>
        IInternalGrainFactory InternalGrainFactory { get; }

        /// <summary>
        /// Provides client application code with access to an Orleans logger.
        /// </summary>
        Logger AppLogger { get; }

        /// <summary>
        /// A unique identifier for the current client.
        /// There is no semantic content to this string, but it may be useful for logging.
        /// </summary>
        string CurrentActivationIdentity { get; }

        /// <summary>
        /// Gets the service provider.
        /// </summary>
        IServiceProvider ServiceProvider { get; }

        /// <summary>
        /// Get the current response timeout setting for this client.
        /// </summary>
        /// <returns>Response timeout value</returns>
        TimeSpan GetResponseTimeout();

        /// <summary>
        /// Sets the current response timeout setting for this client.
        /// </summary>
        /// <param name="timeout">New response timeout value</param>
        void SetResponseTimeout(TimeSpan timeout);

        void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null);

        void ReceiveResponse(Message message);

        Task ExecAsync(Func<Task> asyncFunction, ISchedulingContext context, string activityName);

        void Reset(bool cleanup);

        GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker);

        void DeleteObjectReference(IAddressable obj);

        Streams.IStreamProviderManager CurrentStreamProviderManager { get; }

        Streams.IStreamProviderRuntime CurrentStreamProviderRuntime { get; }

        IGrainTypeResolver GrainTypeResolver { get; }

        void BreakOutstandingMessagesToDeadSilo(SiloAddress deadSilo);
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Solution:
    def simplifyPath(self, path: str) -> str:
        if not path or not path.strip():
            return '/'

        path = path.strip('/')
        folders = path.split('/')
        ignore = 0
        result = ''
        for i in range(len(folders) - 1, -1, -1):
            if not folders[i] or folders[i] == '.':
                continue
            if folders[i] == '..':
                ignore += 1
                continue
            if ignore > 0:
                ignore -= 1
                continue

            result = '/' + folders[i] + result

        return result if len(result) > 0 else '/'


text:
namespace Einstein.Condition
{
	public class MissingMemberPredicateException : PredicateException
	{
		public MissingMemberPredicateException(object context, string member, string condition)
			: base(condition, string.Format("{0} does not contains a member matching the name '{1}'",
			context != null ? context.GetType().FullName : "[NULL]", member), null)
		{
			Context = context;
			MissingMember = member;
		}

		public object Context { get; private set; }
		public string MissingMember { get; private set; }
	}
}


text:
killall loader.rb
rm /tmp/neotoyz.fcgi
export loc_conf="/var/www/dev/phunkybb/config/config.xml"
spawn-fcgi /var/www/dev/neotoyz/loader.rb -s /tmp/neotoyz.fcgi -P /tmp/neotoyz.pid
chown www-data /tmp/neotoyz.fcgi


text:
namespace Engine {
	class IOManager {
	public:
		static bool readFileToBuffer(std::string &filePath, std::vector<unsigned char> &buffer);
};
}


text:
package org.genomebridge.boss.http.service;

import org.apache.commons.lang.ArrayUtils;
import org.genomebridge.boss.http.db.BossDAO;
import org.genomebridge.boss.http.db.ObjectRow;
import org.genomebridge.boss.http.models.ObjectCore;
import org.genomebridge.boss.http.models.StoragePlatform;
import org.genomebridge.boss.http.objectstore.ObjectStore;
import org.skife.jdbi.v2.DBI;

import java.net.URI;
import java.sql.Timestamp;
import java.util.*;

import javax.ws.rs.HttpMethod;
import javax.ws.rs.core.Response;
import javax.xml.bind.DatatypeConverter;

/**
 * Implements all application logic and interacts with object store and DB.
 */
public class DatabaseBossAPI implements BossAPI {

    public DatabaseBossAPI( DBI dbi, ObjectStore localStore, ObjectStore cloudStore,  Map<String,String> messages) {
        mDBI = dbi;
        mLocalStore = localStore;
        mCloudStore = cloudStore;
        mMessages = messages;
    }

    @Override
    public ErrorDesc getObject(String objectId, String userName, ObjectDesc desc) {
        BossDAO dao = getDao();
        if ( userName == null )
            return badReqErr(getMessage("remoteUser"));
        ObjectRow rec = dao.findObjectById(objectId);
        if ( rec == null )
            return notFoundErr(objectId);
        if ( !"Y".equals(rec.active) )
            return goneErr(objectId);
        if ( !dao.canRead(objectId,userName) )
            return readPermsErr(objectId,userName);
        rowToDesc(rec,desc,dao);
        return null;
    }

    @Override
    public ErrorDesc findObjectsByName(String objectName, String userName, List<ObjectDesc> descs) {
        descs.clear();
        if ( userName == null )
            return badReqErr(getMessage("remoteUser"));

        BossDAO dao = getDao();
        List<ObjectRow> recs = dao.findObjectsByName(userName, objectName);
        if ( recs == null || recs.size() == 0 )
            return new ErrorDesc(Response.Status.NOT_FOUND,String.format(getMessage("noReadable"),objectName));

        for ( ObjectRow rec : recs ) {
            ObjectDesc desc = new ObjectDesc();
            rowToDesc(rec,desc,dao);
            descs.add(desc);
        }
        return null;
    }

    @Override
    public ErrorDesc insertObject(ObjectDesc rec, String userName) {
        if ( userName == null )
            return badReqErr(getMessage("remoteUser"));
        String errMsg = testCreationValidity(rec);
        if ( errMsg != null )
            return badReqErr(errMsg);

        rec.objectId = UUID.randomUUID().toString();

        // Use the location passed in by the user if the Object is an opaqueURI object,
        // otherwise generate a new (fresh) location.
        String loc = rec.directoryPath;
        if ( !rec.storagePlatform.equals(StoragePlatform.OPAQUEURI.getValue()) &&
                !Boolean.TRUE.equals(rec.forceLocation) )
            loc = createLocation(rec);

        if ( rec.sizeEstimateBytes == null )
            rec.sizeEstimateBytes = gDefaultEstSize;

        List<String> readers = uniqueUsers(rec.readers);
        List<String> writers = uniqueUsers(rec.writers);

        Timestamp now = new Timestamp(System.currentTimeMillis());
        BossDAO dao = getDao();
        dao.begin();
        dao.insertObject(rec.objectId, rec.objectName, rec.ownerId, rec.sizeEstimateBytes,
                loc, rec.storagePlatform, userName, now);
        dao.insertReaders(rec.objectId, readers);
        dao.insertWriters(rec.objectId, writers);
        dao.commit();
        return null;
    }

    @Override
    public ErrorDesc updateObject(ObjectDesc desc, String objectId, String userName) {
        if ( userName == null )
            return badReqErr(getMessage("remoteUser"));
        BossDAO dao = getDao();
        ObjectRow rec = dao.findObjectById(objectId);
        if ( rec == null )
            return notFoundErr(objectId);
        if ( !"Y".equals(rec.active) )
            return goneErr(objectId);
        if ( !dao.canWrite(objectId,userName) )
            return writePermsErr(objectId,userName);

        String errMsg = testUpdateValidity(rec,desc);
        if ( errMsg != null )
            return badReqErr(errMsg);

        if ( desc.ownerId != null )
            rec.ownerId = desc.ownerId;

        List<String> readersToInsert = null;
        List<String> readersToDelete = null;
        if ( desc.readers != null ) {
            List<String> newUsers = Arrays.asList(desc.readers);
            List<String> curUsers = dao.findReadersById(desc.objectId);
            readersToInsert = diff(newUsers,curUsers);
            readersToDelete = diff(curUsers,newUsers);
        }
        List<String> writersToInsert = null;
        List<String> writersToDelete = null;
        if ( desc.writers != null ) {
            List<String> newUsers = Arrays.asList(desc.writers);
            List<String> curUsers = dao.findWritersById(desc.objectId);
            writersToInsert = diff(newUsers,curUsers);
            writersToDelete = diff(curUsers,newUsers);
        }

        Timestamp now = new Timestamp(System.currentTimeMillis());

        dao.begin();
        dao.updateObject(rec.objectId, rec.objectName, rec.ownerId, rec.sizeEstimateBytes, now);
        if ( readersToInsert != null )
            dao.insertReaders(rec.objectId, readersToInsert);
        if ( readersToDelete != null )
            dao.deleteReaders(rec.objectId, readersToDelete);
        if ( writersToInsert != null )
            dao.insertWriters(rec.objectId, writersToInsert);
        if ( writersToDelete != null )
            dao.deleteWriters(rec.objectId, writersToDelete);
        dao.commit();

        return null;
    }

    /*
        if this object resides in the object store, also delete from the object store.

        BOSS rev3 spec says: If BOSS is unable to delete the underlying object from the object storage
        (e.g. non-transient network failure, or other error from object store server), it will return an
        appropriate 50x error, and the entry for this object will not be deleted from BOSS.

        So, we delete from the db first, then the object store. If object store deletion fails,
        we rollback the db deletion.
    */
    @Override
    public ErrorDesc deleteObject(String objectId, String userName) {
        if ( userName == null )
            return badReqErr(getMessage("remoteUser"));
        BossDAO dao = getDao();
        ObjectRow rec = dao.findObjectById(objectId);
        if ( rec == null || !"Y".equals(rec.active) )
            return notFoundErr(objectId);
        if ( !dao.canWrite(objectId,userName) )
            return writePermsErr(objectId,userName);

        ObjectStore store = getObjectStore(rec.storagePlatform);
        Timestamp now = new Timestamp(System.currentTimeMillis());
        dao.begin();

        // Try to remove object resource first so we don't end up with orphaned records.
        try {
            dao.deleteObject(rec.objectId, now);
        } catch (Exception e) {
            dao.rollback();
            return new ErrorDesc(Response.Status.INTERNAL_SERVER_ERROR,
                    getMessage("unableDelete")+e.getMessage());
        }

        // Only commit the ObjectResource delete after checking for ObjectStore deletion.
        try {
            if ( store != null && rec.directoryPath != null )
                store.deleteObject(rec.directoryPath);
            dao.commit();
        } catch (Exception e) {
            dao.rollback();
            return new ErrorDesc(Response.Status.INTERNAL_SERVER_ERROR,
                   getMessage("unableDeleteFromObjectStore")+e.getMessage());
        }

        return null;
    }

    @Override
    public ErrorDesc resolveObject(String objectId, String userName, ResolveRequest req, ResolveResponse resp) {
        if ( userName == null )
            return badReqErr(getMessage("remoteUser"));
        BossDAO dao = getDao();
        ObjectRow rec = dao.findObjectById(objectId);
        if ( rec == null )
            return notFoundErr(objectId);
        if ( !"Y".equals(rec.active) )
            return goneErr(objectId);

        if ( req.httpMethod.equals(HttpMethod.PUT) ) {
            if ( !dao.canWrite(objectId,userName) )
                return writePermsErr(objectId,userName);
        }
        else if ( req.httpMethod.equals(HttpMethod.GET) ||
                req.httpMethod.equals(HttpMethod.HEAD) ) {
            if ( !dao.canRead(objectId,userName) )
                return readPermsErr(objectId,userName);
        }
        else
            return badReqErr(getMessage("httpMethod"));

        String contentMD5x64 = null;
        if ( req.contentMD5Hex != null ) {
            if ( req.contentMD5Hex.length() != 32 )
                return badReqErr(getMessage("md5"));
            try {
                contentMD5x64 = DatatypeConverter.printBase64Binary(DatatypeConverter.parseHexBinary(req.contentMD5Hex));
            }
            catch ( IllegalArgumentException e ) {
                return badReqErr(getMessage("contentMD5"));
            }
        }

        Timestamp now = new Timestamp(System.currentTimeMillis());
        dao.updateResolveDate(objectId, now);

        resp.validityPeriodSeconds = req.validityPeriodSeconds;
        resp.contentType = req.contentType;
        resp.contentMD5Hex = req.contentMD5Hex;
        if ( rec.storagePlatform.equals(StoragePlatform.OPAQUEURI.getValue()) )
            resp.objectUrl = URI.create(rec.directoryPath);
        else {
            long timeout = now.getTime() + 1000L*req.validityPeriodSeconds;
            ObjectStore objStore = getObjectStore(rec.storagePlatform);
            resp.objectUrl = objStore.generateResolveURI(rec.directoryPath, req.httpMethod,
                                                            timeout, req.contentType, contentMD5x64);
        }
        return null;
    }

    @Override
    public ErrorDesc resolveObjectForCopying(String objectId, String userName, CopyRequest req, CopyResponse resp) {
        if ( userName == null )
            return badReqErr("REMOTE_USER header is required.");
        BossDAO dao = getDao();
        ObjectRow rec = dao.findObjectById(objectId);
        if ( rec == null )
            return notFoundErr(objectId);
        if ( !"Y".equals(rec.active) )
            return goneErr(objectId);
        if ( rec.storagePlatform.equals(StoragePlatform.OPAQUEURI.getValue()) )
            return badReqErr("Can't copy opaqueURI objects.");
        if ( !dao.canWrite(objectId,userName) )
            return writePermsErr(objectId,userName);

        Timestamp now = new Timestamp(System.currentTimeMillis());
        dao.updateResolveDate(objectId, now);

        ObjectStore objStore = getObjectStore(rec.storagePlatform);
        long timeout = now.getTime() + 1000L*req.validityPeriodSeconds;
        resp.uri = objStore.generateCopyURI(rec.directoryPath, req.locationToCopy, timeout);

        return null;
    }

    private BossDAO getDao() {
        return mDBI.onDemand(BossDAO.class);
    }

    private ObjectStore getObjectStore( String storagePlatform ) {
        if ( storagePlatform.equals(StoragePlatform.CLOUDSTORE.getValue()) )
            return mCloudStore;
        if ( storagePlatform.equals(StoragePlatform.LOCALSTORE.getValue()) )
            return mLocalStore;

        return null;
    }

    private String testCreationValidity( ObjectDesc desc ) {
        StringBuilder sb = new StringBuilder();
        if ( desc.objectId != null ) add(sb,getMessage("objectIdNotSupplied"));
        if ( desc.objectName == null ) add(sb,getMessage("objectValidation"));
        if ( desc.ownerId == null ) add(sb,getMessage("ownerIdValidation"));
        if ( desc.storagePlatform == null ) add(sb,getMessage("storagePlatformValidation"));
        else {
            if ( desc.storagePlatform.equals(StoragePlatform.CLOUDSTORE.getValue()) ||
                    desc.storagePlatform.equals(StoragePlatform.LOCALSTORE.getValue()) ) {
                if ( desc.directoryPath != null && !Boolean.TRUE.equals(desc.forceLocation) )
                    add(sb,String.format(getMessage("directoryPathNotSupplied"),desc.storagePlatform));
            }
            else if ( desc.storagePlatform.equals(StoragePlatform.OPAQUEURI.getValue()) ) {
                if ( desc.directoryPath == null )
                    add(sb,String.format(getMessage("directoryPathToSupply"),StoragePlatform.OPAQUEURI.getValue()));
            }
            else {

                add(sb, String.format(getMessage("storagePlatformOptions"),
                        StoragePlatform.CLOUDSTORE.getValue(),
                        StoragePlatform.LOCALSTORE.getValue(),
                        StoragePlatform.OPAQUEURI.getValue()));
            }
        }
        return sb.length() > 0 ? sb.append('.').toString() : null;
    }

    private String testUpdateValidity( ObjectCore oldObj, ObjectCore newObj ) {
        StringBuilder sb = new StringBuilder();
        if ( !consistent(oldObj.objectId,newObj.objectId) )
            add(sb,getMessage("objectIdFixed"));
        if ( !consistent(oldObj.objectName,newObj.objectName) )
            add(sb,getMessage("objectNameFixed"));
        if ( !consistent(oldObj.storagePlatform,newObj.storagePlatform) )
            add(sb,getMessage("storagePlatformFixed"));
        if ( !consistent(oldObj.sizeEstimateBytes,newObj.sizeEstimateBytes) )
            add(sb,getMessage("sizeEstimateFixed"));
        if ( !consistent(oldObj.directoryPath,newObj.directoryPath) )
            add(sb,getMessage("directoryPathFixed"));
        return sb.length() > 0 ? sb.append('.').toString() : null;
    }

    private static void add(StringBuilder sb, String message ) {
        if ( sb.length() > 0 ) sb.append(";/n");
        sb.append(message);
    }

    private static void rowToDesc( ObjectRow row, ObjectDesc desc, BossDAO dao ) {
        desc.copy(row);
        if ( !desc.storagePlatform.equals(StoragePlatform.OPAQUEURI.getValue()) )
            desc.directoryPath = null;
        desc.readers = dao.findReadersById(row.objectId).toArray(ArrayUtils.EMPTY_STRING_ARRAY);
        desc.writers = dao.findWritersById(row.objectId).toArray(ArrayUtils.EMPTY_STRING_ARRAY);
    }

    private static List<String> uniqueUsers( String[] users ) {
        Set<String> userSet = new TreeSet<>(Arrays.asList(users));
        return new ArrayList<String>(userSet);
    }

    private static List<String> diff( List<String> minuend, List<String> subtrahend ) {
        Set<String> strSet = new TreeSet<>(minuend);
        strSet.removeAll(subtrahend);
        return strSet.size() > 0 ? new ArrayList<>(strSet) : null;
    }

    private static String createLocation(ObjectDesc desc) {
        String random = UUID.randomUUID().toString();
        String[] splits = random.split("-");
        String last = splits[splits.length-1];
        return String.format("%s-%s", desc.objectId, last);
    }

    private static boolean consistent(Object oldVal, Object newVal) {
        return newVal == null || newVal.equals(oldVal);
    }

    private ErrorDesc notFoundErr(String objectId) {
        return new ErrorDesc(Response.Status.NOT_FOUND,String.format(getMessage("objectNotFound"),objectId));
    }

    private ErrorDesc goneErr(String objectId) {
        return new ErrorDesc(Response.Status.GONE,String.format(getMessage("objectDeleted"),objectId));
    }

    private ErrorDesc readPermsErr(String objectId, String userName) {
        return new ErrorDesc(Response.Status.FORBIDDEN,String.format(getMessage("noReadPermission"),objectId,userName));
    }

    private ErrorDesc writePermsErr(String objectId, String userName) {
        return new ErrorDesc(Response.Status.FORBIDDEN,String.format(getMessage("noWritePermission"),objectId,userName));
    }

    private static ErrorDesc badReqErr(String message) {
        return new ErrorDesc(Response.Status.BAD_REQUEST,message);
    }

    private String getMessage(String key) {
        String msg = mMessages.get(key);
        if ( msg == null )
            msg = "Server misconfiguration: No message for "+key+'.';
        return msg;
    }

    DBI mDBI;
    private ObjectStore mLocalStore;
    private ObjectStore mCloudStore;
    private Map<String,String> mMessages;
    static private Long gDefaultEstSize = new Long(-1);
}


text:
<?php
namespace JsonRpc;

if (!function_exists("array_is_list")) {
	/* Polyfill from https://wiki.php.net/rfc/is_list */
	function array_is_list(array $array): bool {
		$expect = 0;
		foreach ($array as $k => $_) {
			if ($k !== $expect)
				return false;
			$expect++;
		}
		return true;
	}
}

class Absent {
	/* Sentinel value indicating that no call ID was present
	 * and that the request was a notification without reply.
	 */
}

class RpcException extends \Exception {
}

class RpcParseError extends RpcException {
	function __construct() {
		$this->code = -32700;
		$this->message = "JSON parse error";
	}
}

class RpcMalformedObjectError extends RpcException {
	function __construct() {
		$this->code = -32600;
		$this->message = "Not a well-formed JSON-RPC object";
	}
}

class RpcBadMethodError extends RpcException {
	function __construct() {
		$this->code = -32601;
		$this->message = "Specified method not available";
	}
}

class RpcBadParametersError extends RpcException {
	function __construct() {
		$this->code = -32602;
		$this->message = "Unacceptable call parameters";
	}
}

class Server {
	function dispatch($request, $server) {
		$call_id = null;
		$request = json_decode($request, true, 64);

		try {
			if (!$request) {
				throw new RpcParseError();
			}
			if (!is_array($request)) {
				throw new RpcMalformedObjectError();
			}
			if (@$request["jsonrpc"] !== "2.0") {
				throw new RpcMalformedObjectError();
			}
			if (!isset($request["method"])) {
				throw new RpcMalformedObjectError();
			}
			$method = $request["method"];
			$params = @$request["params"];
			if (!array_key_exists("id", $request)) {
				$call_id = new Absent();
			} else {
				$call_id = $request["id"];
				if (!is_null($call_id)
				&& !is_string($call_id)
				&& !is_numeric($call_id)) {
					throw new RpcMalformedObjectError();
				}
			}
			if (!is_string($method)) {
				throw new RpcMalformedObjectError();
			}
			if (preg_match("/^_|^rpc[._]/", $method)) {
				throw new RpcBadMethodError();
			}
			if (!method_exists($server, $method)) {
				throw new RpcBadMethodError();
			}
			try {
				if ($params === null) {
					$result = $server->$method();
				} elseif (is_array($params) && array_is_list($params)) {
					$result = $server->$method(...$params);
				} elseif (is_array($params)) {
					/* PHP allows spread of name=>value mappings,
					 * but we don't want to allow that. */
					throw new RpcBadParametersError();
				} else {
					throw new RpcMalformedObjectError();
				}
			} catch (\ArgumentCountError $e) {
				throw new RpcBadParametersError();
			}
			$response = [
				"jsonrpc" => "2.0",
				"result" => $result,
				"id" => $call_id,
			];
		} catch (RpcException $e) {
			$response = [
				"jsonrpc" => "2.0",
				"error" => [
					"code" => $e->getCode(),
					"message" => $e->getMessage(),
				],
				"id" => $call_id,
			];
		}

		if ($call_id instanceof Absent) {
			return null;
		} else {
			$response = json_encode($response);
			return $response;
		}
	}

	function handle_posted_request($server) {
		$request = file_get_contents("php://input");
		$response = $this->dispatch($request, $server);
		if ($response === null) {
			die();
		} else {
			header("Content-Type: application/json");
			die($response);
		}
	}
}


text:
require "spec_helper"
require "securerandom"

describe Rack::Oa::Middleware do
  include Rack::Test::Methods

  let(:app) do
    app = Rack::Builder.new
    app.use Rack::Oa::Middleware, options
    app.run ->(env) do
      [
        200,
        {},
        ["dummy"],
      ]
    end
    app
  end

  let(:options) do
    {
      authorization_class: authorization_class,
      client_class: client_class,
      resource_owner_class: resource_owner_class,
    }
  end

  let(:authorization_class) do
    Class.new do
      def self.find_by(access_token: nil)
        new
      end

      def self.create(client: nil, resource_owner: nil, scopes: nil)
        new
      end

      def to_hash
        {
          application: nil,
          created_at: nil,
          note: nil,
          scopes: nil,
          token: nil,
          updated_at: nil,
        }
      end
    end
  end

  let(:client_class) do
    Class.new do
      def self.find_by(client_id: nil, client_secret: nil)
        new
      end
    end
  end

  let(:resource_owner_class) do
    Class.new do
      def self.find_by(username: nil, password: nil)
        new
      end
    end
  end

  # Alias
  let(:response) do
    last_response
  end

  subject do
    send(method, path, request_body, env)
    response.status
  end

  let(:params) do
    {}
  end

  let(:headers) do
    {}
  end

  let(:request_body) do
    %r<application/json> === headers["Content-Type"] ? params.to_json : params
  end

  let(:env) do
    headers.inject({}) do |result, (key, value)|
      if key == "Content-Type"
        result.merge(key.upcase.gsub("-", "_") => value)
      else
        result.merge("HTTP_" + key.upcase.gsub("-", "_") => value)
      end
    end
  end

  let(:access_token) do
    SecureRandom.hex(32)
  end

  shared_examples_for "invalid request error" do
    it "returns an invalid request error" do
      should == 401
      response.body.should be_json_as(
        error: "invalid_request",
        error_message: "Access token was not given",
      )
    end
  end

  describe "GET /oauth/token" do
    let(:method) do
      :get
    end

    let(:path) do
      "/oauth/token"
    end

    context "without access token" do
      include_examples "invalid request error"
    end

    context "with Authorization header with bearer access token" do
      before do
        headers["Authorization"] = "Bearer #{access_token}"
      end

      it "returns access token details" do
        should == 200
        response.body.should be_json_as(
          application: nil,
          created_at: nil,
          note: nil,
          scopes: nil,
          token: nil,
          updated_at: nil,
        )
      end
    end

    context "with access token parameter" do
      before do
        params[:access_token] = access_token
      end

      it "always takes access token via parameter" do
        should == 200
      end
    end
  end

  describe "POST /oauth/token" do
    before do
      headers["Content-Type"] = "application/json"
      params[:client_id] = SecureRandom.hex(32)
      params[:client_secret] = SecureRandom.hex(32)
      params[:scopes] = []
    end

    let(:method) do
      :post
    end

    let(:path) do
      "/oauth/token"
    end

    context "without client_id parameter" do
      before do
        params.delete(:client_id)
      end
      include_examples "invalid request error"
    end

    context "without client_secret parameter" do
      before do
        params.delete(:client_secret)
      end
      include_examples "invalid request error"
    end

    context "with valid condition" do
      it "creates a authorization" do
        should == 201
        response.body.should be_json_as(
          application: nil,
          created_at: nil,
          note: nil,
          scopes: nil,
          token: nil,
          updated_at: nil,
        )
      end
    end
  end
end


text:
import os
from app.configuration import get_value
from app.helper import output_start, php, get_dirs, output_error

def execute():
    output_start('phpcs')

    dirs = get_dirs()
    phpcs_standard = dirs['project']+get_value('phpcs-standard')
    check_dir = get_value('check-dir')

    exclude_dirs = []
    for exclude_dir in get_value('exclude-dirs'):
        exclude_dirs.append(exclude_dir+'/*')
    excludes = ','.join(exclude_dirs)

    if excludes != '':
        excludes = '--ignore='+excludes

    if not os.path.isfile(phpcs_standard):
        print('>>> No phpcs-standard found. Fallback is the default move-elevator/symfony-coding-standard:')
        phpcs_standard = get_value('checker-dir')+'vendor/move-elevator/symfony-coding-standard/Standards/Symfony2'

    print('>>> phpcs standard: '+phpcs_standard)
    print('>>> Excludes: '+excludes)

    code = php('phpcs', '--standard='+phpcs_standard+' --extensions=php --report-checkstyle='+check_dir+'checkstyle.xml '+excludes+' '+dirs['scan'])

    if code == 512:
        output_error('There was a error/exception while executing phpcs.')


text:
window.ParsleyConfig = window.ParsleyConfig || {};

(function ($) {
  window.ParsleyConfig = $.extend( true, {}, window.ParsleyConfig, {
    messages: {
        defaultMessage: "Este valor parece estar inválido."
      , type: {
            email:      "Este valor deve ser um e-mail válido."
          , url:        "Este valor deve ser uma URL válida."
          , urlstrict:  "Este valor deve ser uma URL válida."
          , number:     "Este valor deve ser um número válido."
          , digits:     "Este valor deve ser um dígito válido."
          , dateIso:    "Este valor deve ser uma data válida (YYYY-MM-DD)."
          , alphanum:   "Este valor deve ser alfanumérico."
        }
      , notnull:        "Este valor não deve ser nulo."
      , notblank:       "Este valor não deve ser branco."
      , required:       "Este valor é obrigatório."
      , regexp:         "Este valor parece estar inválido."
      , min:            "Este valor deve ser maior que %s."
      , max:            "Este valor deve ser menor que %s."
      , range:          "Este valor deve estar entre %s e %s."
      , minlength:      "Este valor é muito pequeno. Ele deve ter %s caracteres ou mais."
      , maxlength:      "Este valor é muito grande. Ele deve ter %s caracteres ou menos."
      , rangelength:    "O tamanho deste valor é inválido. Ele deve possuir entre %s e %s caracteres."
      , equalto:        "Este valor deve ser o mesmo."
      , minwords:       "Este valor deve possuir no mínimo %s palavras."
      , maxwords:       "Este valor deve possuir no máximo %s palavras."
      , rangewords:     "Este valor deve possuir entre %s e %s palavras."
    }
  });
}(window.jQuery || window.Zepto));


text:
package com.muatik.service;

import com.muatik.model.Book;
import com.muatik.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by mustafaatik on 06/01/17.
 */
@Service
public class BookService {
    @Autowired
    private BookRepository repository;

    public void save(Book book) {
        repository.save(book);
    }

}


text:
package com.google.android.exoplayer2.source.rtsp.reader;

import static com.google.android.exoplayer2.util.Util.getBytesFromHexString;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.rtsp.RtpPayloadFormat;
import com.google.android.exoplayer2.testutil.FakeExtractorOutput;
import com.google.android.exoplayer2.testutil.FakeTrackOutput;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Bytes;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Unit test for {@link RtpAmrReader}. */
@RunWith(AndroidJUnit4.class)
public final class RtpAmrReaderTest {

  private FakeExtractorOutput extractorOutput;

  @Before
  public void setUp() {
    extractorOutput = new FakeExtractorOutput();
  }

  @Test
  public void consume_validAmrNbPackets() {
    RtpAmrReader amrReader = createAmrReader(MimeTypes.AUDIO_AMR);

    amrReader.createTracks(extractorOutput, /* trackId= */ 0);
    amrReader.onReceivingFirstPacket(/* timestamp= */ 2599168056L, /* sequenceNumber= */ 40289);
    amrReader.consume(
        new ParsableByteArray(
            Bytes.concat(
                getBytesFromHexString("00"), // AMR-NB Codec Mode = 0.
                getBytesFromHexString("40"), // AMR-NB ToC, F=0, FT=8.
                getBytesFromHexString("0102030405"))),
        /* timestamp= */ 2599168056L,
        /* sequenceNumber= */ 40289,
        /* rtpMarker= */ false);
    amrReader.consume(
        new ParsableByteArray(
            Bytes.concat(
                getBytesFromHexString("60"), // AMR-NB Codec Mode = 6.
                getBytesFromHexString("C0"), // AMR-NB ToC, F=1, FT=8.
                getBytesFromHexString("060708090A"))),
        /* timestamp= */ 2599169592L,
        /* sequenceNumber= */ 40290,
        /* rtpMarker= */ false);

    FakeTrackOutput trackOutput = extractorOutput.trackOutputs.get(0);
    assertThat(trackOutput.getSampleCount()).isEqualTo(2);
    assertThat(trackOutput.getSampleData(0)).isEqualTo(getBytesFromHexString("400102030405"));
    assertThat(trackOutput.getSampleTimeUs(0)).isEqualTo(0);
    assertThat(trackOutput.getSampleData(1)).isEqualTo(getBytesFromHexString("C0060708090A"));
    assertThat(trackOutput.getSampleTimeUs(1)).isEqualTo(192000);
  }

  @Test
  public void consume_amrNbPacketWithInvalidFrameType_throwsIllegalArgumentException() {
    RtpAmrReader amrReader = createAmrReader(MimeTypes.AUDIO_AMR);

    amrReader.createTracks(extractorOutput, /* trackId= */ 0);
    amrReader.onReceivingFirstPacket(/* timestamp= */ 2599168056L, /* sequenceNumber= */ 40289);

    assertThrows(
        IllegalArgumentException.class,
        () ->
            amrReader.consume(
                new ParsableByteArray(
                    Bytes.concat(
                        getBytesFromHexString("00"), // AMR-NB Codec Mode = 0.
                        getBytesFromHexString("68"), // AMR-NB ToC, F=0, FT=13.
                        getBytesFromHexString("0102030405"))),
                /* timestamp= */ 2599168056L,
                /* sequenceNumber= */ 40289,
                /* rtpMarker= */ false));
  }

  @Test
  public void consume_amrNbPacketWithInvalidFrameSize_throwsIllegalArgumentException() {
    // The payload frame type is 8, expecting five bytes of data, getting four.
    RtpAmrReader amrReader = createAmrReader(MimeTypes.AUDIO_AMR);

    amrReader.createTracks(extractorOutput, /* trackId= */ 0);
    amrReader.onReceivingFirstPacket(/* timestamp= */ 2599168056L, /* sequenceNumber= */ 40289);

    assertThrows(
        IllegalArgumentException.class,
        () ->
            amrReader.consume(
                new ParsableByteArray(
                    Bytes.concat(
                        getBytesFromHexString("00"), // AMR-NB Codec Mode = 0.
                        getBytesFromHexString("40"), // AMR-NB ToC, F=0, FT=8.
                        getBytesFromHexString("01020304"))),
                /* timestamp= */ 2599168056L,
                /* sequenceNumber= */ 40289,
                /* rtpMarker= */ false));
  }

  @Test
  public void consume_validAmrWbPackets() {
    RtpAmrReader amrReader = createAmrReader(MimeTypes.AUDIO_AMR_WB);

    amrReader.createTracks(extractorOutput, /* trackId= */ 0);
    amrReader.onReceivingFirstPacket(/* timestamp= */ 2599168056L, /* sequenceNumber= */ 40289);
    amrReader.consume(
        new ParsableByteArray(
            Bytes.concat(
                getBytesFromHexString("60"), // AMR-WB Codec Mode = 6.
                getBytesFromHexString("87"), // AMR-WB ToC, F=0, FT=0.
                getBytesFromHexString("0102030405060708090A0B0C0D0E0F1011"))),
        /* timestamp= */ 2599168056L,
        /* sequenceNumber= */ 40289,
        /* rtpMarker= */ false);
    amrReader.consume(
        new ParsableByteArray(
            Bytes.concat(
                getBytesFromHexString("00"), // AMR-WB Codec Mode = 0.
                getBytesFromHexString("7E"))), // AMR-WB ToC, F=0, FT=15.
        /* timestamp= */ 2599169592L,
        /* sequenceNumber= */ 40290,
        /* rtpMarker= */ false);

    FakeTrackOutput trackOutput = extractorOutput.trackOutputs.get(0);
    assertThat(trackOutput.getSampleCount()).isEqualTo(2);
    assertThat(trackOutput.getSampleData(0))
        .isEqualTo(getBytesFromHexString("870102030405060708090A0B0C0D0E0F1011"));
    assertThat(trackOutput.getSampleTimeUs(0)).isEqualTo(0);
    assertThat(trackOutput.getSampleData(1)).isEqualTo(getBytesFromHexString("7E"));
    assertThat(trackOutput.getSampleTimeUs(1)).isEqualTo(96000);
  }

  @Test
  public void consume_amrWbPacketWithInvalidFrameType_throwsIllegalArgumentException() {
    RtpAmrReader amrReader = createAmrReader(MimeTypes.AUDIO_AMR_WB);

    amrReader.createTracks(extractorOutput, /* trackId= */ 0);
    amrReader.onReceivingFirstPacket(/* timestamp= */ 2599168056L, /* sequenceNumber= */ 40289);

    assertThrows(
        IllegalArgumentException.class,
        () ->
            amrReader.consume(
                new ParsableByteArray(
                    Bytes.concat(
                        getBytesFromHexString("00"), // AMR-WB Codec Mode = 0.
                        getBytesFromHexString("D5"), // AMR-WB ToC, F=1, FT=10.
                        getBytesFromHexString("01020304"))),
                /* timestamp= */ 2599168056L,
                /* sequenceNumber= */ 40289,
                /* rtpMarker= */ false));
  }

  @Test
  public void consume_amrWbPacketWithInvalidFrameSize_throwsIllegalArgumentException() {
    // The payload frame type is 4, expecting 40 bytes of data, getting two.
    RtpAmrReader amrReader = createAmrReader(MimeTypes.AUDIO_AMR_WB);

    amrReader.createTracks(extractorOutput, /* trackId= */ 0);
    amrReader.onReceivingFirstPacket(/* timestamp= */ 2599168056L, /* sequenceNumber= */ 40289);

    assertThrows(
        IllegalArgumentException.class,
        () ->
            amrReader.consume(
                new ParsableByteArray(
                    Bytes.concat(
                        getBytesFromHexString("00"), // AMR-WB Codec Mode = 0.
                        getBytesFromHexString("A5"), // AMR-WB ToC, F=1, FT=4.
                        getBytesFromHexString("0102"))),
                /* timestamp= */ 2599168056L,
                /* sequenceNumber= */ 40289,
                /* rtpMarker= */ false));
  }

  private static RtpAmrReader createAmrReader(String mimeType) {
    switch (mimeType) {
      case MimeTypes.AUDIO_AMR:
        return new RtpAmrReader(createRtpPayloadFormat(mimeType, /* sampleRate= */ 8000));
      case MimeTypes.AUDIO_AMR_WB:
        return new RtpAmrReader(createRtpPayloadFormat(mimeType, /* sampleRate= */ 16000));
      default:
        throw new IllegalArgumentException("MimeType " + mimeType + " not supported.");
    }
  }

  private static RtpPayloadFormat createRtpPayloadFormat(String mimeType, int sampleRate) {
    return new RtpPayloadFormat(
        new Format.Builder()
            .setChannelCount(1)
            .setSampleMimeType(mimeType)
            .setSampleRate(sampleRate)
            .build(),
        /* rtpPayloadType= */ 97,
        /* clockRate= */ sampleRate,
        /* fmtpParameters= */ ImmutableMap.of(),
        MimeTypes.AUDIO_AMR.equals(mimeType)
            ? RtpPayloadFormat.RTP_MEDIA_AMR
            : RtpPayloadFormat.RTP_MEDIA_AMR_WB);
  }
}


text:
///////////////////////////////////////////////////////////////////////////////
// Name:        wx/time.h
// Purpose:     Miscellaneous time-related functions.
// Author:      Vadim Zeitlin
// Created:     2011-11-26
// Copyright:   (c) 2011 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

#ifndef _WX_TIME_H_
#define _WX_TIME_H_

#include "wx/longlong.h"

// Returns the difference between UTC and local time in seconds.
WXDLLIMPEXP_BASE int wxGetTimeZone();

// Get number of seconds since local time 00:00:00 Jan 1st 1970.
extern long WXDLLIMPEXP_BASE wxGetLocalTime();

// Get number of seconds since GMT 00:00:00, Jan 1st 1970.
extern long WXDLLIMPEXP_BASE wxGetUTCTime();

#if wxUSE_LONGLONG
    typedef wxLongLong wxMilliClock_t;
    inline long wxMilliClockToLong(wxLongLong ll) { return ll.ToLong(); }
#else
    typedef double wxMilliClock_t;
    inline long wxMilliClockToLong(double d) { return wx_truncate_cast(long, d); }
#endif // wxUSE_LONGLONG

// Get number of milliseconds since local time 00:00:00 Jan 1st 1970
extern wxMilliClock_t WXDLLIMPEXP_BASE wxGetLocalTimeMillis();

#if wxUSE_LONGLONG

// Get the number of milliseconds or microseconds since the Epoch.
wxLongLong WXDLLIMPEXP_BASE wxGetUTCTimeMillis();
wxLongLong WXDLLIMPEXP_BASE wxGetUTCTimeUSec();

#endif // wxUSE_LONGLONG

#define wxGetCurrentTime() wxGetLocalTime()

// on some really old systems gettimeofday() doesn't have the second argument,
// define wxGetTimeOfDay() to hide this difference
#ifdef HAVE_GETTIMEOFDAY
    #ifdef WX_GETTIMEOFDAY_NO_TZ
        #define wxGetTimeOfDay(tv)      gettimeofday(tv)
    #else
        #define wxGetTimeOfDay(tv)      gettimeofday((tv), NULL)
    #endif
#endif // HAVE_GETTIMEOFDAY

/* Two wrapper functions for thread safety */
#ifdef HAVE_LOCALTIME_R
#define wxLocaltime_r localtime_r
#else
WXDLLIMPEXP_BASE struct tm *wxLocaltime_r(const time_t*, struct tm*);
#if wxUSE_THREADS && !defined(__WINDOWS__) && !defined(__WATCOMC__)
     // On Windows, localtime _is_ threadsafe!
#warning using pseudo thread-safe wrapper for localtime to emulate localtime_r
#endif
#endif

#ifdef HAVE_GMTIME_R
#define wxGmtime_r gmtime_r
#else
WXDLLIMPEXP_BASE struct tm *wxGmtime_r(const time_t*, struct tm*);
#if wxUSE_THREADS && !defined(__WINDOWS__) && !defined(__WATCOMC__)
     // On Windows, gmtime _is_ threadsafe!
#warning using pseudo thread-safe wrapper for gmtime to emulate gmtime_r
#endif
#endif

#endif // _WX_TIME_H_


text:
Create a [Square-like](http://www.squareup.com) Menu Animation for Website using jQuery and CSS3
Created by [Pete R.](http://www.thepetedesign.com), Founder of [BucketListly](http://www.bucketlistly.com)

## Demo
[View demo](http://peachananr.github.io/square_menu/demo/square_menu_demo.html)

## Compatibility
Modern browsers such as Chrome, Firefox, and Safari on both desktop and smartphones have been tested. I have not tested this on IE.

## Basic Usage
Square menu, as you can see from the name, is a plugin that let you add a similar animated menu that you see on the new [Square website](http://www.squareup.com). I've also added additional animations, add various browsers support and provide options for you to play around with.

To add this to your website, make sure you've included the latest jQuery library together with `jquery.square_menu.js` and `square_menu.css` into your document's `<head>`, and make sure your HTML markup are as follows:
````html
<body>
  ..
  <div class="sidemenu">
    <nav class="left">
      <a href="...">...</a>
      <a href="...">...</a>
      <a href="...">...</a>
    </nav>
    <nav class="right">
      <a href="...">...</a>
      <a href="...">...</a>
      <a href="...">...</a>
    </nav>
  </div>
  ..
</body>
````
Note: Having 2 `nav` tags is very important for the plugin to function. Both these `nav` tags will be used to create a similar animation that you see on Square website. The content inside on the other hand, can be changed as you see fit.

Once that is done, simply call the function like this:

````javascript
  $(".sidemenu").square_menu({
    flyDirection: "bottom", // The direction where the menu will fly from. Available options are "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left" and "bottom-right". The default value is "bottom".
    button: "Menu", // You can define text inside the auto-generated button here. If you want to prevent the plugin from generating a menu button, change this to false. The default value is "Menu".
    animationStyle: "vertical", // The type of animation style you will see after it flew in. Available options are "vertical" which expands vertically and "horizontal" which expands horizontally. Vertical works best with "top" or "bottom" flyDirection whereas Horizontal works best with "left" or "right" flyDirection. The default value is "vertical".
    closeButton: "X" // You can define the content of the close button appears after animates are completed here. Change this to false to hide the close button. The default value is X.
  });
````

## Public Method

### $.fn.openMenu()

With this method, you can open your menu programmatically by calling the `openMenu()` function like this:

````javascript
$(".sidemenu").openMenu();
````

### $.fn.closeMenu()

Same goes for this method. You can close your menu programmatically by calling the `closeMenu()` function like this:

````javascript
$(".sidemenu").closeMenu();
````

Now you will have a beautifully crafted menu animation like you see on [Squareup.com](http://www.squareup.com) website with little to no effort. If you like this kind of plugin, stay tuned for more from me. :)

If you want to see more of my plugins, visit [The Pete Design](http://www.thepetedesign.com/#design), or follow me on [Twitter](http://www.twitter.com/peachananr) and [Github](http://www.github.com/peachananr).

## Other Resources
- [Tutorial](http://www.onextrapixel.com/2014/01/09/create-a-square-like-3d-animated-menu-gallery-with-jquery-square-menu/)


text:
<?php

namespace FFMPEGWrapper\Data;

class FFMPEGLibrary {
    use FFMPEGDataGetterTrait;

    private $_name;
    private $_version;

    public function __construct($name, $version)
    {
        $this->_name    = $name;
        $this->_version = $version;

        $this->addToGetterArray([
            "name"    => "getName",
            "version" => "getVersion"
        ]);
    }

    public function getName()
    {
        return $this->_name;
    }

    public function getVersion()
    {
        return $this->_version;
    }
}


text:
package sh.isaac.api.component.concept;

import org.jvnet.hk2.annotations.Contract;
import sh.isaac.api.coordinate.LogicCoordinate;
import sh.isaac.api.logic.LogicalExpression;

/**
 * The Interface ConceptBuilderService.
 *
 * @author kec
 */
@Contract
public interface ConceptBuilderService {
   /**
    * Gets the concept builder.
    *
    * @param conceptName - Optional - if specified, a FQN will be created using this value (but see additional information on semanticTag)
    * @param semanticTag - Optional - if specified, conceptName must be specified, and two descriptions will be created using the following forms:
    * - FQN: "conceptName (semanticTag)"
    * - Preferred: "conceptName"
    * If not specified:
    *    - If the specified FQN contains a semantic tag, the FQN will be created using that value. A preferred term will be created by stripping the
    * supplied semantic tag.
    *   - If the specified FQN does not contain a semantic tag, no preferred term will be created.
    * @param logicalExpression - Optional
    * @param languageForDescriptions - Optional - used as the language for the created FQN and preferred term
    * @param dialectForDescriptions - Optional - used as the language for the created FQN and preferred term
    * @param logicCoordinate - Optional - used during the creation of the logical expression, if any are passed for creation.
    * @param assemblageId the assemblage to create the concept in
    * @return the concept builder
    */
   ConceptBuilder getConceptBuilder(String conceptName,
                                    String semanticTag,
                                    LogicalExpression logicalExpression,
                                    ConceptSpecification languageForDescriptions,
                                    ConceptSpecification dialectForDescriptions,
                                    LogicCoordinate logicCoordinate,
                                    int assemblageId);

   /**
    * Gets the default concept builder.
    *
    * @param conceptName - Optional - if specified, a FQN will be created using this value (but see additional information on semanticTag)
    * @param semanticTag - Optional - if specified, conceptName must be specified, and two descriptions will be created using the following forms:
    * - FQN: "conceptName (semanticTag)"
    * - Preferred: "conceptName"
    * If not specified:
    *    - If the specified FQN contains a semantic tag, the FQN will be created using that value. A preferred term will be created by stripping the
    * supplied semantic tag.
    *   - If the specified FQN does not contain a semantic tag, no preferred term will be created.
    * @param logicalExpression - Optional
    * @param assemblageId the assemblage id to create the concept in
    * @return the default concept builder
    */
   ConceptBuilder getDefaultConceptBuilder(String conceptName, String semanticTag, LogicalExpression logicalExpression, int assemblageId);

   /**
    * Set default dialect assemblage for descriptions.
    *
    * @param dialectForDescriptions the dialect for descriptions
    * @return the concept builder service
    */
   ConceptBuilderService setDefaultDialectAssemblageForDescriptions(ConceptSpecification dialectForDescriptions);

   /**
    * Gets the default dialect for descriptions.
    *
    * @return the default dialect for descriptions
    */
   ConceptSpecification getDefaultDialectForDescriptions();

   /**
    * Gets the default language for descriptions.
    *
    * @return the default language for descriptions
    */
   ConceptSpecification getDefaultLanguageForDescriptions();

   /**
    * Set default language for descriptions.
    *
    * @param languageForDescriptions the language for descriptions
    * @return the concept builder service
    */
   ConceptBuilderService setDefaultLanguageForDescriptions(ConceptSpecification languageForDescriptions);

   /**
    * Gets the default logic coordinate.
    *
    * @return the default logic coordinate
    */
   LogicCoordinate getDefaultLogicCoordinate();

   //~--- set methods ---------------------------------------------------------

   /**
    * Set default logic coordinate.
    *
    * @param logicCoordinate the logic coordinate
    * @return the concept builder service
    */
   ConceptBuilderService setDefaultLogicCoordinate(LogicCoordinate logicCoordinate);
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="description" content="Propeller is a front-end responsive framework based on Material design & Bootstrap.">
	<meta content="width=device-width, initial-scale=1, user-scalable=no" name="viewport">
    <title>Form - Propeller Components</title>

	<link href="https://opensource.propeller.in/assets/landing-page/images/favicon.ico" type="image/x-icon" rel="icon"  />

	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet" />

	<link href="https://opensource.propeller.in/components/card/css/card.css" type="text/css" rel="stylesheet" />

	<link href="https://opensource.propeller.in/docs/css/example-docs.css" type="text/css" rel="stylesheet" />

	<link href="https://opensource.propeller.in/components/typography/css/typography.css" type="text/css" rel="stylesheet" />

    <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
	<link href="https://opensource.propeller.in/components/icons/css/google-icons.css" type="text/css" rel="stylesheet" />

    <link href="https://opensource.propeller.in/components/button/css/button.css" type="text/css" rel="stylesheet" />

    <link href="css/radio.css" type="text/css" rel="stylesheet" />

Radio

An HTML form is a section of a document containing normal content, markup, special elements called controls (checkboxes, radio buttons, menus, etc.), and labels on those controls. Users generally "complete" a form by modifying its controls (entering text, selecting menu items, etc.), before submitting the form to an agent for processing (e.g., to a Web server, to a mail server, etc.)

Radio

Add .pmd-radio in label to create a propeller customized radio. You can also add .pmd-radio-ripple-effect to provide a ripple effect to the radio.

											<input type="radio" name="optionsRadios" id="click" value="option1" checked>
											Option one is this and that—be sure to include why it's great

											<input type="radio" name="optionsRadios" id="click1" value="option1" checked>
											Option one is this and that—be sure to include why it's great

											<input type="radio" name="optionsRadios" id="optionsRadios3" value="option3" disabled>
											Option three is disabled

											<input type="radio" name="optionsRadios" id="click4" value="option1">
											Option one is this and that—be sure to include why it's great

											<input type="radio" name="optionsRadios" id="click5" value="option2" checked>
											Option one is this and that—be sure to include why it's great

											<input type="radio" name="optionsRadios" id="optionsRadios3" value="option3" disabled>
											Option three is disabled

							<button class="btn btn-default pmd-btn-raised" onclick="addRadio()">Add Radio</button>


text:
package test.annotationheaders.custom.d;

import test.annotationheaders.custom.CustomA;
import test.annotationheaders.custom.CustomA.Cardinality;

@CustomA(cardinality = Cardinality.MULTIPLE)
public interface Consumer {}


text:
using namespace std;
using namespace cv;

cameraInput::cameraInput(int num)
{
	cameraIndex = num;
	open(cameraIndex);
}

cameraInput::cameraInput()
{
	cameraInput(0);
}

cameraInput::~cameraInput()
{
}

cv::Mat cameraInput::getUndistortedImage()
{
	cv::Mat img, proc;
	read(img);
	undistort(img, proc, cameraMatrix, distCoeffs);
	return proc;
}

bool cameraInput::saveCameraProfile(string fileName)
{
	FileStorage fs(fileName, FileStorage::WRITE);
	fs << "CameraMatrix" << cameraMatrix;
	fs << "distCoeffs" << distCoeffs;
	fs << "R" << R;
	fs << "T" << T;
	return true;
}

bool cameraInput::loadCameraProfile(string fileName)
{
	FileStorage fs(fileName, FileStorage::READ);
	fs["CameraMatrix"] >> cameraMatrix;
	fs["distCoeffs"] >> distCoeffs;
	fs["R"] >> R;
	fs["T"] >> T;
	return true;
}
void cameraInput::calibrateByFiles(string fileList[], int fileNum)
{
	cv::Size chessboardSize(9, 6);
	double length = 27.0;
	vector<vector<cv::Point2f>> img_points;
	vector<vector<cv::Point3f>> obj_points;

	//cv::Mat corners[10];
	vector<cv::Point3f> objPoints;
	string oimg = "Original Image", pimg = "Processed Image";
	cv::namedWindow(oimg, cv::WINDOW_AUTOSIZE);
	cv::namedWindow(pimg, cv::WINDOW_AUTOSIZE);
	cv::moveWindow(oimg, 10, 10);
	cv::moveWindow(pimg, 660, 10);
	for (int i = 0; i < 6; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			cv::Point3f cur(j*length, i*length, 0);
			objPoints.push_back(cur);
		}
	}
	for (int i = 0; i < fileNum; i++)
	{

		cv::Mat img = cv::imread(fileList[i], 0);
		//cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
		vector<cv::Point2f> corners;
		corners.resize(54);
		bool patternFound = cv::findChessboardCorners(img, chessboardSize, cv::Mat(corners));
		if (patternFound)
		{
			cv::Size winSize(5, 5);
			cv::Size zeroZone(-1, -1);
			cv::TermCriteria criteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.001);

			/// Calculate the refined corner locations
			cornerSubPix(img, corners, winSize, zeroZone, criteria);
			cv::imshow(oimg, img);
			cv::cvtColor(img, img, cv::COLOR_GRAY2BGR);
			cv::drawChessboardCorners(img, chessboardSize, cv::Mat(corners), true);
			cv::imshow(pimg, img);
			img_points.push_back(corners);
			obj_points.push_back(objPoints);
		}
		cv::waitKey(300);
	}
	cv::calibrateCamera(obj_points, img_points, cv::Size(640, 480), cameraMatrix, distCoeffs, R, T);
	cout << "Camera Matrix:" << endl;
	cout << cameraMatrix << endl;
	cout << "Distortion:" << endl;
	cout << distCoeffs << endl;
	cout << "Rotation:" << endl;
	cout << R[0] << endl;
	cout << "Translation:" << endl;
	cout << T[0] << endl;
}

void cameraInput::calibrateByCamera()
{
	cv::Size chessboardSize(9, 6);
	double length = 1;
	vector<vector<cv::Point2f>> img_points;
	vector<vector<cv::Point3f>> obj_points;

	//cv::Mat corners[10];
	vector<cv::Point3f> objPoints;
	string oimg = "Original Image", pimg = "Processed Image";
	cv::namedWindow(oimg, cv::WINDOW_AUTOSIZE);
	cv::namedWindow(pimg, cv::WINDOW_AUTOSIZE);
	cv::moveWindow(oimg, 10, 10);
	cv::moveWindow(pimg, 660, 10);
	for (int i = 0; i < 6; i++)
	{
		for (int j = 0; j < 9; j++)
		{
			cv::Point3f cur(j*length, i*length, 0);
			objPoints.push_back(cur);
		}
	}
	while (true)
	{
		cv::Mat img;
		read(img);
		cv::imshow("Input", img);
		char ch = cv::waitKey(30);
		if (ch == ' ')
		{
			cv::cvtColor(img, img, cv::COLOR_BGR2GRAY);
			vector<cv::Point2f> corners;
			corners.resize(54);
			bool patternFound = cv::findChessboardCorners(img, chessboardSize, cv::Mat(corners));
			if (patternFound)
			{
				cv::Size winSize(5, 5);
				cv::Size zeroZone(-1, -1);
				cv::TermCriteria criteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.001);

				/// Calculate the refined corner locations
				cornerSubPix(img, corners, winSize, zeroZone, criteria);
				cv::imshow(oimg, img);
				cv::cvtColor(img, img, cv::COLOR_GRAY2BGR);
				cv::drawChessboardCorners(img, chessboardSize, cv::Mat(corners), true);
				cv::imshow(pimg, img);
				img_points.push_back(corners);
				obj_points.push_back(objPoints);
			}
		}
		if (ch == 27)
		{
			break;
		}
	}
	cv::calibrateCamera(obj_points, img_points, cv::Size(640, 480), cameraMatrix, distCoeffs, R, T);
	cout << "Camera Matrix:" << endl;
	cout << cameraMatrix << endl;
	cout << "Distortion:" << endl;
	cout << distCoeffs << endl;
	cout << "Rotation:" << endl;
	cout << R[0] << endl;
	cout << "Translation:" << endl;
	cout << T[0] << endl;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FPVR
{
    /// <summary>
    /// Defines the different types of vehicle.
    /// </summary>
    public enum VehicleType
    {
        Unknown,
        Drone,
        Plane,
        Helicopter,
        Car,
        Truck,
        Boat,
        Hovercraft,
        Other
    };

    /// <summary>
    /// Provides information about a specific vehicle.
    /// </summary>
    public class VehicleInfo
    {
        /// <summary>
        /// Gets or sets an ID for the vehicle that is unique to the provider.
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the 3D model name, if any, that can be used to represent the vehicle.
        /// </summary>
        public string ModelName { get; set; }

        /// <summary>
        /// Gets or sets the name of the vehicle.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the provider that contains the vehicle.
        /// </summary>
        public IVehicleProvider Provider { get; set; }

        /// <summary>
        /// Gets or set the general type of the vehicle.
        /// </summary>
        public VehicleType Type { get; set; }
    }
}


text:
package com.viewer.model;

public class GetImageUrlsParameters extends WatermarkedDocumentParameters {
	public Integer width = null;
	public int firstPage;
	public Integer pageCount = null;
	public Integer quality = null;
	public Boolean usePdf;
	public Boolean ignoreDocumentAbsence;
	public Boolean useHtmlBasedEngine;
	public Boolean supportPageRotation;
	public String instanceIdToken;
	public String locale;
	public String callBack;

	public Integer getWidth() {
		return width;
	}

	public void setWidth(Integer width) {
		this.width = width;
	}

	public int getFirstPage() {
		return firstPage;

	}

	public void serFirstPage(int firstPage) {
		this.firstPage = firstPage;
	}

	public Integer getPageCount() {
		return pageCount;
	}

	public void setPageCount(Integer pageCount) {
		this.pageCount = pageCount;
	}

	public Integer getQuality() {
		return quality;
	}

	public void setQuality(Integer quality) {
		this.quality = quality;
	}

	public Boolean getUsePdf() {
		return usePdf;

	}

	public void setUsePdf(Boolean usePdf) {
		this.usePdf = usePdf;

	}
	////////////

	public void setCallBack(String callBack) {
		this.callBack = callBack;
	}

	public String getCallBack() {
		return callBack;
	}

	public void setLocale(String locale) {
		this.locale = locale;
	}

	public String getLocale() {
		return locale;
	}

	public void setInstanceIdToken(String instanceIdToken) {
		this.instanceIdToken = instanceIdToken;
	}

	public String getInstanceIdToken() {
		return instanceIdToken;
	}

	public void setSupportPageRotation(Boolean supportPageRotation) {
		this.supportPageRotation = supportPageRotation;
	}

	public Boolean getSupportPageRotation() {
		return supportPageRotation;
	}

	public void setUseHtmlBasedEngine(Boolean useHtmlBasedEngine) {
		this.useHtmlBasedEngine = useHtmlBasedEngine;
	}

	public Boolean getUseHtmlBasedEngine() {
		if(useHtmlBasedEngine == null)
			return false;
		return useHtmlBasedEngine;
	}

	public void setIgnoreDocumentAbsence(Boolean ignoreDocumentAbsence) {
		this.ignoreDocumentAbsence = ignoreDocumentAbsence;
	}

	public Boolean getIgnoreDocumentAbsence() {
		return false;
	}

}


text:
#import "JCSLocalization.h"

#define DEFINE_SHARED_INSTANCE_USING_BLOCK(block) \
  static dispatch_once_t pred = 0; \
  __strong static id _sharedObject = nil; \
  dispatch_once(&pred, ^{ \
    _sharedObject = block(); \
  }); \
  return _sharedObject; \

@interface JCSLocalization ()

@property (nonatomic, strong) NSBundle *languageBundle;

@end

@implementation JCSLocalization

+ (JCSLocalization *)sharedInstance {
    DEFINE_SHARED_INSTANCE_USING_BLOCK(^{
        return [[JCSLocalization alloc] initSingleton];
    });
}

- (id)init {
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:[NSString stringWithFormat:@"You must use [%@ %@] instead",
                                                                     NSStringFromClass([self class]),
                                                                     NSStringFromSelector(@selector(sharedInstance))]
                                 userInfo:nil];
    return nil;
}

- (id)initSingleton {
    self = [super init];

    if (self) {

    }

    return self;
}

- (NSString *)localizedStringForKey:(NSString *)key {
    return NSLocalizedStringFromTableInBundle(key, @"", [self languageBundle], nil);
}

- (NSBundle *)languageBundle {
    if (_languageBundle) {
        return _languageBundle;
    }

    if (!self.forcedLocale) {
        [self setForcedLocale:[NSLocale systemLocale]];
    }

    NSString *languageCode = [self.forcedLocale objectForKey:NSLocaleLanguageCode];
    NSBundle *bundle = [self loadLanguageBundleWithCode:languageCode];

    if (!bundle) {
        bundle = [self loadLanguageBundleWithCode:@"en"];
    }

    [self setLanguageBundle:bundle];

    return bundle;
}

- (NSBundle *)loadLanguageBundleWithCode:(NSString *)languageCode {
    return [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:languageCode ofType:@"lproj"]];
}

@end


text:
const { not } = require("../lib");

describe("not", () => {
  test("returns the ! value of the argument", () => {
    expect(not(true)).toBe(false);
    expect(not()).toBe(true);
    expect(not(false)).toBe(true);
  });
});


text:
package fixed;

import static org.junit.Assert.*;

import org.junit.Test;

public class SeminarV6bTest {

	private static final double DELTA = 0.001;

	private static final int DEFAULT_NET_PRICE = 500;

	@Test
	public void test_a_tax_free_seminar_should_return_a_gross_price_without_tax() {
		final Seminar seminar = createSeminar();
		seminar.setTaxFree(true);
		assertEquals(DEFAULT_NET_PRICE, seminar.grossPrice(), DELTA);
	}

	@Test
	public void test_a_not_tax_free_seminar_should_return_gross_price_with_correct_tax() {
		final Seminar seminar = createSeminar();
		seminar.setTaxFree(false);
		assertEquals(DEFAULT_NET_PRICE * Seminar.TAX_RATE, seminar.grossPrice(), DELTA);
	}

	@Test
	public void test_a_3letter_seminar_should_return_a_gross_price_with_discount() {
		final Seminar seminar = createSeminar();
		seminar.setName("OOP");
		assertEquals(DEFAULT_NET_PRICE - DEFAULT_NET_PRICE * Seminar.THREE_LETTER_DISCOUNT_RATE / 100, seminar.grossPrice(), DELTA);
	}

	@Test
	public void test_a_more_letters_seminar_should_return_a_net_price_without_discount() {
		final Seminar seminar = createSeminar();
		seminar.setName("OOP");
		seminar.setTaxFree(false);
		assertEquals((DEFAULT_NET_PRICE - DEFAULT_NET_PRICE * Seminar.THREE_LETTER_DISCOUNT_RATE / 100) * Seminar.TAX_RATE, seminar.grossPrice(), DELTA);
	}

	private static Seminar createSeminar() {
		return new Seminar("Object Oriented Programming", DEFAULT_NET_PRICE, true);
	}
}


text:
Monte Carlo password checking, as described in the
[ACM CCS 2015 paper](http://www.eurecom.fr/~filippon/Publications/ccs15.pdf)
by Matteo Dell'Amico and Maurizio Filippone.

Copyright 2016 Symantec Corporation

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0]

## Write me to get more info!

Very limited documentation right now -- sorry!  If you want to use
this write me (matteo_dellamico@symantec.com) and I'll add docs to
help you do what you need. There's plenty of stuff to help scalability
and persist models; my plan is to write documentation if somebody is
interested in this.

## Dependencies

Python 3 and Numpy (for Python 3, of course!)

## How to Use

Well, if you just want something simple then create a training text
with passwords (repeat passwords that happen more than once!), and
just run example.py. The first argument is the password file; the
program will get passwords to evaluate from standard input (one per
line), and will output the strength estimation (in terms of guesses
needed) with different attack models in a CSV format.

For example, using John the Ripper's password.lst file as training
set, here's a test of "mypassword42"'s strength:

```
$ echo mypassword42 | ./example.py /usr/share/john/password.lst
password,2-gram,3-gram,4-gram,5-gram,Backoff,PCFG
mypassword42,7.24304921617e+15,4.47184963775e+49,1.11128546873e+13,2806031917.0,7.95632951796e+13,4.09424936607e+36
```

For anything more complex, just ask and I'll update the documentation!


text:
<?xml version="1.0" encoding="UTF-8"?>
<UnitTestSuiteConfig xmlns="http://zstack.org/schema/zstack" timeout="120">
	<TestCase class="org.zstack.test.storage.volume.TestCreateDataVolume"/>
    <TestCase class="org.zstack.test.storage.volume.TestCreateDataVolume2"/>
    <TestCase class="org.zstack.test.storage.volume.TestCreateDataVolume3"/>
    <TestCase class="org.zstack.test.storage.volume.TestCreateDataVolume4"/>
    <TestCase class="org.zstack.test.storage.volume.TestCreateDataVolume5"/>
	<TestCase class="org.zstack.test.storage.volume.TestDeleteDataVolume"/>
	<TestCase class="org.zstack.test.storage.volume.TestQueryVolume"/>
    <TestCase class="org.zstack.test.storage.volume.TestDataVolumeGetCandidateVm"/>
    <TestCase class="org.zstack.test.storage.volume.TestDataVolumeGetCandidateVm1"/>
    <TestCase class="org.zstack.test.storage.volume.TestVmGetAttachableVolume"/>
    <TestCase class="org.zstack.test.storage.volume.TestVmGetAttachableVolume1"/>
    <TestCase class="org.zstack.test.storage.volume.TestGetVolumeFormat"/>
    <TestCase class="org.zstack.test.storage.volume.TestUpdateVolume"/>
    <TestCase class="org.zstack.test.storage.volume.TestPolicyForVolume"/>
</UnitTestSuiteConfig>


text:
.. _trainable-docs:

.. TODO: these "basic" sections before the actual API docs start don't really belong here. Then again, the function
    API does not really have a signature to just describe.
.. TODO: Reusing actors and advanced resources allocation seem ill-placed.

Training (tune.Trainable, session.report)
==========================================

Training can be done with either a **Function API** (:ref:`session.report <tune-function-docstring>`) or **Class API** (:ref:`tune.Trainable <tune-trainable-docstring>`).

For the sake of example, let's maximize this objective function:

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __example_objective_start__
    :end-before: __example_objective_end__

.. _tune-function-api:

Function API
------------

The Function API allows you to define a custom training function that Tune will run in parallel Ray actor processes,
one for each Tune trial.

With the Function API, you can report intermediate metrics by simply calling ``session.report`` within the function.

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __function_api_report_intermediate_metrics_start__
    :end-before: __function_api_report_intermediate_metrics_end__

.. tip:: Do not use ``session.report`` within a ``Trainable`` class.

In the previous example, we reported on every step, but this metric reporting frequency
is configurable. For example, we could also report only a single time at the end with the final score:

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __function_api_report_final_metrics_start__
    :end-before: __function_api_report_final_metrics_end__

It's also possible to return a final set of metrics to Tune by returning them from your function:

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __function_api_return_final_metrics_start__
    :end-before: __function_api_return_final_metrics_end__

You'll notice that Ray Tune will output extra values in addition to the user reported metrics,
such as ``iterations_since_restore``. See :ref:`tune-autofilled-metrics` for an explanation/glossary of these values.

.. _tune-function-checkpointing:

Function API Checkpointing
~~~~~~~~~~~~~~~~~~~~~~~~~~

Many Tune features rely on checkpointing, including the usage of certain Trial Schedulers and fault tolerance.
You can save and load checkpoints in Ray Tune in the following manner:

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __function_api_checkpointing_start__
    :end-before: __function_api_checkpointing_end__

.. note:: ``checkpoint_frequency`` and ``checkpoint_at_end`` will not work with Function API checkpointing.

In this example, checkpoints will be saved by training iteration to ``<local_dir>/<exp_name>/trial_name/checkpoint_<step>``.

Tune also may copy or move checkpoints during the course of tuning. For this purpose,
it is important not to depend on absolute paths in the implementation of ``save``.

See :ref:`here for more information on creating checkpoints <air-checkpoint-ref>`.
If using framework-specific trainers from Ray AIR, see :ref:`here <air-trainer-ref>` for
references to framework-specific checkpoints such as `TensorflowCheckpoint`.

.. _tune-class-api:

Trainable Class API
-------------------

.. caution:: Do not use ``session.report`` within a ``Trainable`` class.

The Trainable **class API** will require users to subclass ``ray.tune.Trainable``. Here's a naive example of this API:

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __class_api_example_start__
    :end-before: __class_api_example_end__

As a subclass of ``tune.Trainable``, Tune will create a ``Trainable`` object on a
separate process (using the :ref:`Ray Actor API <actor-guide>`).

  1. ``setup`` function is invoked once training starts.
  2. ``step`` is invoked **multiple times**.
     Each time, the Trainable object executes one logical iteration of training in the tuning process,
     which may include one or more iterations of actual training.
  3. ``cleanup`` is invoked when training is finished.

.. tip:: As a rule of thumb, the execution time of ``step`` should be large enough to avoid overheads
    (i.e. more than a few seconds), but short enough to report progress periodically (i.e. at most a few minutes).

You'll notice that Ray Tune will output extra values in addition to the user reported metrics,
such as ``iterations_since_restore``.
See :ref:`tune-autofilled-metrics` for an explanation/glossary of these values.

.. _tune-trainable-save-restore:

Class API Checkpointing
~~~~~~~~~~~~~~~~~~~~~~~

You can also implement checkpoint/restore using the Trainable Class API:

.. literalinclude:: /tune/doc_code/trainable.py
    :language: python
    :start-after: __class_api_checkpointing_start__
    :end-before: __class_api_checkpointing_end__

You can checkpoint with three different mechanisms: manually, periodically, and at termination.

**Manual Checkpointing**: A custom Trainable can manually trigger checkpointing by returning ``should_checkpoint: True``
(or ``tune.result.SHOULD_CHECKPOINT: True``) in the result dictionary of `step`.
This can be especially helpful in spot instances:

.. code-block:: python

    def step(self):
        # training code
        result = {"mean_accuracy": accuracy}
        if detect_instance_preemption():
            result.update(should_checkpoint=True)
        return result

**Periodic Checkpointing**: periodic checkpointing can be used to provide fault-tolerance for experiments.
This can be enabled by setting ``checkpoint_frequency=<int>`` and ``max_failures=<int>`` to checkpoint trials
every *N* iterations and recover from up to *M* crashes per trial, e.g.:

.. code-block:: python

    tuner = tune.Tuner(
        my_trainable,
        run_config=air.RunConfig(
            checkpoint_config=air.CheckpointConfig(checkpoint_frequency=10),
            failure_config=air.FailureConfig(max_failures=5))
    )
    results = tuner.fit()

**Checkpointing at Termination**: The checkpoint_frequency may not coincide with the exact end of an experiment.
If you want a checkpoint to be created at the end of a trial, you can additionally set the ``checkpoint_at_end=True``:

.. code-block:: python
   :emphasize-lines: 5

    tuner = tune.Tuner(
        my_trainable,
        run_config=air.RunConfig(
            checkpoint_config=air.CheckpointConfig(checkpoint_frequency=10, checkpoint_at_end=True),
            failure_config=air.FailureConfig(max_failures=5))
    )
    results = tuner.fit()

Use ``validate_save_restore`` to catch ``save_checkpoint``/``load_checkpoint`` errors before execution.

.. code-block:: python

    from ray.tune.utils import validate_save_restore

    # both of these should return
    validate_save_restore(MyTrainableClass)
    validate_save_restore(MyTrainableClass, use_object_store=True)

Advanced: Reusing Actors
~~~~~~~~~~~~~~~~~~~~~~~~

.. note:: This feature is only for the Trainable Class API.

Your Trainable can often take a long time to start.
To avoid this, you can do ``tune.TuneConfig(reuse_actors=True)`` (which is taken in by ``Tuner``) to reuse the same Trainable Python process and
object for multiple hyperparameters.

This requires you to implement ``Trainable.reset_config``, which provides a new set of hyperparameters.
It is up to the user to correctly update the hyperparameters of your trainable.

.. code-block:: python

    class PytorchTrainble(tune.Trainable):
        """Train a Pytorch ConvNet."""

        def setup(self, config):
            self.train_loader, self.test_loader = get_data_loaders()
            self.model = ConvNet()
            self.optimizer = optim.SGD(
                self.model.parameters(),
                lr=config.get("lr", 0.01),
                momentum=config.get("momentum", 0.9))

        def reset_config(self, new_config):
            for param_group in self.optimizer.param_groups:
                if "lr" in new_config:
                    param_group["lr"] = new_config["lr"]
                if "momentum" in new_config:
                    param_group["momentum"] = new_config["momentum"]

            self.model = ConvNet()
            self.config = new_config
            return True

Comparing the Function API and Class API
----------------------------------------

Here are a few key concepts and what they look like for the Function and Class API's.

======================= =============================================== ==============================================
Concept                 Function API                                    Class API
======================= =============================================== ==============================================
Training Iteration      Increments on each `session.report` call        Increments on each `Trainable.step` call
Report  metrics         `session.report(metrics)`                       Return metrics from `Trainable.step`
Saving a checkpoint     `session.report(..., checkpoint=checkpoint)`    `Trainable.save_checkpoint`
Loading a checkpoint    `session.get_checkpoint()`                      `Trainable.load_checkpoint`
Accessing config        Passed as an argument `def train_func(config):` Passed through `Trainable.setup`
======================= =============================================== ==============================================

Advanced Resource Allocation
----------------------------

Trainables can themselves be distributed. If your trainable function / class creates further Ray actors or tasks
that also consume CPU / GPU resources, you will want to add more bundles to the :class:`PlacementGroupFactory`
to reserve extra resource slots.
For example, if a trainable class requires 1 GPU itself, but also launches 4 actors, each using another GPU,
then you should use this:

.. code-block:: python
   :emphasize-lines: 4-10

    tuner = tune.Tuner(
        tune.with_resources(my_trainable, tune.PlacementGroupFactory([
            {"CPU": 1, "GPU": 1},
            {"GPU": 1},
            {"GPU": 1},
            {"GPU": 1},
            {"GPU": 1}
        ])),
        run_config=air.RunConfig(name="my_trainable")
    )

The ``Trainable`` also provides the ``default_resource_requests`` interface to automatically
declare the resources per trial based on the given configuration.

It is also possible to specify memory (``"memory"``, in bytes) and custom resource requirements.

.. _tune-function-docstring:

session (Function API)
----------------------

.. autofunction:: ray.air.session.report
    :noindex:

.. autofunction:: ray.air.session.get_checkpoint
    :noindex:

.. autofunction:: ray.air.session.get_trial_name
    :noindex:

.. autofunction:: ray.air.session.get_trial_id
    :noindex:

.. autofunction:: ray.air.session.get_trial_resources
    :noindex:

.. autofunction:: ray.air.session.get_trial_dir
    :noindex:

.. _tune-trainable-docstring:

tune.Trainable (Class API)
--------------------------

.. autoclass:: ray.tune.Trainable
    :member-order: groupwise
    :private-members:
    :members:

.. _tune-util-ref:

Utilities
---------

.. autofunction:: ray.tune.utils.wait_for_gpu

.. autofunction:: ray.tune.utils.diagnose_serialization

.. autofunction:: ray.tune.utils.validate_save_restore

.. _tune-with-parameters:

tune.with_parameters
--------------------

.. autofunction:: ray.tune.with_parameters


text:
class FrameLimiter{
private:
  double TLastDraw;
  double TLastOverShoot;
  double desired_fps;
  bool was_init;
  Timer timer;
public:

  FrameLimiter() {
    was_init=false;
  };

  //init needs to be called *once* with the desired framerate
  void init(double fps) {
    desired_fps=fps;
    TLastDraw=timer.midtime();
    TLastOverShoot=timer.midtime();
    timer.start();
    was_init=true;
  };

  ~FrameLimiter() {};

  //waitForNextFrame() should be called each time right before the buffer switch
  void waitForNextFrame() {
    if (was_init==false) {
      printf("Need to call init() first before waitForNextFrame()\n");
    }
    // Wait if we are ahead of the desired framerate
    double waiting=1.0 / desired_fps;
    double curtime=timer.midtime();
    double diff=waiting-(curtime-TLastDraw);
    if (diff > 0) {
    //Compensate for any previous sluggish Frames:
      if (TLastOverShoot > 0 && TLastOverShoot < diff) diff-=TLastOverShoot;
      if (diff > waiting) diff=waiting;
      usleep((unsigned long)(diff*1.0E6));
    }
    TLastDraw=timer.midtime();
    TLastOverShoot=(TLastDraw-curtime)-diff;
  };
};

#endif


text:
namespace DKFoundation
{
	/// @brief Create writable memory object from URL or other stream, memory object.
	/// provide compression, base64-encoding functionality.
	/// thread safe.
	///
	/// @note
	///  Encode means 'encode with base64' in this class
	class DKGL_API DKBuffer : public DKData
	{
	public:
		DKBuffer(DKAllocator& alloc = DKAllocator::DefaultAllocator());
		DKBuffer(const DKData* p, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		/// if p is NULL, an empty buffer with given length will be created.
		DKBuffer(const void* p, size_t s, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		DKBuffer(const DKBuffer&);
		DKBuffer(DKBuffer&&);
		~DKBuffer();

		size_t Length() const override;
		size_t CopyContents(void* p, size_t offset, size_t length) const;

		bool SetLength(size_t);

		/// compress / decompress data
		DKObject<DKBuffer> Compress(const DKCompressor&, DKAllocator& alloc = DKAllocator::DefaultAllocator()) const;
		DKObject<DKBuffer> Decompress(DKAllocator& alloc = DKAllocator::DefaultAllocator()) const;
		static DKObject<DKBuffer> Compress(const DKCompressor&, const void* p, size_t len, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		static DKObject<DKBuffer> Decompress(const void* p, size_t len, DKAllocator& alloc = DKAllocator::DefaultAllocator());

		/// base64 encode / decode
		bool Base64Encode(DKStringU8& strOut) const;
		bool Base64Encode(DKStringW& strOut) const;
		static DKObject<DKBuffer> Base64Decode(const DKStringU8& str, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		static DKObject<DKBuffer> Base64Decode(const DKStringW& str, DKAllocator& alloc = DKAllocator::DefaultAllocator());

		/// create object from file or URL.
		static DKObject<DKBuffer> Create(const DKString& url, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		static DKObject<DKBuffer> Create(const void* p, size_t s, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		static DKObject<DKBuffer> Create(const DKData* p, DKAllocator& alloc = DKAllocator::DefaultAllocator());
		static DKObject<DKBuffer> Create(DKStream* s, DKAllocator& alloc = DKAllocator::DefaultAllocator());

		size_t SetContents(const void* p, size_t s); ///< create zero-fill buffer if p is NULL.
		size_t SetContents(const DKData* p);

		DKBuffer& operator = (const DKBuffer&);
		DKBuffer& operator = (DKBuffer&&);

		bool IsReadable() const override { return true; }
		bool IsWritable() const	override { return true; }
		bool IsExcutable() const override { return false; }
		bool IsTransient() const override { return false; }

		void SwitchAllocator(DKAllocator& alloc);
		DKAllocator& Allocator() const;

		const void* Contents() const override;
		void* MutableContents() override;

	private:
		void*	contentsPtr;
		size_t	contentsLength;
		DKAllocator* allocator;
	};
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TrelloMailer.Win.Controllers;
using TrelloNet;

namespace TrelloMailer.Win.Actions
{
    public class LoadCardAction : AbstractAction<MainController>
    {

        public LoadCardAction(MainController mainController)
            : base(mainController)
        {

        }
        public override bool AutoLock
        {
            get { return true; }
        }

        protected override void BeforeRun(object arg)
        {
            base.BeforeRun(arg);
            controller.View.TreeViewBoards.Enabled = false;
            controller.View.toolStripStatusLabel1.Text = "Loading cards ...";
        }

        protected override void OnDoWork(System.ComponentModel.DoWorkEventArgs e)
        {
            base.OnDoWork(e);
            List list = e.Argument as List;
            if (list != null)
            {
                if (list.Cards.Count == 0)
                {
                    this.controller.TrelloSerivce.LoadCards(this, list);
                }
                e.Result = list.Cards;
            }
        }

        protected override void OnRunWorkerCompleted(System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            base.OnRunWorkerCompleted(e);
            this.controller.View.ListViewCards.Items.Clear();
            if (e.Result != null)
            {

                List<Card> cards = e.Result as List<Card>;
                foreach (var c in cards)
                {
                    ListViewItem item = new ListViewItem(new string[]
                    {
                        c.Name,
                        c.Due.HasValue?c.Due.Value.ToString(): "-",
                        string.Join<Member>(",", c.Members),
                        string.Join<Card.Label>(",", c.Labels )
                    });
                    item.Tag = c;
                    controller.View.ListViewCards.Items.Add(item);

                }
                controller.View.ListViewCards.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            }
            controller.View.TreeViewBoards.Enabled = true;
            controller.View.toolStripStatusLabel1.Text = "Done";

        }

    }
}


text:
package citrus.util;

import citrus.type.SchemeObject;
import citrus.type.SchemeList;
import citrus.type.Null;
import citrus.type.Pair;

public class List {
    public static SchemeList list(SchemeObject ... elements) {
        SchemeList l = new Null();
        for(int i = 0; i < elements.length; i++) {
            l = new Pair(elements[i], l);
        }
        return reverse(l);
    }

    public static SchemeObject first(SchemeObject list) {
        return list.car();
    }

    public static SchemeObject second(SchemeObject list) {
        return list.cdr().car();
    }

    public static SchemeObject third(SchemeObject list) {
        return list.cdr().cdr().car();
    }

    public static SchemeList reverse(SchemeList list) {
        SchemeList prevTail = new Null();
        while(!list.isNull()) {
            Pair p = Pair.of(list);
            SchemeList tmp = SchemeList.of(p.tail);
            p.tail = prevTail;
            prevTail = list;
            list = tmp;
        }
        return prevTail;
    }

    public static int length(SchemeObject list) {
        int count = 0;
        while(!list.isNull()) {
            list = list.cdr();
            count++;
        }
        return count;
    }
}


text:
/* eslint-disable jsx-a11y/label-has-for */
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';

import Input from './Input';

const labeledInput = (type) => (

{type}

    <Input id={type} type={type} onChange={action('onChange')} value="" />

);

storiesOf('Input', module)
  .add('base', () => <Input onChange={action('onChange')} value="some text" />)
  .add('disabled', () => <Input onChange={action('onChange')} disabled value="some text" />)
  .add('invalid', () => <Input onChange={action('onChange')} invalid value="some text" />)
  .add('different types', () => (

      {['text', 'number', 'date', 'email', 'phone', 'search', 'password'].map(labeledInput)}

  ));


text:
package org.gradle.api.internal.externalresource.metadata;

import org.gradle.api.Nullable;
import org.gradle.internal.Factory;

import java.util.Date;

public abstract class ExternalResourceMetaDataCompare {
    public static boolean isDefinitelyUnchanged(@Nullable ExternalResourceMetaData local, Factory<ExternalResourceMetaData> remoteFactory) {
        if (local == null) {
            return false;
        }

        String localEtag = local.getEtag();

        Date localLastModified = local.getLastModified();
        if (localEtag == null && localLastModified == null) {
            return false;
        }

        long localContentLength = local.getContentLength();
        if (localEtag == null && localContentLength < 1) {
            return false;
        }

        // We have enough local data to make a comparison, get the remote metadata
        ExternalResourceMetaData remote = remoteFactory.create();
        if (remote == null) {
            return false;
        }

        String remoteEtag = remote.getEtag();
        if (localEtag != null && remoteEtag != null) {
            return localEtag.equals(remoteEtag);
        }

        Date remoteLastModified = remote.getLastModified();
        if (remoteLastModified == null) {
            return false;
        }

        long remoteContentLength = remote.getContentLength();
        //noinspection SimplifiableIfStatement
        if (remoteContentLength < 1) {
            return false;
        }

        return localContentLength == remoteContentLength && remoteLastModified.equals(localLastModified);
    }
}


text:
package org.apache.flink.table.plan.rules.dataSet

import org.apache.calcite.plan.{Convention, RelOptRule, RelTraitSet}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.convert.ConverterRule
import org.apache.calcite.rel.logical.LogicalIntersect
import org.apache.flink.table.plan.nodes.dataset.{DataSetIntersect, DataSetConvention}

class DataSetIntersectRule
  extends ConverterRule(
    classOf[LogicalIntersect],
    Convention.NONE,
    DataSetConvention.INSTANCE,
    "DataSetIntersectRule")
{

  def convert(rel: RelNode): RelNode = {

    val intersect: LogicalIntersect = rel.asInstanceOf[LogicalIntersect]
    val traitSet: RelTraitSet = rel.getTraitSet.replace(DataSetConvention.INSTANCE)
    val convLeft: RelNode = RelOptRule.convert(intersect.getInput(0), DataSetConvention.INSTANCE)
    val convRight: RelNode = RelOptRule.convert(intersect.getInput(1), DataSetConvention.INSTANCE)

    new DataSetIntersect(
      rel.getCluster,
      traitSet,
      convLeft,
      convRight,
      rel.getRowType,
      intersect.all)
  }
}

object DataSetIntersectRule {
  val INSTANCE: RelOptRule = new DataSetIntersectRule
}


text:
require 'isolated_server/base'
require 'isolated_server/version'
require 'shellwords'

# Load support for databases if their corresponding gem is available
begin
  require 'mongo'
  require 'isolated_server/mongodb'
rescue LoadError
end

begin
  require 'mysql2'
  require 'isolated_server/mysql'
rescue LoadError
end

module IsolatedServer
end


text:
.class public interface abstract Lcom/google/android/gms/internal/zzef;
.super Ljava/lang/Object;

# virtual methods
.method public abstract zzaX()V
.end method

.method public abstract zzaY()V
.end method

.method public abstract zzaZ()V
.end method

.method public abstract zzba()V
.end method

.method public abstract zzbb()V
.end method


text:
#ifndef _DriverFilter_H_
#define _DriverFilter_H_

#ifdef _DEBUG
#define FILTER_NAME "SD DriverModul Debug"
#define OID_NEW_LANE_DETECTION "atdf.smartdriving.DriverFilter.debug"
#else
#define FILTER_NAME "SD DriverModul"
#define OID_NEW_LANE_DETECTION "atdf.smartdriving.DriverFilter.release"
#endif

#define PROP_NAME "ManeuverFile"

class DriverFilter : public cFilter
{
	ADTF_FILTER(OID_NEW_LANE_DETECTION, FILTER_NAME, OBJCAT_DataFilter);

private:
	// Coder description for input pins
	cObjectPtr<IMediaTypeDescription> coderDescriptionJury;
	cObjectPtr<IMediaTypeDescription> coderDescriptionDriver;
	cObjectPtr<IMediaTypeDescription> coderDescriptionManeuver;
	cObjectPtr<IMediaDescriptionManager> descriptionManager;

	// input pins
	cInputPin juryStatePin;
	cInputPin maneuverFinishedPin;

	// output pins
	cOutputPin driverStatePin;
	cOutputPin currentManeuverPin;

	// maneuver
	cFilename maneuverListFile;
	std::vector<tSector> sectorList;

	Maneuver currentManeuver;
	tInt currentManeuverId;
	tInt ddlSizeManeuver;
	tInt ddlSizeDriver;

	// stuff
	tBool isFirstTimeRun;
	tInt highestManeuverId;
	tInt stopCounter;

public:
	DriverFilter(const tChar *__info);
	virtual ~DriverFilter(void);

public:
	tResult Init(tInitStage eStage, __exception = NULL);
	tResult Start(__exception = NULL);
	tResult Stop(__exception = NULL);
	tResult Shutdown(tInitStage eStage, __exception = NULL);

	tResult OnPinEvent(IPin*, tInt, tInt, tInt, IMediaSample*);

private:
	tVoid initProperties();

	tResult initMediaType(const char *mediaTypeDescriptionName, cObjectPtr<IMediaType> &mediaType, cObjectPtr<IMediaTypeDescription> &coderDescription);
	tResult createInputPin(const char *pinName, cInputPin &pin, cObjectPtr<IMediaType> &typeSignal);
	tResult createOutputPin(const char *pinName, cOutputPin &pin, cObjectPtr<IMediaType> &typeSignal);

	tResult getManeuver(IMediaSample *mediaSample, tInt8 &actionId, tInt16 &maneuverId);
	tResult getManeuver(IMediaSample *mediaSample, tUInt16 &maneuverValue, tTimeStamp &timeStamp);

	tResult loadManeuverList();
	tVoid getHighestManeuverId(tInt &highestId);

	tResult sendError(const tInt16 &maneuverId);
	tResult sendReady(const tInt16 &maneuverId);
	tResult sendRunning(const tInt16 &maneuverId);
	tResult sendComplete(const tInt16 &maneuverId);
	tResult sendDriverState(const DriverState &driverState, const tInt16 &maneuverId);

	tBool isManeuverFinished(const tUInt16 &maneuverValue) const;

	/**
	 * @return returns true if a following maneuver exists, false otherwise
	 */
	tBool getNextManeuver(tInt &maneuverId, Maneuver &maneuver);
	tVoid getManeuverFromId(const tInt &maneuverId, Maneuver &maneuver);

	tVoid getManeuverFromString(const cString &name, Maneuver &maneuver);

	tResult sendManeuver(cOutputPin &pin, const Maneuver &maneuver);
	tResult sendManeuver(cOutputPin &pin, const Maneuver &manuever, const tTimeStamp &timeStamp);
};

#endif


text:
@implementation NSDate (MKHelpers)

- (NSString*) stringWithFormat:(NSString*)format
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:self];
}

@end