text:
'use strict';

module.exports = function (db, config) {
    return {
        login:       require('./login')(db, config),
        searchUsers: require('./searchUsers')(db, config),
        block:       require('./block')(db, config),
        sendReset:   require('./sendReset')(db, config),
        resetPwd:    require('./resetPwd')(db, config),
        getUsername: require('./getUsername')(db, config)
    };
};


text:
#
#ifndef FISX_XRF_H
#define FISX_XRF_H
#include "fisx_xrfconfig.h"
#include "fisx_elements.h"
#include <iostream>

namespace fisx
{

class XRF
{

typedef std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > > \
        expectedLayerEmissionType;
typedef std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > >::const_iterator \
        iteratorExpectedLayerEmissionType;

public:
    /*!
    Default constructor
    */
    XRF();

    /*!
    Constructor with configuration file
    */
    XRF(const std::string & configurationFile);

    /*!
    Read the configuration from file
    */
    void readConfigurationFromFile(const std::string & fileName);

    /*!
    Set the excitation beam
    */
    void setBeam(const Beam & beam);

    /*!
    Easy to wrap funtion to set the excitation beam
    \param energies Set of double values corresponding to energies (in keV) describing
           the incoming beam
    \param weight Set of weights with the relative intensity of each energy
    \param characteristic Integer flag currently ignored by fisx library
    \param divergency Beam divergency in degrees (currently ignored by fisx library)
    */
    void setBeam(const std::vector<double> & energies, \
                 const std::vector<double> & weight, \
                 const std::vector<int> & characteristic = std::vector<int>(), \
                 const std::vector<double> & divergency = std::vector<double>());

    /*!
    Funtion to set a single energy excitation beam
    \param energy Energy of the incoming beam
    */
    void setBeam(const double & energy, const double & divergency = 0.0);

    /*!
    Set the beam filters to be applied
    */
    void setBeamFilters(const std::vector<Layer> & filters);

    /*!
    Set the user beam filters to be applied
    */
    void setUserBeamFilters(const std::vector<TransmissionTable> & userFilters);

    /*!
    Set the sample description.
    It consists on a set of layers of different materials, densities and thicknesses.
    The top layer will be taken as reference layer. This can be changed calling setRefenceLayer
    */
    void setSample(const std::vector<Layer> & layers, const int & referenceLayer = 0);

    /*!
    Convenience method for single layer samples.
    */
    void setSample(const std::string & name, \
                   const double & density = 1.0, \
                   const double & thickness = 1.0);

    /*!
    Convenience method for single layer samples.
    */
    void setSample(const Layer & layer);

    /*!
    It consists on a set of layers of different materials, densities and thicknesses and
    "funny" factors.
    */
    void setAttenuators(const std::vector<Layer> & attenuators);

    /*!
    Set the user transmission tables to be applied as attenuators
    */
    void setUserAttenuators(const std::vector<TransmissionTable> & userAttenuators);

    /*!
    Set the detector. For the time being it is very simple.
    It has active area/diameter, material, density, thickness and distance.
    */
    void setDetector(const Detector & detector);

    /*!
    Set the excitation geometry.
    For the time being, just the incident, outgoing angles and scattering angle to detector
    center. A negative scattering angle of 90 degrees indicates the scattering angle is the
    sum of alphaIn and alphaOut.
    */
    void setGeometry(const double & alphaIn, const double & alphaOut,\
                      const double & scatteringAngle = -90.);

    /*!
    Set the reference layer. The detector distance is measured from the reference layer surface.
    If not specified, the layer closest to the detector
    */
    void setReferenceLayer(const int & index);
    void setRefenceLayer(const std::string & name);

    /*!
    Set the elements library to be used.
    */
    //void setElementsReference(const Elements & elements);

    /*!
    Collimators are not implemented yet. The collimators are attenuators that take into account their distance to
    the sample, their diameter, thickness and density
    */
    void setCollimators();
    void addCollimator();

    /*!
    Get the current configuration
    */
    const XRFConfig & getConfiguration() const;

    /*!
    Set the configuration
    */
    void setConfiguration(const XRFConfig & configuration);

    /*!
    Get the expected fluorescence emission coming from primary excitation per unit photon.
    It needs to be multiplied by the mass fraction and the total number of photons to get
    the actual primary fluorescence.

    The output is a map:

    Element -> Family -> Line -> energy: double, ratio: double

    */
    std::map< std::string, std::map< std::string, std::map<std::string, std::map<std::string, double> > > >\
                getExpectedPrimaryEmission(const std::vector<std::string> & elementList,
                                           const Elements & elements);

    /*!
    Get geometric efficiency term. Solid angle subtended by the detector at the sample divided by 4 * pi
    */
    double getGeometricEfficiency(const int & layerIndex = 0) const;

    /*!
    Return a complete output of the form
    [Element Family][Layer][line]["energy"] - Energy in keV of the emission line
    [Element Family][Layer][line]["primary"] - Primary rate prior to correct for detection efficiency
    [Element Family][Layer][line]["secondary"] - Secondary rate prior to correct for detection efficiency
    [Element Family][Layer][line]["rate"] - Overall rate
    [Element Family][Layer][line]["efficiency"] - Detection efficiency
    [Element Family][Layer][line][element line layer] - Secondary rate (prior to correct for detection efficiency)
    due to the fluorescence from the given element, line and layer index composing the map key.
    */
    std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > > \
                getMultilayerFluorescence(const std::string & element, \
                const Elements & elementsLibrary, const int & sampleLayerIndex = 0, \
                const std::string & lineFamily = "", const int & secondary = 0, \
                const int & useGeometricEfficiency = 1, const int & useMassFractions = 0, \
                const double & secondaryCalculationLimit = 0.0);
    /*!
    Basis method called by all the other convenience methods.
    \param elementFamilyLayer - Vector of strings. Each string represents the information we are interested on.\n
    "Cr"     - We want the information for Cr, for all line families and sample layers\n
    "Cr K"   - We want the information for Cr, for the family of K-shell emission lines, in all layers.\n
    "Cr K 0" - We want the information for Cr, for the family of K-shell emission lines, in layer 0.
    \param elementsLibrary - Instance of library to be used for all the Physical constants
    \param secondary - Flag to indicate different levels of secondary excitation to be considered.\n
                0 Means not considered\n
                1 Consider secondary excitation\n
                2 Consider tertiary excitation\n
    \param useGeometricEfficiency - Take into account solid angle or not. Default is 1 (yes)

    \param useMassFractions - If 0 (default) the output corresponds to the requested information if the mass
    fraction of the element would be one on each calculated sample layer. To get the actual signal, one
    has to multiply the rates by the actual mass fraction of the element on each sample layer.
                       If set to 1, the rate will be already corrected by the actual mass fraction.

    \return Return a complete output of the form:\n
    [Element Family][Layer][line]["energy"] - Energy in keV of the emission line\n
    [Element Family][Layer][line]["primary"] - Primary rate prior to correct for detection efficiency\n
    [Element Family][Layer][line]["secondary"] - Secondary rate prior to correct for detection efficiency\n
    [Element Family][Layer][line]["rate"] - Overall rate\n
    [Element Family][Layer][line]["efficiency"] - Detection efficiency\n
    [Element Family][Layer][line][element line layer] - Secondary rate (prior to correct for detection efficiency)
    due to the fluorescence from the given element, line and layer index composing the map key.\n
    [Element Family][Layer][line]["massFraction"] - Mass fraction of the element in the considered layer
    */
    std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > > \
                getMultilayerFluorescence(const std::vector<std::string> & elementFamilyLayer, \
                const Elements & elementsLibrary, const int & secondary = 0, \
                const int & useGeometricEfficiency = 1, \
                const int & useMassFractions = 0, \
                const double & secondaryCalculationLimit = 0.0);

    std::map<std::string, std::map<int, std::map<std::string, std::map<std::string, double> > > > \
                getMultilayerFluorescence(const std::vector<std::string> & elementList,
                                          const Elements & elementsLibrary, \
                                          const std::vector<int> & layerList, \
                                          const std::vector<std::string> &  familyList, \
                                          const int & secondary = 0, \
                                          const int & useGeometricEfficiency = 1, \
                                          const int & useMassFractions = 0, \
                                          const double & secondaryCalculationLimit = 0.0);

    double getEnergyThreshold(const std::string & elementName, const std::string & family, \
                                const Elements & elementsLibrary) const;

    /*!
    Get the beam
    */
    const Beam & getBeam() const {return this->configuration.getBeam();};

    /*!
    Get the beam filters to be applied
    */
    const std::vector<Layer> & getBeamFilters() const {return this->configuration.getBeamFilters();};

    /*!
    Get the user beam filters to be applied
    */
    const std::vector<TransmissionTable> & getUserBeamFilters() const {return this->configuration.getUserBeamFilters();};

    /*!
    Get the sample description
    */
    const std::vector<Layer> & getSample() const {return this->configuration.getSample();};

    /*!
    Get the attenuator layers
    */
    const std::vector<Layer> & getAttenuators() const {return this->configuration.getAttenuators();};

    /*!
    Get the user attenuators to be applied
    */
    const std::vector<TransmissionTable> & getUserAttenuators() const {return this->configuration.getUserAttenuators();};

    /*!
    Get the detector
    */
    const Detector & getDetector() const {return this->configuration.getDetector();};

    const double & getAlphaIn() const {return this->configuration.getAlphaIn();};
    const double & getAlphaOut() const {return this->configuration.getAlphaOut();};
    const double & getScatteringAngle() const {return this->configuration.getScatteringAngle();};
    const int & getReferenceLayer() const {return this->configuration.getReferenceLayer();};

private:
    /*!
    Reference to elements library to be used for calculations
    */
    /*!
    The internal configuration
    */
    XRFConfig configuration;

    /*!
    Some optimization flags
    */
    bool recentBeam;

    expectedLayerEmissionType lastMultilayerFluorescence;
};

} // namespace fisx

#endif // FISX_XRF_H

redpajama_set_name: RedPajamaGithub


text:
package drools

import com.mongodb.Mongo
import com.mongodb.gridfs.{GridFSDBFile, GridFS}
import com.typesafe.config.{ConfigFactory, Config}

/**
  * Created by faganpe on 18/01/2016.
  */
/*
 * Class to execute the rules
 */
class RulesExecutor (gridFSDroolsFileName: String, xlsFileName : String)  extends Serializable {

  // save the drools file locally here from MongoGridFS
//  val droolsFileLocal: DroolsFile = new DroolsFile
//  droolsFileLocal.createLocalFile(gridFSDroolsFileName, xlsFileName)

  def writeLocalFile(droolsFileSpark: String, writeLocalFile: String) {
    // setup the scala typesafe config
    val conf: Config = ConfigFactory.load
    // put the config values into variables
    val mongoServer = conf.getString("proxylog-streaming.mongoServer")
    val mongoPort = conf.getInt("proxylog-streaming.mongoPort")
    val mongo = new Mongo(mongoServer, mongoPort)
    val db = mongo.getDB("imagedb")
    val collection = db.getCollection("rulelist")

    // create a "drools" namespace
    val gfsDroolsFile = new GridFS(db, "drools")

    // get image file by it's filename
    val gridFSFileName = droolsFileSpark
    val imageForOutput: GridFSDBFile = gfsDroolsFile.findOne(gridFSFileName)

    // save it into a new image file
    imageForOutput.writeTo(writeLocalFile)

    // remove the image file from mongoDB
    //            gfsDroolsFile.remove(gfsDroolsFile.findOne(gridFSFileName));
    System.out.println("Done")

    mongo.close()
  }

  //evaluate all the rules and send the result back to
  def evalRules (incomingEvents : Iterator[ProxyLogs]) : Iterator[ProxyLogs] = {
    val ksession = KieSessionFactory.getKieSession(xlsFileName)
    val proxylogs = incomingEvents.map(patient => {
      ksession.execute(patient)
      patient
    })
    proxylogs
  }

//  def closeDroolsFileLocalMongo(): Unit = {
//    droolsFileLocal.CloseMongoConnection()
//  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Parameters that define the IP flow to be verified. */
@Fluent
public final class VerificationIpFlowParameters {
    /*
     * The ID of the target resource to perform next-hop on.
     */
    @JsonProperty(value = "targetResourceId", required = true)
    private String targetResourceId;

    /*
     * The direction of the packet represented as a 5-tuple.
     */
    @JsonProperty(value = "direction", required = true)
    private Direction direction;

    /*
     * Protocol to be verified on.
     */
    @JsonProperty(value = "protocol", required = true)
    private IpFlowProtocol protocol;

    /*
     * The local port. Acceptable values are a single integer in the range (0-65535). Support for * for the source
     * port, which depends on the direction.
     */
    @JsonProperty(value = "localPort", required = true)
    private String localPort;

    /*
     * The remote port. Acceptable values are a single integer in the range (0-65535). Support for * for the source
     * port, which depends on the direction.
     */
    @JsonProperty(value = "remotePort", required = true)
    private String remotePort;

    /*
     * The local IP address. Acceptable values are valid IPv4 addresses.
     */
    @JsonProperty(value = "localIPAddress", required = true)
    private String localIpAddress;

    /*
     * The remote IP address. Acceptable values are valid IPv4 addresses.
     */
    @JsonProperty(value = "remoteIPAddress", required = true)
    private String remoteIpAddress;

    /*
     * The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of them, then this parameter must be
     * specified. Otherwise optional).
     */
    @JsonProperty(value = "targetNicResourceId")
    private String targetNicResourceId;

    /** Creates an instance of VerificationIpFlowParameters class. */
    public VerificationIpFlowParameters() {
    }

    /**
     * Get the targetResourceId property: The ID of the target resource to perform next-hop on.
     *
     * @return the targetResourceId value.
     */
    public String targetResourceId() {
        return this.targetResourceId;
    }

    /**
     * Set the targetResourceId property: The ID of the target resource to perform next-hop on.
     *
     * @param targetResourceId the targetResourceId value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withTargetResourceId(String targetResourceId) {
        this.targetResourceId = targetResourceId;
        return this;
    }

    /**
     * Get the direction property: The direction of the packet represented as a 5-tuple.
     *
     * @return the direction value.
     */
    public Direction direction() {
        return this.direction;
    }

    /**
     * Set the direction property: The direction of the packet represented as a 5-tuple.
     *
     * @param direction the direction value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withDirection(Direction direction) {
        this.direction = direction;
        return this;
    }

    /**
     * Get the protocol property: Protocol to be verified on.
     *
     * @return the protocol value.
     */
    public IpFlowProtocol protocol() {
        return this.protocol;
    }

    /**
     * Set the protocol property: Protocol to be verified on.
     *
     * @param protocol the protocol value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withProtocol(IpFlowProtocol protocol) {
        this.protocol = protocol;
        return this;
    }

    /**
     * Get the localPort property: The local port. Acceptable values are a single integer in the range (0-65535).
     * Support for * for the source port, which depends on the direction.
     *
     * @return the localPort value.
     */
    public String localPort() {
        return this.localPort;
    }

    /**
     * Set the localPort property: The local port. Acceptable values are a single integer in the range (0-65535).
     * Support for * for the source port, which depends on the direction.
     *
     * @param localPort the localPort value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withLocalPort(String localPort) {
        this.localPort = localPort;
        return this;
    }

    /**
     * Get the remotePort property: The remote port. Acceptable values are a single integer in the range (0-65535).
     * Support for * for the source port, which depends on the direction.
     *
     * @return the remotePort value.
     */
    public String remotePort() {
        return this.remotePort;
    }

    /**
     * Set the remotePort property: The remote port. Acceptable values are a single integer in the range (0-65535).
     * Support for * for the source port, which depends on the direction.
     *
     * @param remotePort the remotePort value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withRemotePort(String remotePort) {
        this.remotePort = remotePort;
        return this;
    }

    /**
     * Get the localIpAddress property: The local IP address. Acceptable values are valid IPv4 addresses.
     *
     * @return the localIpAddress value.
     */
    public String localIpAddress() {
        return this.localIpAddress;
    }

    /**
     * Set the localIpAddress property: The local IP address. Acceptable values are valid IPv4 addresses.
     *
     * @param localIpAddress the localIpAddress value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withLocalIpAddress(String localIpAddress) {
        this.localIpAddress = localIpAddress;
        return this;
    }

    /**
     * Get the remoteIpAddress property: The remote IP address. Acceptable values are valid IPv4 addresses.
     *
     * @return the remoteIpAddress value.
     */
    public String remoteIpAddress() {
        return this.remoteIpAddress;
    }

    /**
     * Set the remoteIpAddress property: The remote IP address. Acceptable values are valid IPv4 addresses.
     *
     * @param remoteIpAddress the remoteIpAddress value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withRemoteIpAddress(String remoteIpAddress) {
        this.remoteIpAddress = remoteIpAddress;
        return this;
    }

    /**
     * Get the targetNicResourceId property: The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of
     * them, then this parameter must be specified. Otherwise optional).
     *
     * @return the targetNicResourceId value.
     */
    public String targetNicResourceId() {
        return this.targetNicResourceId;
    }

    /**
     * Set the targetNicResourceId property: The NIC ID. (If VM has multiple NICs and IP forwarding is enabled on any of
     * them, then this parameter must be specified. Otherwise optional).
     *
     * @param targetNicResourceId the targetNicResourceId value to set.
     * @return the VerificationIpFlowParameters object itself.
     */
    public VerificationIpFlowParameters withTargetNicResourceId(String targetNicResourceId) {
        this.targetNicResourceId = targetNicResourceId;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (targetResourceId() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property targetResourceId in model VerificationIpFlowParameters"));
        }
        if (direction() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property direction in model VerificationIpFlowParameters"));
        }
        if (protocol() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property protocol in model VerificationIpFlowParameters"));
        }
        if (localPort() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property localPort in model VerificationIpFlowParameters"));
        }
        if (remotePort() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property remotePort in model VerificationIpFlowParameters"));
        }
        if (localIpAddress() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property localIpAddress in model VerificationIpFlowParameters"));
        }
        if (remoteIpAddress() == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property remoteIpAddress in model VerificationIpFlowParameters"));
        }
    }

    private static final ClientLogger LOGGER = new ClientLogger(VerificationIpFlowParameters.class);
}


text:
package org.apache.lucene.codecs.cranky;

import java.io.IOException;
import java.util.Random;

import org.apache.lucene.codecs.CompoundFormat;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;

class CrankyCompoundFormat extends CompoundFormat {
  CompoundFormat delegate;
  Random random;

  CrankyCompoundFormat(CompoundFormat delegate, Random random) {
    this.delegate = delegate;
    this.random = random;
  }

  @Override
  public Directory getCompoundReader(Directory dir, SegmentInfo si, IOContext context) throws IOException {
    return delegate.getCompoundReader(dir, si, context);
  }

  @Override
  public void write(Directory dir, SegmentInfo si, IOContext context) throws IOException {
    if (random.nextInt(100) == 0) {
      throw new IOException("Fake IOException from CompoundFormat.write()");
    }
    delegate.write(dir, si, context);
  }
}


text:
module Main where

import Codec.Archive.Tar

import Codec.Compression.GZip.GUnZip (gunzip)

import qualified Data.ByteString.Lazy as BS
import Data.ByteString.Lazy (ByteString)
import Control.Monad
import Data.Bits
import Data.Char (toUpper)
import qualified Data.Set as Set
import System.Console.GetOpt
import System.Environment
import System.Exit
import System.Locale (defaultTimeLocale)
import System.IO
import System.Posix.Types (EpochTime)
import System.Time (ClockTime(..), toUTCTime, formatCalendarTime)

main :: IO ()
main = do args <- getArgs
          (opts, files) <- parseOptions args
          mainOpts opts files

parseOptions :: [String] -> IO (Options, [FilePath])
parseOptions args =
   do let (fs, files, nonopts, errs) = getOpt' RequireOrder optDescr args
      when (not (null errs)) $ die errs
      case nonopts of
        []         -> return $ (foldl (flip ($)) defaultOptions fs, files)
        ["--help"] -> usage
        _          -> die (map (("unrecognized option "++).show) nonopts)

mainOpts :: Options -> [FilePath] -> IO ()
mainOpts (Options { optAction = Nothing }) _
    = die ["No action given. Specify one of -c, -t or -x."]
mainOpts (Options { optFile = file,
                    optAction = Just action,
                    optCompression = compression,
                    optVerbose = verbose }) files =
    -- FIXME: catch errors and print out nicely
    case action of
      Create  -> recurseDirectories files
                 >>= mapM (createEntry verbose)
                 >>= output . compress compression
                         . writeTarArchive . TarArchive
      Extract -> inputEntries >>= mapM_ (extractEntry verbose)
      List    -> inputEntries >>= mapM_ (putStrLn . entryInfo verbose)
  where input  = if file == "-" then BS.getContents else BS.readFile file
        output = if file == "-" then BS.putStr      else BS.writeFile file
        inputEntries = input >>= return . readEntries files . decompress compression

compress :: Maybe Compression -> ByteString -> ByteString
compress Nothing      = id
compress (Just GZip)  = error "gzip compression is not supported yet"
compress (Just BZip2) = error "bzip2 compression is not supported yet"

decompress :: Maybe Compression -> ByteString -> ByteString
decompress Nothing      = id
decompress (Just GZip)  = gunzip
decompress (Just BZip2) = error "bzip2 decompression is not supported yet"

readEntries :: [FilePath] -> ByteString -> [TarEntry]
readEntries files = (if null files then id else keepFiles files)
                    . archiveEntries . readTarArchive

-- FIXME: allow files names to differ in trailing slashes
keepFiles :: [FilePath] -> [TarEntry] -> [TarEntry]
keepFiles files = filter (p . entryHeader)
  where p = ((`Set.member` Set.fromList files) . tarFileName)

createEntry :: Bool -> FilePath -> IO TarEntry
createEntry verbose file =
    do when verbose $ putStrLn file
       createTarEntry file

extractEntry :: Bool -> TarEntry -> IO ()
extractEntry verbose e =
    do when verbose $ putStrLn $ tarFileName $ entryHeader e
       extractTarEntry e

die :: [String] -> IO a
die errs = do mapM_ (\e -> hPutStrLn stderr $ "htar: " ++ e) $ errs
              hPutStrLn stderr "Try `htar --help' for more information."
              exitFailure

usage :: IO a
usage = do putStrLn (usageInfo hdr optDescr)
           exitWith ExitSuccess
  where hdr = unlines ["htar creates and extracts TAR archives.",
                       "",
                       "Usage: htar [OPTION ...] [FILE ...]"]

-- * Options

data Options = Options
    {
     optFile :: FilePath, -- "-" means stdin/stdout
     optAction :: Maybe Action,
     optCompression :: Maybe Compression,
     optVerbose :: Bool
    }
 deriving Show

data Action = Create
            | Extract
            | List
  deriving Show

data Compression = GZip | BZip2
  deriving Show

defaultOptions :: Options
defaultOptions = Options {
                          optFile = "-",
                          optAction = Nothing,
                          optCompression = Nothing,
                          optVerbose = False
                         }

optDescr :: [OptDescr (Options -> Options)]
optDescr =
    [
     Option ['c'] ["create"] (action Create) "Create a new archive.",
     Option ['x'] ["extract","get"] (action Extract) "Extract files.",
     Option ['t'] ["list"] (action List) "List archive contents.",
     Option ['z'] ["gzip","ungzip"] (compression GZip) "Use gzip compression.",
     Option ['j'] ["bzip2"] (compression BZip2) "Use bzip2 compression.",
     Option ['f'] ["file"] (ReqArg (\f o -> o { optFile = f}) "ARCHIVE")
            "Use archive file ARCHIVE.",
     Option ['v'] ["verbose"] (NoArg (\o -> o { optVerbose = True }))
            "Increase output verbosity."
    ]
 where action a = NoArg (\o -> o { optAction = Just a })
       compression c = NoArg (\o -> o { optCompression = Just c })

-- * Formatted information about archives

entryInfo :: Bool -- ^ Verbosity
          -> TarEntry -> String
entryInfo True  = detailedInfo . entryHeader
entryInfo False = tarFileName  . entryHeader

detailedInfo :: TarHeader -> String
detailedInfo hdr = unwords [typ:mode, owner, group, size, time, name++link]
    where typ = case tarFileType hdr of
                  TarHardLink        -> 'h'
                  TarSymbolicLink    -> 'l'
                  TarCharacterDevice -> 'c'
                  TarBlockDevice     -> 'b'
                  TarDirectory       -> 'd'
                  TarFIFO            -> 'p'
                  _                  -> '-'
          mode = concat [u,g,o]
              where m = tarFileMode hdr
                    f r w x s c = [if testBit m r then 'r' else '-',
                                   if testBit m w then 'w' else '-',
                                   if testBit m s
                                     then if testBit m x then c   else toUpper c
                                     else if testBit m x then 'x' else '-']
                    u = f 8 7 6 11 's'
                    g = f 5 4 3 10 's'
                    o = f 2 1 0  9 't'
          owner = rpad 7 ' ' $ nameOrID (tarOwnerName hdr) (tarOwnerID hdr)
          group = rpad 7 ' ' $ nameOrID (tarGroupName hdr) (tarGroupID hdr)
          nameOrID n i = if null n then show i else n
          size = lpad 11 ' ' $ show (tarFileSize hdr)
          time = formatEpochTime "%Y-%m-%d %H:%M:%S" (tarModTime hdr)
          name = tarFileName hdr
          link = case tarFileType hdr of
                   TarHardLink     -> " link to " ++ tarLinkTarget hdr
                   TarSymbolicLink -> " -> " ++ tarLinkTarget hdr
                   _               -> ""

lpad :: Int -> a -> [a] -> [a]
lpad n x xs = replicate (n - length xs) x ++ xs

rpad :: Int -> a -> [a] -> [a]
rpad n x xs = xs ++ replicate (n - length xs) x

formatEpochTime :: String -> EpochTime -> String
formatEpochTime f =
    formatCalendarTime defaultTimeLocale f . toUTCTime . epochTimeToClockTime

epochTimeToClockTime :: EpochTime -> ClockTime
epochTimeToClockTime e = TOD s (truncate (1000000000 * f))
    where (s,f) = properFraction (toRational e)


text:
<?xml version='1.0' encoding='utf-8'?>
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you 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.
  -->

<Server port="8005" shutdown="SHUTDOWN">

  <Service className="org.wso2.carbon.tomcat.ext.service.ExtendedStandardService" name="Catalina">

    <!--
	optional attributes:

	proxyPort="80"
    -->
    <Connector  protocol="org.apache.coyote.http11.Http11NioProtocol"
                port="9763"
                redirectPort="9443"
                bindOnInit="false"
                maxHttpHeaderSize="8192"
                acceptorThreadCount="2"
                maxThreads="250"
                minSpareThreads="50"
                disableUploadTimeout="false"
                connectionUploadTimeout="120000"
                maxKeepAliveRequests="200"
                acceptCount="200"
                server="WSO2 Carbon Server"
                compression="on"
                compressionMinSize="2048"
                noCompressionUserAgents="gozilla, traviata"
                compressableMimeType="text/html,text/javascript,application/x-javascript,application/javascript,application/xml,text/css,application/xslt+xml,text/xsl,image/gif,image/jpg,image/jpeg"
                URIEncoding="UTF-8"/>

    <!--
	optional attributes:

	proxyPort="443"
    -->
    <Connector  protocol="org.apache.coyote.http11.Http11NioProtocol"
                port="9443"
                bindOnInit="false"
                sslEnabledProtocols="TLSv1,TLSv1.1,TLSv1.2"
                maxHttpHeaderSize="8192"
                acceptorThreadCount="2"
                maxThreads="250"
                minSpareThreads="50"
                disableUploadTimeout="false"
                enableLookups="false"
                connectionUploadTimeout="120000"
                maxKeepAliveRequests="200"
                acceptCount="200"
                server="WSO2 Carbon Server"
                clientAuth="false"
                compression="on"
                scheme="https"
                secure="true"
                SSLEnabled="true"
				keystoreFile="${carbon.home}/repository/resources/security/wso2carbon.jks"
				keystorePass="wso2carbon"
                compressionMinSize="2048"
                noCompressionUserAgents="gozilla, traviata"
                compressableMimeType="text/html,text/javascript,application/x-javascript,application/javascript,application/xml,text/css,application/xslt+xml,text/xsl,image/gif,image/jpg,image/jpeg"
                URIEncoding="UTF-8"/>

    <Engine name="Catalina" defaultHost="localhost">

      <!--Realm className="org.apache.catalina.realm.MemoryRealm" pathname="${carbon.home}/repository/conf/tomcat/tomcat-users.xml"/-->

      <Realm className="org.wso2.carbon.tomcat.ext.realms.CarbonTomcatRealm"/>

      <Host name="localhost" unpackWARs="true" deployOnStartup="false" autoDeploy="false" appBase="${carbon.home}/repository/deployment/server/webapps/">
          <Valve className="org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve"/>
          <Valve className="org.apache.catalina.valves.AccessLogValve" directory="${carbon.home}/repository/logs"
               prefix="http_access_management_console_" suffix=".log"
               pattern="combined" />
          <Valve className="org.wso2.carbon.ui.valve.CSRFValve"/>
          <Valve className="org.wso2.carbon.ui.valve.XSSValve"/>

          <Valve className="org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve" threshold="600"/>
          <Valve className="org.wso2.carbon.tomcat.ext.valves.CompositeValve"/>
          <!--<Valve className="org.wso2.carbon.integrator.core.IntegratorValve"/>-->
      </Host>
    </Engine>
  </Service>
</Server>


text:
using System.Collections.Generic;

namespace Raml.Parser.Expressions
{
    public class QueryString
    {
        public QueryString()
        {
            Examples = new Dictionary<string, string>();
            Type = new string[0];
        }

        public IDictionary<string, string> Examples { get; set; }
        public string DisplayName { get; set; }
        public string[] Type { get; set; }
    }
}


text:
LaTeX and script files for creating my daily planner.

I use this daily planner to keep track of my daily occupations. I use `Schedule` column to mark occupations with definite dates. `i` and `ii` columns are back up columns for events of longer period such as a bus trip or an 24 hour event. `Bullets` section is to be filled with [Bullet Journal](http://www.bulletjournal.com/) style check-boxes and bullets.

## How can I use it?
Edit the parameters in [config.json](config.json) and run `daily_planner.py`.

```
sudo pip3 install -r requirements.txt
python3 daily_planner.py && open output.pdf
```

### Dependencies
 - Python 3
 - TexLive or MikTeX. Comes with `pdflatex` command line tool. (Included in MacTeX)

## How it works?
It has a one page LaTeX file that needs a `jobname` file to get its `date` string. This string is the title of the page.

The script generates human readable dates between given two dates and writes them in individual `jobname` files in `temp` directory. Then, it runs `pdflatex` for each of these generated date strings and generates corresponding PDF files in the same directory. Finally, it merges these pdf files into one and removes the `temp` directory.

## License
[MIT](LICENSE).


text:
layout: page-fullwidth
title: "Các tiểu dự án Javascript"
subheadline: "Mini Javascript"
teaser: "Kết hợp giữa HTML, CSS, Javascript & JqueryJquery cùng một vài thuật toán cơ sở khác! Các dự án được xây dựng trên codepen.io, nếu có hứng thú bạn có thể fork và sửa source code theo ý của mình :)"
permalink: "/minijavascript/"
---

 Wikipedia Viewer

 Build a Random Quote Machine

 Build a pomodoro Clock

 Show the Local Weather

 Consuming Twich.tv API

 Build a Javascript Calculator

Tic Tac Toe with AI

 Simon game


text:
package com.ysynzehao.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/5/4.
 */
@Aspect
@Component
public class LogHandler {

    private Logger logger = LoggerFactory.getLogger(LogHandler.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    @Pointcut(value = "execution(* com.ysynzehao.service.*.*(..))")
    public void common(){}

    @Before("common()")
    public void before(JoinPoint joinPoint) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        logger.info("before: request url: " + request.getRequestURL().toString());

        logger.info("before: class.method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }

    @After("common()")
    public void after(JoinPoint joinPoint) {

        logger.info("after: class.method: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    }

    @AfterReturning(returning = "object", pointcut="common()")
    public void returnMsg(JoinPoint joinPoint, Object object) {
        try {
            logger.info("returnMsg: " + objectMapper.writeValueAsString(object));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}


text:
using System;
using OpenToolkit.Mathematics;

namespace Net3dBool
{
    /// <summary>
    /// Representation of a bound - the extremes of a 3d component for each coordinate.
    /// </summary>
    public class Bound
    {
        /** maximum from the x coordinate */
        private double XMax;
        /** minimum from the x coordinate */
        private double XMin;
        /** maximum from the y coordinate */
        private double YMax;
        /** minimum from the y coordinate */
        private double YMin;
        /** maximum from the z coordinate */
        private double ZMax;
        /** minimum from the z coordinate */
        private double ZMin;

        /** tolerance value to test equalities */
        private readonly static double EqualityTolerance = 1e-10f;

        //---------------------------------CONSTRUCTORS---------------------------------//

        /**
        * Bound constructor for a face
        *
        * @param p1 point relative to the first vertex
        * @param p2 point relative to the second vertex
        * @param p3 point relative to the third vertex
        */
        public Bound(Vector3d p1, Vector3d p2, Vector3d p3)
        {
            XMax = XMin = p1.X;
            YMax = YMin = p1.Y;
            ZMax = ZMin = p1.Z;

            CheckVertex(p2);
            CheckVertex(p3);
        }

        /**
        * Bound constructor for a object 3d
        *
        * @param vertices the object vertices
        */
        public Bound(Vector3d[] vertices)
        {
            XMax = XMin = vertices[0].X;
            YMax = YMin = vertices[0].Y;
            ZMax = ZMin = vertices[0].Z;

            for (int i = 1; i < vertices.Length; i++)
            {
                CheckVertex(vertices[i]);
            }
        }

        //----------------------------------OVERRIDES-----------------------------------//

        /**
        * Makes a string definition for the bound object
        *
        * @return the string definition
        */
        public string toString()
        {
            return "x: " + XMin + " .. " + XMax + "\ny: " + YMin + " .. " + YMax + "\nz: " + ZMin + " .. " + ZMax;
        }

        //--------------------------------------OTHERS----------------------------------//

        /**
        * Checks if a bound overlaps other one
        *
        * @param bound other bound to make the comparison
        * @return true if they insersect, false otherwise
        */
        public bool Overlap(Bound bound)
        {
            if ((XMin > bound.XMax + EqualityTolerance) || (XMax < bound.XMin - EqualityTolerance) || (YMin > bound.YMax + EqualityTolerance) || (YMax < bound.YMin - EqualityTolerance) || (ZMin > bound.ZMax + EqualityTolerance) || (ZMax < bound.ZMin - EqualityTolerance))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        //-------------------------------------PRIVATES---------------------------------//

        /**
        * Checks if one of the coordinates of a vertex exceed the ones found before
        *
        * @param vertex vertex to be tested
        */
        private void CheckVertex(Vector3d vertex)
        {
            if (vertex.X > XMax)
            {
                XMax = vertex.X;
            }
            else if (vertex.X < XMin)
            {
                XMin = vertex.X;
            }

            if (vertex.Y > YMax)
            {
                YMax = vertex.Y;
            }
            else if (vertex.Y < YMin)
            {
                YMin = vertex.Y;
            }

            if (vertex.Z > ZMax)
            {
                ZMax = vertex.Z;
            }
            else if (vertex.Z < ZMin)
            {
                ZMin = vertex.Z;
            }
        }
    }
}


text:
static void debounce_timerfunc(void *arg);
static void swtich_intr_handler(int8_t key);
void switch_init();
void led_init();

static os_timer_t debounce_timer;

#endif


text:
<?php

/**
 * TOP API: tmall.eai.order.refund.message.get request
 *
 * @author auto create
 * @since  1.0, 2013-09-13 16:51:03
 */
class Taobao_Request_TmallEaiOrderRefundMessageGetRequest {
	/**
	 * 页码。取值范围:大于零的整数; 默认值:1
	 **/
	private $pageNo;

	/**
	 * 每页条数。取值范围:大于零的整数; 默认值:40;最大值:100
	 **/
	private $pageSize;

	/**
	 * 退款单编号
	 **/
	private $refundId;

	/**
	 * 售中:onsale
	 * 售后:aftersale
	 **/
	private $refundPhase;

	private $apiParas = array();

	public function setPageNo($pageNo) {
		$this->pageNo = $pageNo;
		$this->apiParas["page_no"] = $pageNo;
	}

	public function getPageNo() {
		return $this->pageNo;
	}

	public function setPageSize($pageSize) {
		$this->pageSize = $pageSize;
		$this->apiParas["page_size"] = $pageSize;
	}

	public function getPageSize() {
		return $this->pageSize;
	}

	public function setRefundId($refundId) {
		$this->refundId = $refundId;
		$this->apiParas["refund_id"] = $refundId;
	}

	public function getRefundId() {
		return $this->refundId;
	}

	public function setRefundPhase($refundPhase) {
		$this->refundPhase = $refundPhase;
		$this->apiParas["refund_phase"] = $refundPhase;
	}

	public function getRefundPhase() {
		return $this->refundPhase;
	}

	public function getApiMethodName() {
		return "tmall.eai.order.refund.message.get";
	}

	public function getApiParas() {
		return $this->apiParas;
	}

	public function check() {

		Taobao_RequestCheckUtil::checkMinValue($this->pageNo, 1, "pageNo");
		Taobao_RequestCheckUtil::checkMaxValue($this->pageSize, 100, "pageSize");
		Taobao_RequestCheckUtil::checkMinValue($this->pageSize, 1, "pageSize");
		Taobao_RequestCheckUtil::checkNotNull($this->refundId, "refundId");
		Taobao_RequestCheckUtil::checkNotNull($this->refundPhase, "refundPhase");
	}

	public function putOtherTextParam($key, $value) {
		$this->apiParas[$key] = $value;
		$this->$key = $value;
	}
}


text:
function run_multi_machine_hpc(cmd_str, machineInfo, runMode, init_matlab_cmdstr)
%
%  Runs the string in 'cmd_str' on the machines listed in the cell array
%  machines. Each will be running within a
%  screen with the specified string 'ID_str' in the name (default is
%  'MultiMatlab').
%
% IMPORTANT:
%  Note that it is assumed that passwordless login is available when
%  ssh-ing to each of the provided machines.

% Create the call to matlab:
if exist('init_matlab_cmdstr', 'var') && ~isempty(init_matlab_cmdstr)
cmd = sprintf('%s; matlab -nodesktop -nosplash -r \"%s\"', init_matlab_cmdstr, cmd_str);
else
cmd = sprintf('matlab -nodesktop -nosplash -r \"%s\"', cmd_str);    % nice default is 10
end

if strcmp(runMode, 'newCl')
    num_jobs = machineInfo.num_jobs;
    num_cpu = machineInfo.num_cpu;
    memgb = machineInfo.memgb;
    clusterName = machineInfo.clusterName;
    logdir = machineInfo.logdir;
    %logstring = machineInfo.logstring;
    %lsscript = machineInfo.lsscript;
    ID_str = machineInfo.procname;

    for i_job = 1:num_jobs

       [blah pbsjobid] = system(['job submit /scheduler:' clusterName ' /jobname:ls /numcores:1 dir']);
        jobidnum = str2num(pbsjobid(end-3:end-1))+1;

        OUTPUT_FILER=[logdir '/' num2str(jobidnum) '.warp.output'];
        ERROR_FILER=[logdir '/' num2str(jobidnum) '.warp.error'];
        finalcmd = [cmd ' > ' OUTPUT_FILER];

        system(['job submit /scheduler:' clusterName ' /jobname:' ID_str ' /stdout:' OUTPUT_FILER ' /stderr:' ERROR_FILER ...
            ' /numcores:' num2str(num_cpu) ' '  finalcmd]);

        pause(1);
    end
elseif strcmp(runMode, 'oldCl')
    machines = machineInfo.machines;
    machines = cellstr(machines);       % handles case that a single string is passed in
    domain = machineInfo.domain;
    num_proc = machineInfo.num_procs;
    procname = machineInfo.procname;
    for i_machine = 1:length(machines)
        ID_str{i_machine} = ['MultiMatlab-' machines{i_machine}];    % can replace 'MultiM' with procname
    end

    for i_machine = 1:length(machines)
        % Create the ssh call for this machine
        ssh_cmd = sprintf(['ssh %s.%s ''%s'''], machines{i_machine}, domain, cmd);
        for i_proc = 1:num_proc
            fprintf('Starting process %d on %s\n', i_proc, machines{i_machine});
            try
                %screen_cmd = ['screen -m -d -S ' ID_str ' ' ssh_cmd];
                screen_cmd = ['screen -m -d -S ' ID_str{i_machine} ' ' ssh_cmd];
                system(screen_cmd);            % Actually do the ssh inside of a screen
            catch
                warning('Unable to start process %d on %s', i_proc, machines{i_machine});
            end
        end
    end
end


text:
import { Labels } from './data';
import { DataFrame } from './dataFrame';
import { AbsoluteTimeRange } from './time';
import { DataQuery } from './datasource';

/**
 * Mapping of log level abbreviation to canonical log level.
 * Supported levels are reduce to limit color variation.
 */
export enum LogLevel {
  emerg = 'critical',
  fatal = 'critical',
  alert = 'critical',
  crit = 'critical',
  critical = 'critical',
  warn = 'warning',
  warning = 'warning',
  err = 'error',
  eror = 'error',
  error = 'error',
  info = 'info',
  information = 'info',
  informational = 'info',
  notice = 'info',
  dbug = 'debug',
  debug = 'debug',
  trace = 'trace',
  unknown = 'unknown',
}

// Used for meta information such as common labels or returned log rows in logs view in Explore
export enum LogsMetaKind {
  Number,
  String,
  LabelsMap,
  Error,
}

export enum LogsSortOrder {
  Descending = 'Descending',
  Ascending = 'Ascending',
}

export interface LogsMetaItem {
  label: string;
  value: string | number | Labels;
  kind: LogsMetaKind;
}

export interface LogRowModel {
  // Index of the field from which the entry has been created so that we do not show it later in log row details.
  entryFieldIndex: number;

  // Index of the row in the dataframe. As log rows can be stitched from multiple dataFrames, this does not have to be
  // the same as rows final index when rendered.
  rowIndex: number;

  // Full DataFrame from which we parsed this log.
  // TODO: refactor this so we do not need to pass whole dataframes in addition to also parsed data.
  dataFrame: DataFrame;
  duplicates?: number;

  // Actual log line
  entry: string;
  hasAnsi: boolean;
  hasUnescapedContent: boolean;
  labels: Labels;
  logLevel: LogLevel;
  raw: string;
  searchWords?: string[];
  timeFromNow: string;
  timeEpochMs: number;
  // timeEpochNs stores time with nanosecond-level precision,
  // as millisecond-level precision is usually not enough for proper sorting of logs
  timeEpochNs: string;
  timeLocal: string;
  timeUtc: string;
  uid: string;
  uniqueLabels?: Labels;
}

export interface LogsModel {
  hasUniqueLabels: boolean;
  meta?: LogsMetaItem[];
  rows: LogRowModel[];
  series?: DataFrame[];
  visibleRange?: AbsoluteTimeRange;
  queries?: DataQuery[];
}

export interface LogSearchMatch {
  start: number;
  length: number;
  text: string;
}

export interface LogLabelStatsModel {
  active?: boolean;
  count: number;
  proportion: number;
  value: string;
}

export enum LogsDedupStrategy {
  none = 'none',
  exact = 'exact',
  numbers = 'numbers',
  signature = 'signature',
}

export interface LogsParser {
  /**
   * Value-agnostic matcher for a field label.
   * Used to filter rows, and first capture group contains the value.
   */
  buildMatcher: (label: string) => RegExp;

  /**
   * Returns all parsable substrings from a line, used for highlighting
   */
  getFields: (line: string) => string[];

  /**
   * Gets the label name from a parsable substring of a line
   */
  getLabelFromField: (field: string) => string;

  /**
   * Gets the label value from a parsable substring of a line
   */
  getValueFromField: (field: string) => string;
  /**
   * Function to verify if this is a valid parser for the given line.
   * The parser accepts the line unless it returns undefined.
   */
  test: (line: string) => any;
}

export enum LogsDedupDescription {
  none = 'No de-duplication',
  exact = 'De-duplication of successive lines that are identical, ignoring ISO datetimes.',
  numbers = 'De-duplication of successive lines that are identical when ignoring numbers, e.g., IP addresses, latencies.',
  signature = 'De-duplication of successive lines that have identical punctuation and whitespace.',
}


text:
package main

import (
	"testing"
	"fmt"
	//"net/http"
	//"strings"
	//"net/http/httptest"
)

var testCases = []struct {
	in string
	out string
} {
	{"", "a"},
	{"aa", "ab"},
	{"a9", "ba"},
	{"99", "aaa"},
}

func TestCodeGeneration(t *testing.T) {

	for _, testCase := range testCases {
		expected := testCase.out
		response, _ := GenerateNextCode(testCase.in)
		if response != expected {
			fmt.Println("Expected :"+expected+ " Received :"+response)
			t.Error("Test failed")
		}
	}
}

//func TestCreateShortUrl(t *testing.T) {
//	req, _ := http.NewRequest(
//		"POST",
//		"http://localhost:8080/create/",
//		strings.NewReader("url=http://coditas.com"),
//	)
//
//	recorder := httptest.NewRecorder()
//	Create(recorder, req, nil)
//	if recorder.Code != http.StatusOK {
//		t.Errorf("Expected status 200 Received %d", recorder.Code)
//	}
//
//	if !strings.Contains(recorder.Body.String(), "SUCCESS") {
//		t.Error("Unexpected body in response %q", recorder.Body.String())
//	}
//}


text:
/* eslint-disable no-unused-vars, space-before-function-paren */

class ListLabel {
  constructor (obj) {
    this.id = obj.id;
    this.title = obj.title;
    this.color = obj.color;
    this.textColor = obj.text_color;
    this.description = obj.description;
    this.priority = (obj.priority !== null) ? obj.priority : Infinity;
  }
}

window.ListLabel = ListLabel;


text:
package org.apache.camel.api.management.mbean;

import org.apache.camel.api.management.ManagedOperation;

public interface ManagedBrowsableEndpointMBean extends ManagedEndpointMBean {

    @ManagedOperation(description = "Current number of Exchanges in Queue")
    long queueSize();

    @ManagedOperation(description = "Get Exchange from queue by index")
    String browseExchange(Integer index);

    @ManagedOperation(description = "Get message body from queue by index")
    String browseMessageBody(Integer index);

    /**
     * @deprecated use {@link #browseAllMessagesAsXml(Boolean)} instead
     */
    @ManagedOperation(description = "Get message as XML from queue by index")
    @Deprecated
    String browseMessageAsXml(Integer index);

    @ManagedOperation(description = "Get message as XML from queue by index")
    String browseMessageAsXml(Integer index, Boolean includeBody);

    @ManagedOperation(description = "Gets all the messages as XML from the queue")
    String browseAllMessagesAsXml(Boolean includeBody);

    @ManagedOperation(description = "Gets the range of messages as XML from the queue")
    String browseRangeMessagesAsXml(Integer fromIndex, Integer toIndex, Boolean includeBody);

}


text:
_**Note:** This package is unpublished. I was trolled by near identical named packages and now I have found an acceptable package so the world does not need this..._

> _Allows project bundling via webpack for serverless invoke local and deploy_

[![Build Status](https://travis-ci.org/lteacher/serverless-plugin-bundler.svg?branch=master)](https://travis-ci.org/lteacher/serverless-plugin-bundler)
[![Coverage Status](https://coveralls.io/repos/github/lteacher/serverless-plugin-bundler/badge.svg?branch=master)](https://coveralls.io/github/lteacher/serverless-plugin-bundler?branch=master)

### Install

In your serverless project, run npm or yarn install. Note that to import the webpack config you also need the [`serverless-plugin-js-import`](https://www.npmjs.com/package/serverless-plugin-js-import)

```sh
npm install --save-dev serverless-plugin-bundler serverless-plugin-js-import
```

You need to be running webpack in your project, so `npm i --save-dev webpack` if you dont have it

### Setup
Configure both plugins in the `serverless.yml` like:

```yaml
plugins:
  - serverless-plugin-bundler
  - serverless-plugin-js-import
```

### Usage

#### Option 1

Include a webpack configuration via import to an existing config file

```yaml
custom:
  webpack: ${file(./webpack.config.js)}
```

#### Option 2 - _(Experimental)_

Include a webpack configuration, also in `serverless.yml` like _(example only)_

```yaml
custom:
  webpack:
    entry: ./handler.js
    target: node
    output:
      libraryTarget: umd
      filename: handler.js
      path: dist/
    module:
      loaders:
        -
          test: /\.js$/
          exclude: /(node_modules|dist)/
          loader: babel-loader
```

### Config

The bundler has some minimal configuration here are the options which also go into the `custom` section of the yaml under `bundler` exactly as shown

```yaml
custom:
  bundler:
    logging: true # Enables logging. SLS_DEBUG=* also enables this
    clean: true   # Allows for not cleaning the output dir. Defaults to true
```


text:
#ifndef BOOST_SPIRIT_INCLUDE_CLASSIC_PARSER_CONTEXT
#define BOOST_SPIRIT_INCLUDE_CLASSIC_PARSER_CONTEXT
#include <lslboost/spirit/home/classic/core/non_terminal/parser_context.hpp>
#endif


text:
var util = node.require('util');

function Console(stdout, stderr) {
  if (!(this instanceof Console)) {
    return new Console(stdout, stderr);
  }
  if (!stdout || typeof stdout.write !== 'function') {
    throw new TypeError('Console expects a writable stream instance');
  }
  if (!stderr) {
    stderr = stdout;
  }
  var prop = {
    writable: true,
    enumerable: false,
    configurable: true
  };
  prop.value = stdout;
  Object.defineProperty(this, '_stdout', prop);
  prop.value = stderr;
  Object.defineProperty(this, '_stderr', prop);
  prop.value = {};
  Object.defineProperty(this, '_times', prop);

  // bind the prototype functions to this Console instance
  Object.keys(Console.prototype).forEach(function(k) {
    this[k] = this[k].bind(this);
  }, this);
}

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};

Console.prototype.info = Console.prototype.log;

Console.prototype.warn = function() {
  this._stderr.write(util.format.apply(this, arguments) + '\n');
};

Console.prototype.error = Console.prototype.warn;

Console.prototype.dir = function(object) {
  this._stdout.write(util.inspect(object) + '\n');
};

Console.prototype.time = function(label) {
  this._times[label] = Date.now();
};

Console.prototype.timeEnd = function(label) {
  var time = this._times[label];
  if (!time) {
    throw new Error('No such label: ' + label);
  }
  var duration = Date.now() - time;
  this.log('%s: %dms', label, duration);
};

Console.prototype.trace = function(label) {
  // TODO probably can to do this better with V8's debug object once that is
  // exposed.
  var err = new Error;
  err.name = 'Trace';
  err.message = label || '';
  Error.captureStackTrace(err, arguments.callee);
  this.error(err.stack);
};

Console.prototype.assert = function(expression) {
  if (!expression) {
    var arr = Array.prototype.slice.call(arguments, 1);
    node.require('assert').ok(false, util.format.apply(this, arr));
  }
};

module.exports = new Console(process.stdout, process.stderr);
module.exports.Console = Console;


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/formslib.php');
require_once($CFG->dirroot . '/repository/lib.php');

/**
 * Class to post in a forum.
 *
 * @package   mod_forum
 * @copyright Jamie Pratt <me@jamiep.org>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class mod_forum_post_form extends moodleform {

    /**
     * Returns the options array to use in filemanager for forum attachments
     *
     * @param stdClass $forum
     * @return array
     */
    public static function attachment_options($forum) {
        global $COURSE, $PAGE, $CFG;
        $maxbytes = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $COURSE->maxbytes, $forum->maxbytes);
        return array(
            'subdirs' => 0,
            'maxbytes' => $maxbytes,
            'maxfiles' => $forum->maxattachments,
            'accepted_types' => '*',
            'return_types' => FILE_INTERNAL
        );
    }

    /**
     * Returns the options array to use in forum text editor
     *
     * @param context_module $context
     * @param int $postid post id, use null when adding new post
     * @return array
     */
    public static function editor_options(context_module $context, $postid) {
        global $COURSE, $PAGE, $CFG;
        // TODO: add max files and max size support
        $maxbytes = get_user_max_upload_file_size($PAGE->context, $CFG->maxbytes, $COURSE->maxbytes);
        return array(
            'maxfiles' => EDITOR_UNLIMITED_FILES,
            'maxbytes' => $maxbytes,
            'trusttext'=> true,
            'return_types'=> FILE_INTERNAL | FILE_EXTERNAL,
            'subdirs' => file_area_contains_subdirs($context, 'mod_forum', 'post', $postid)
        );
    }

    /**
     * Form definition
     *
     * @return void
     */
    function definition() {
        global $CFG, $OUTPUT;

        $mform =& $this->_form;

        $course = $this->_customdata['course'];
        $cm = $this->_customdata['cm'];
        $coursecontext = $this->_customdata['coursecontext'];
        $modcontext = $this->_customdata['modcontext'];
        $forum = $this->_customdata['forum'];
        $post = $this->_customdata['post'];
        $subscribe = $this->_customdata['subscribe'];
        $edit = $this->_customdata['edit'];
        $thresholdwarning = $this->_customdata['thresholdwarning'];

        $mform->addElement('header', 'general', '');//fill in the data depending on page params later using set_data

        // If there is a warning message and we are not editing a post we need to handle the warning.
        if (!empty($thresholdwarning) && !$edit) {
            // Here we want to display a warning if they can still post but have reached the warning threshold.
            if ($thresholdwarning->canpost) {
                $message = get_string($thresholdwarning->errorcode, $thresholdwarning->module, $thresholdwarning->additional);
                $mform->addElement('html', $OUTPUT->notification($message));
            }
        }

        $mform->addElement('text', 'subject', get_string('subject', 'forum'), 'size="48"');
        $mform->setType('subject', PARAM_TEXT);
        $mform->addRule('subject', get_string('required'), 'required', null, 'client');
        $mform->addRule('subject', get_string('maximumchars', '', 255), 'maxlength', 255, 'client');

        $mform->addElement('editor', 'message', get_string('message', 'forum'), null, self::editor_options($modcontext, (empty($post->id) ? null : $post->id)));
        $mform->setType('message', PARAM_RAW);
        $mform->addRule('message', get_string('required'), 'required', null, 'client');

        $manageactivities = has_capability('moodle/course:manageactivities', $coursecontext);

        if (\mod_forum\subscriptions::is_forcesubscribed($forum)) {
            $mform->addElement('checkbox', 'discussionsubscribe', get_string('discussionsubscription', 'forum'));
            $mform->freeze('discussionsubscribe');
            $mform->setDefaults('discussionsubscribe', 0);
            $mform->addHelpButton('discussionsubscribe', 'forcesubscribed', 'forum');

        } else if (\mod_forum\subscriptions::subscription_disabled($forum) && !$manageactivities) {
            $mform->addElement('checkbox', 'discussionsubscribe', get_string('discussionsubscription', 'forum'));
            $mform->freeze('discussionsubscribe');
            $mform->setDefaults('discussionsubscribe', 0);
            $mform->addHelpButton('discussionsubscribe', 'disallowsubscription', 'forum');

        } else {
            $mform->addElement('checkbox', 'discussionsubscribe', get_string('discussionsubscription', 'forum'));
            $mform->addHelpButton('discussionsubscribe', 'discussionsubscription', 'forum');
        }

        if (!empty($forum->maxattachments) && $forum->maxbytes != 1 && has_capability('mod/forum:createattachment', $modcontext))  {  //  1 = No attachments at all
            $mform->addElement('filemanager', 'attachments', get_string('attachment', 'forum'), null, self::attachment_options($forum));
            $mform->addHelpButton('attachments', 'attachment', 'forum');
        }

        if (empty($post->id) && $manageactivities) {
            $mform->addElement('checkbox', 'mailnow', get_string('mailnow', 'forum'));
        }

        if (!empty($CFG->forum_enabletimedposts) && !$post->parent && has_capability('mod/forum:viewhiddentimedposts', $coursecontext)) { // hack alert
            $mform->addElement('header', 'displayperiod', get_string('displayperiod', 'forum'));

            $mform->addElement('date_time_selector', 'timestart', get_string('displaystart', 'forum'), array('optional' => true));
            $mform->addHelpButton('timestart', 'displaystart', 'forum');

            $mform->addElement('date_time_selector', 'timeend', get_string('displayend', 'forum'), array('optional' => true));
            $mform->addHelpButton('timeend', 'displayend', 'forum');

        } else {
            $mform->addElement('hidden', 'timestart');
            $mform->setType('timestart', PARAM_INT);
            $mform->addElement('hidden', 'timeend');
            $mform->setType('timeend', PARAM_INT);
            $mform->setConstants(array('timestart'=> 0, 'timeend'=>0));
        }

        if ($groupmode = groups_get_activity_groupmode($cm, $course)) {
            $groupdata = groups_get_activity_allowed_groups($cm);

            $groupinfo = array();
            foreach ($groupdata as $groupid => $group) {
                // Check whether this user can post in this group.
                // We must make this check because all groups are returned for a visible grouped activity.
                if (forum_user_can_post_discussion($forum, $groupid, null, $cm, $modcontext)) {
                    // Build the data for the groupinfo select.
                    $groupinfo[$groupid] = $group->name;
                } else {
                    unset($groupdata[$groupid]);
                }
            }
            $groupcount = count($groupinfo);

            // Check whether a user can post to all of their own groups.

            // Posts to all of my groups are copied to each group that the user is a member of. Certain conditions must be met.
            // 1) It only makes sense to allow this when a user is in more than one group.
            // Note: This check must come before we consider adding accessallgroups, because that is not a real group.
            $canposttoowngroups = empty($post->edit) && $groupcount > 1;

            // 2) Important: You can *only* post to multiple groups for a top level post. Never any reply.
            $canposttoowngroups = $canposttoowngroups && empty($post->parent);

            // 3) You also need the canposttoowngroups capability.
            $canposttoowngroups = $canposttoowngroups && has_capability('mod/forum:canposttomygroups', $modcontext);
            if ($canposttoowngroups) {
                // This user is in multiple groups, and can post to all of their own groups.
                // Note: This is not the same as accessallgroups. This option will copy a post to all groups that a
                // user is a member of.
                $mform->addElement('checkbox', 'posttomygroups', get_string('posttomygroups', 'forum'));
                $mform->addHelpButton('posttomygroups', 'posttomygroups', 'forum');
                $mform->disabledIf('groupinfo', 'posttomygroups', 'checked');
            }

            // Check whether this user can post to all groups.
            // Posts to the 'All participants' group go to all groups, not to each group in a list.
            // It makes sense to allow this, even if there currently aren't any groups because there may be in the future.
            if (forum_user_can_post_discussion($forum, -1, null, $cm, $modcontext)) {
                // Note: We must reverse in this manner because array_unshift renumbers the array.
                $groupinfo = array_reverse($groupinfo, true );
                $groupinfo[-1] = get_string('allparticipants');
                $groupinfo = array_reverse($groupinfo, true );
                $groupcount++;
            }

            // Determine whether the user can select a group from the dropdown. The dropdown is available for several reasons.
            // 1) This is a new post (not an edit), and there are at least two groups to choose from.
            $canselectgroupfornew = empty($post->edit) && $groupcount > 1;

            // 2) This is editing of an existing post and the user is allowed to movediscussions.
            // We allow this because the post may have been moved from another forum where groups are not available.
            // We show this even if no groups are available as groups *may* have been available but now are not.
            $canselectgroupformove = $groupcount && !empty($post->edit) && has_capability('mod/forum:movediscussions', $modcontext);

            // Important: You can *only* change the group for a top level post. Never any reply.
            $canselectgroup = empty($post->parent) && ($canselectgroupfornew || $canselectgroupformove);

            if ($canselectgroup) {
                $mform->addElement('select','groupinfo', get_string('group'), $groupinfo);
                $mform->setDefault('groupinfo', $post->groupid);
                $mform->setType('groupinfo', PARAM_INT);
            } else {
                if (empty($post->groupid)) {
                    $groupname = get_string('allparticipants');
                } else {
                    $groupname = format_string($groupdata[$post->groupid]->name);
                }
                $mform->addElement('static', 'groupinfo', get_string('group'), $groupname);
            }
        }
        //-------------------------------------------------------------------------------
        // buttons
        if (isset($post->edit)) { // hack alert
            $submit_string = get_string('savechanges');
        } else {
            $submit_string = get_string('posttoforum', 'forum');
        }

        $this->add_action_buttons(true, $submit_string);

        $mform->addElement('hidden', 'course');
        $mform->setType('course', PARAM_INT);

        $mform->addElement('hidden', 'forum');
        $mform->setType('forum', PARAM_INT);

        $mform->addElement('hidden', 'discussion');
        $mform->setType('discussion', PARAM_INT);

        $mform->addElement('hidden', 'parent');
        $mform->setType('parent', PARAM_INT);

        $mform->addElement('hidden', 'userid');
        $mform->setType('userid', PARAM_INT);

        $mform->addElement('hidden', 'groupid');
        $mform->setType('groupid', PARAM_INT);

        $mform->addElement('hidden', 'edit');
        $mform->setType('edit', PARAM_INT);

        $mform->addElement('hidden', 'reply');
        $mform->setType('reply', PARAM_INT);
    }

    /**
     * Form validation
     *
     * @param array $data data from the form.
     * @param array $files files uploaded.
     * @return array of errors.
     */
    function validation($data, $files) {
        $errors = parent::validation($data, $files);
        if (($data['timeend']!=0) && ($data['timestart']!=0) && $data['timeend'] <= $data['timestart']) {
            $errors['timeend'] = get_string('timestartenderror', 'forum');
        }
        if (empty($data['message']['text'])) {
            $errors['message'] = get_string('erroremptymessage', 'forum');
        }
        if (empty($data['subject'])) {
            $errors['subject'] = get_string('erroremptysubject', 'forum');
        }
        return $errors;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using MySql.Data.MySqlClient;
using TaskHistory.Api.Configuration;
using TaskHistory.Api.Sql;

namespace TaskHistory.Impl.Sql
{
	/// <summary>
	/// Provider that communicates with a MySql database for reading data
	/// Consider using ApplicationDataProxy instead of using this class directly
	/// </summary>
	public class DataReaderProvider : BaseDataProvider, IDataReaderProvider
	{
		readonly SqlDataReaderFactory _sqlDataReaderFactory;
		readonly string _connectionString;

		const string NullFromExecuteReaderForTypeCollection = "Null returned from ExceuteReaderForTypeCollection";

		public IEnumerable<T> ExecuteReaderForTypeCollection<T>(IFromDataReaderFactory<T> factory,
											  string storedProcedureName)
		{
			if (factory == null)
				throw new ArgumentNullException(nameof(factory));

			if (string.IsNullOrEmpty(storedProcedureName))
				throw new ArgumentNullException(nameof(storedProcedureName));

			return this.ExecuteReaderForTypeCollection(factory,
													   storedProcedureName,
													   new List<ISqlDataParameter>());
		}

		public T ExecuteReader<T> (IFromDataReaderFactory<T> factory,
			string storedProcedureName,
			ISqlDataParameter parameter)
		{
			if (factory == null)
				throw new ArgumentNullException (nameof(factory));

			if (string.IsNullOrEmpty(storedProcedureName))
				throw new ArgumentNullException(nameof(storedProcedureName));

			if (parameter == null)
				throw new ArgumentNullException (nameof(parameter));

			IEnumerable<T> collection = this.ExecuteReaderForTypeCollection<T> (factory, storedProcedureName, parameter);
			if (collection == null)
				throw new NullReferenceException (NullFromExecuteReaderForTypeCollection);

			return collection.FirstOrDefault ();
		}

		public T ExecuteReader<T> (IFromDataReaderFactory<T> factory,
			string storedProcedureName,
			IEnumerable<ISqlDataParameter> parameters)
		{
			if (factory == null)
				throw new ArgumentNullException (nameof(factory));

			if (string.IsNullOrEmpty(storedProcedureName))
				throw new ArgumentNullException(nameof(storedProcedureName));

			if (parameters == null)
				throw new ArgumentNullException (nameof(parameters));

			IEnumerable<T> collection = this.ExecuteReaderForTypeCollection<T> (factory,
			                                                                    storedProcedureName,
			                                                                    parameters);
			if (collection == null)
				throw new NullReferenceException (NullFromExecuteReaderForTypeCollection);

			return collection.FirstOrDefault ();
		}

		public IEnumerable<T> ExecuteReaderForTypeCollection<T> (IFromDataReaderFactory<T> factory,
		                                                         string storedProcedureName,
		                                                         ISqlDataParameter parameter)
		{
			if (factory == null)
				throw new ArgumentNullException (nameof(factory));

			if ((storedProcedureName == null) || (storedProcedureName == string.Empty))
				throw new ArgumentNullException (nameof(storedProcedureName));

			if (parameter == null)
				throw new ArgumentNullException (nameof(parameter));

			var returnVal = ExecuteReaderForTypeCollection<T> (factory,
				storedProcedureName,
				new List<ISqlDataParameter> { parameter });

			if (returnVal == null)
				throw new NullReferenceException (NullFromExecuteReaderForTypeCollection);

			return returnVal;
		}

		public IEnumerable<T> ExecuteReaderForTypeCollection<T> (IFromDataReaderFactory<T> factory,
			string storedProcedureName,
			IEnumerable<ISqlDataParameter> parameters)
		{
			if (factory == null)
				throw new ArgumentNullException (nameof(factory));

			if ((storedProcedureName == null) || (storedProcedureName == string.Empty))
				throw new ArgumentNullException (nameof(storedProcedureName));

			if (parameters == null)
				throw new ArgumentNullException (nameof(parameters));

			using (var connection = new MySqlConnection (_connectionString))
			using (var command = new MySqlCommand (storedProcedureName, connection))
			{
				command.CommandType = CommandType.StoredProcedure;

				var dataProviderParameters = BaseDataProvider.CreateMySqlParametersFromSqlDataParams (parameters);
				if (dataProviderParameters == null)
					throw new NullReferenceException ("Null returned from CreateMySqlParametersFromSqlDataParams in base class");

				foreach (var param in dataProviderParameters)
				{
					command.Parameters.Add (param);
				}

				command.Connection.Open ();

				MySqlDataReader reader = command.ExecuteReader (CommandBehavior.CloseConnection);
				ISqlDataReader sqlReader = _sqlDataReaderFactory.MakeDataReader(reader);
				if (sqlReader == null)
					throw new NullReferenceException ("Null returned from SqlDataReaderFactory");

				var returnVal = new List<T> ();

				while (reader.Read ())
				{
					T currentItem = factory.Build (sqlReader);
					returnVal.Add (currentItem);
				}
				return returnVal;
			}
		}

		public T ExecuteReader<T>(IFromDataReaderFactory<T> factory,
		                         string storedProcedureName)
		{
			if (factory == null)
				throw new ArgumentNullException(nameof(factory));

			if (string.IsNullOrEmpty(storedProcedureName))
				throw new ArgumentNullException(nameof(storedProcedureName));

			return this.ExecuteReader(factory,
									  storedProcedureName,
									  new List<ISqlDataParameter>());
		}

		public DataReaderProvider (SqlDataReaderFactory sqlDataReaderFactory,
		                           IConfigurationProvider configurationProvider)
			: base()
		{
			_sqlDataReaderFactory = sqlDataReaderFactory;
			_connectionString = configurationProvider.SqlConnectionString;
		}
	}
}


text:
@interface SPDependency ()
@property(copy) SPDependsFancyCallback callback;
@property(assign) id owner;
@property(retain) NSMutableArray *subscriptions;
@end

@implementation SPDependency
@synthesize callback = _callback, owner = _owner;
@synthesize subscriptions = _subscriptions;

- (id)initWithDependencies:(NSArray*)pairs callback:(SPDependsFancyCallback)callback owner:(id)owner
{
    if (!(self = [super init]))
        return nil;

    self.callback = callback;
    self.owner = owner;

    _subscriptions = [NSMutableArray new];

    NSEnumerator *en = [pairs objectEnumerator];
    id object = [en nextObject];
    id next = [en nextObject];

    for(;;) {
        SPKVObservation *subscription = [object sp_addObserver:self forKeyPath:next options:0 selector:@selector(somethingChanged:inObject:forKey:)];
        [_subscriptions addObject:subscription];

        next = [en nextObject];
        if (!next)
            break;

        if (![next isKindOfClass:[NSString class]]) {
            object = next;
            next = [en nextObject];
        }
    }

    self.callback(nil, nil, nil);

    return self;
}
-(void)invalidate;
{
    for(SPKVObservation *observation in _subscriptions)
        [observation invalidate];
    self.callback = nil;
}
-(void)dealloc;
{
    [self invalidate];
    self.subscriptions = nil;
    self.owner = nil;
    self.callback = nil;
    [super dealloc];
}
-(void)somethingChanged:(NSDictionary*)change inObject:(id)object forKey:(NSString*)key
{
#if _DEBUG
    NSAssert(self.callback != nil, @"Somehow a KVO reached us after an 'invalidate'?");
#endif
    if (self.callback)
        self.callback(change, object, key);
}
@end

static void *dependenciesKey = &dependenciesKey;

SPDependency *SPAddDependency(id owner, NSString *associationName, NSArray *dependenciesAndNames, SPDependsCallback callback)
{
    id dep = [[SPDependency alloc] initWithDependencies:dependenciesAndNames callback:callback owner:owner];
    if(owner && associationName) {
        NSMutableDictionary *dependencies = objc_getAssociatedObject(owner, dependenciesKey);
        if(!dependencies) dependencies = [NSMutableDictionary dictionary];

        SPDependency *oldDependency = [dependencies objectForKey:associationName];
        if(oldDependency) [oldDependency invalidate];

        [dependencies setObject:dep forKey:associationName];
        objc_setAssociatedObject(owner, dependenciesKey, dependencies, OBJC_ASSOCIATION_RETAIN);
        [dep release];
    } else {
        // Try to avoid autorelease, so only do it when we can't guarantee the life length of the dep longer
        // than the runloop.
        [dep autorelease];
    }
    return dep;
}

SPDependency *SPAddDependencyTA(id owner, NSString *associationName, NSArray *dependenciesAndNames, __unsafe_unretained id target, SEL action)
{
    __block __unsafe_unretained id unretainedTarget = target;
    return SPAddDependency(owner, associationName, dependenciesAndNames, ^(NSDictionary *change, id object, NSString *keyPath){
        // must cast to appropriate function pointer. see OBJC_OLD_DISPATCH_PROTOTYPES
        ((id(*)(id, SEL, ...))[unretainedTarget methodForSelector:action])(unretainedTarget, action, change, object, keyPath);
    });
}

SPDependency *SPAddDependencyV(id owner, NSString *associationName, ...)
{
    va_list va;
    va_start(va, associationName);

    id object = va_arg(va, id);
    id peek = va_arg(va, id);

#if defined (_DEBUG) || SP_WITH_QA_TESTING
    NSCAssert(object, @"Dependency argument is nil.");
    NSCAssert(peek, @"Dependency argument is nil.");
#endif

    if (object == nil || peek == nil)
        return nil;

    NSMutableArray *dependenciesAndNames = [NSMutableArray new];

    do {
        [dependenciesAndNames addObject:object];
        object = peek;
        peek = va_arg(va, id);
    } while(peek != nil);

    id dep = SPAddDependency(owner, associationName, dependenciesAndNames, object);

    [dependenciesAndNames release];
    return dep;
}

void SPRemoveAssociatedDependencies(id owner)
{
    NSMutableDictionary *dependencies = objc_getAssociatedObject(owner, dependenciesKey);
    for(SPDependency *dep in [dependencies allValues])
        [dep invalidate];

    objc_setAssociatedObject(owner, dependenciesKey, nil, OBJC_ASSOCIATION_RETAIN);
}

void SPRemoveAssociatedDependency(id owner, NSString *associationName)
{
    NSMutableDictionary *dependencies = objc_getAssociatedObject(owner, dependenciesKey);
    SPDependency *dep = [dependencies objectForKey:associationName];
    [dep invalidate];
    if (dep)
        [dependencies removeObjectForKey:associationName];
}

@implementation NSObject (SPDepends)
- (SPDependency*)sp_addDependency:(NSString*)depName on:(NSArray*)dependenciesAndNames changed:(SPDependsCallback)changed;
{
    return SPAddDependency(self, depName, dependenciesAndNames, changed);
}

- (SPDependency*)sp_addDependency:(NSString*)depName on:(NSArray*)dependenciesAndNames target:(id)target action:(SEL)action;
{
    return SPAddDependencyTA(self, depName, dependenciesAndNames, target, action);
}
- (SPDependency*)sp_addDependencyOn:(NSArray*)dependenciesAndNames changed:(SPDependsCallback)changed
{
    return [self sp_addDependency:nil on:dependenciesAndNames changed:changed];
}
- (SPDependency*)sp_addDependencyOn:(NSArray*)dependenciesAndNames target:(id)target action:(SEL)action
{
    return [self sp_addDependency:nil on:dependenciesAndNames target:target action:action];
}

- (void)sp_removeDependency:(NSString*)name
{
    SPRemoveAssociatedDependency(self, name);
}

- (void)sp_removeDependencies
{
    SPRemoveAssociatedDependencies(self);
}
@end


text:
namespace Google.Cloud.Iam.Admin.V1.Snippets
{
    // [START iam_v1_generated_IAM_QueryAuditableServices_async]
    using Google.Cloud.Iam.Admin.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedIAMClientSnippets
    {
        /// <summary>Snippet for QueryAuditableServicesAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task QueryAuditableServicesRequestObjectAsync()
        {
            // Create client
            IAMClient iAMClient = await IAMClient.CreateAsync();
            // Initialize request argument(s)
            QueryAuditableServicesRequest request = new QueryAuditableServicesRequest
            {
                FullResourceName = "",
            };
            // Make the request
            QueryAuditableServicesResponse response = await iAMClient.QueryAuditableServicesAsync(request);
        }
    }
    // [END iam_v1_generated_IAM_QueryAuditableServices_async]
}


text:
<?php
/**
 * <ClanDB Client>
 * @package: ClanDB Client for DZCP 1.6.x
 * @author: ClanDB Developer Team || Hammermaps.de Developer Team
 * @link: http://www.clandb.de || http://www.hammermaps.de
 */

define('max_list_clans', 10);


text:
<?xml version="1.0" encoding="UTF-8"?>
<typeSystemDescription xmlns="http://uima.apache.org/resourceSpecifier">
  <name>SentimentType</name>
  <description/>
  <version>1.0</version>
  <vendor/>
  <types>
    <typeDescription>
      <name>de.unidue.langtech.teaching.rp.type.OriginalLanguage</name>
      <description/>
      <supertypeName>uima.tcas.Annotation</supertypeName>
      <features>
        <featureDescription>
          <name>language</name>
          <description/>
          <rangeTypeName>uima.cas.String</rangeTypeName>
        </featureDescription>
      </features>
    </typeDescription>
  </types>
</typeSystemDescription>


text:
module Alloy
  module Core
    module Size
      @@sizes = Hash.new Alloy::Poros::Size

      def size queue = nil
        get_size queue
      end

      private
      def get_size queue
        @@sizes[queue] = Alloy::Poros::Size.new if queue unless @@sizes.has_key? queue

        @@sizes[queue]
      end
    end
  end
end


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

namespace Hepsi.CommandProcessor.Messaging
{
    /// <summary>
    /// Class MessageHeader
    /// The header for a <see cref="Message"/>
    /// </summary>
    public class MessageHeader : IEquatable<MessageHeader>
    {
        /// <summary>
        /// Gets the identifier.
        /// </summary>
        /// <value>The identifier.</value>
        public Guid Id { get; private set; }
        /// <summary>
        /// Gets the topic.
        /// </summary>
        /// <value>The topic.</value>
        public string Topic { get; private set; }
        /// <summary>
        /// Gets the type of the message. Used for routing the message to a handler
        /// </summary>
        /// <value>The type of the message.</value>
        public MessageType MessageType { get; private set; }
        /// <summary>
        /// Gets the bag.
        /// </summary>
        /// <value>The bag.</value>
        public Dictionary<string, object> Bag { get; private set; } //intended for extended headers

        /// <summary>
        /// Initializes a new instance of the <see cref="MessageHeader"/> class.
        /// </summary>
        /// <param name="messageId">The message identifier.</param>
        /// <param name="topic">The topic.</param>
        /// <param name="messageType">Type of the message.</param>
        public MessageHeader(Guid messageId, string topic, MessageType messageType)
        {
            Id = messageId;
            Topic = topic;
            MessageType = messageType;
            Bag = new Dictionary<string, object>();
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        public bool Equals(MessageHeader other)
        {
            return Id == other.Id && Topic == other.Topic && MessageType == other.MessageType;
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
        /// </summary>
        /// <param name="obj">The object to compare with the current object.</param>
        /// <returns><c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.</returns>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return false;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj.GetType() != GetType())
            {
                return false;
            }

            return Equals((MessageHeader)obj);
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = Id.GetHashCode();
                hashCode = (hashCode * 397) ^ (Topic != null ? Topic.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (int)MessageType;
                return hashCode;
            }
        }

        /// <summary>
        /// Implements the ==.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator ==(MessageHeader left, MessageHeader right)
        {
            return Equals(left, right);
        }

        /// <summary>
        /// Implements the !=.
        /// </summary>
        /// <param name="left">The left.</param>
        /// <param name="right">The right.</param>
        /// <returns>The result of the operator.</returns>
        public static bool operator !=(MessageHeader left, MessageHeader right)
        {
            return !Equals(left, right);
        }
    }
}


text:
<?php
/*
 * 用户类型详情页
 */

class Controller_Admin_User_Usertype_Usertypedetail extends Controller_Admin_App
{

	/**
	 * 用户类型详情
	 * @access  public
	 * @return  Response
	 */
	public function action_index($user_type_id)
	{
		$data = array();

		//调用共用Header
		$data['header'] = Request::forge('admin/common/header')->execute()->response();

		try {
			//获取自身所持有的用户类型
			$data['user_type_self'] = Model_User::SelectUserTypeById($_SESSION['login_user']['id']);

			if(!is_numeric($user_type_id)) {
				//用户类型ID不是数字
				return Response::forge(View::forge($this->template . '/admin/error/access_error', $data, false));
			} elseif(!Model_Permission::CheckPermissionByUser($_SESSION['login_user']['id'], 'sub_group', 8)) {
				//当前登陆用户不具备查看用户类型的权限
				return Response::forge(View::forge($this->template . '/admin/error/permission_error', $data, false));
			} else {
				$data['success_message'] = '';

				//获取用户类型信息
				$user_type = Model_UserType::SelectUserType(array('user_type_id' => $user_type_id));
				//是否允许操作特殊用户类型
				$special_able_flag = Model_Permission::CheckPermissionByUser($_SESSION['login_user']['id'], 'function', 5);

				if(!$user_type) {
					//不存在该ID的用户类型
					return Response::forge(View::forge($this->template . '/admin/error/access_error', $data, false));
					exit;
				} elseif(intval($user_type['special_level']) > 1) {
					//该ID的用户类型为系统用户类型
					return Response::forge(View::forge($this->template . '/admin/error/access_error', $data, false));
					exit;
				} elseif(!$special_able_flag && intval($user_type['special_level']) > 0) {
					//该ID的用户类型为特殊用户类型且当前登陆用户不具备操作特殊用户类型的权限
					return Response::forge(View::forge($this->template . '/admin/error/permission_error', $data, false));
					exit;
				}

				//用户类型信息
				$data['user_type'] = $user_type;
				//获取全部权限
				$data['permission_list'] = Model_Permission::SelectSystemPermissionList();
				//用户类型特殊等级列表
				$data['special_level_list'] = array('一般类型', '特殊类型', '系统类型');
				//是否具备用户类型编辑权限
				$data['edit_able_flag'] = Model_Permission::CheckPermissionByUser($_SESSION['login_user']['id'], 'function', 3);
				//是否允许操作特殊用户类型
				$data['special_able_flag'] = $special_able_flag;
				//获取当前该用户类型所持有的权限列表
				$permission_list = Model_Permission::SelectPermissionList(array('user_type' => $user_type_id));
				$data['master_group'] = $permission_list['master_group'];
				$data['sub_group'] = $permission_list['sub_group'];
				$data['function'] = $permission_list['function'];
				$data['authority'] = $permission_list['authority'];

				//输出提示信息
				if(isset($_SESSION['add_user_type_success'])) {
					$data['success_message'] = '用户类型添加成功';
					unset($_SESSION['add_user_type_success']);
				}
				if(isset($_SESSION['modify_user_type_success'])) {
					$data['error_message'] = '用户类型编辑失敗';
					unset($_SESSION['modify_user_type_success']);
				}

				//调用View
				return Response::forge(View::forge($this->template . '/admin/user/user_type/user_type_detail', $data, false));
			}
		} catch (Exception $e) {
			//发生系统异常
			return Response::forge(View::forge($this->template . '/admin/error/system_error', $data, false));
		}
	}

}


text:
"""BIG-IP® Local Traffic Manager™ (LTM®) cipher module.

REST URI
    ``http://localhost/mgmt/tm/ltm/cipher``

GUI Path
    ``Local Traffic --> Ciphers``

REST Kind
    ``tm:ltm:cipher:*``
"""

from f5.bigip.resource import Collection
from f5.bigip.resource import OrganizingCollection
from f5.bigip.resource import Resource

class Cipher(OrganizingCollection):
    """BIG-IP® LTM cipher collection"""
    def __init__(self, ltm):
        super(Cipher, self).__init__(ltm)
        self._meta_data['allowed_lazy_attributes'] = [
            Rules,
            Groups
        ]

class Rules(Collection):
    """BIG-IP® cipher rule sub-collection"""
    def __init__(self, cipher):
        super(Rules, self).__init__(cipher)
        self._meta_data['allowed_lazy_attributes'] = [Rule]
        self._meta_data['attribute_registry'] =\
            {'tm:ltm:cipher:rule:rulestate': Rule}

class Rule(Resource):
    """BIG-IP® cipher rule sub-collection resource"""
    def __init__(self, rule_s):
        super(Rule, self).__init__(rule_s)
        self._meta_data['required_creation_parameters'].update(('partition',))
        self._meta_data['required_json_kind'] =\
            'tm:ltm:cipher:rule:rulestate'

class Groups(Collection):
    """BIG-IP® cipher group sub-collection"""
    def __init__(self, cipher):
        super(Groups, self).__init__(cipher)
        self._meta_data['allowed_lazy_attributes'] = [Group]
        self._meta_data['attribute_registry'] =\
            {'tm:ltm:cipher:group:groupstate': Group}

class Group(Resource):
    """BIG-IP® cipher group sub-collection resource"""
    def __init__(self, group_s):
        super(Group, self).__init__(group_s)
        self._meta_data['required_creation_parameters'].update(('partition',))
        self._meta_data['required_json_kind'] =\
            'tm:ltm:cipher:group:groupstate'


text:
var util = require('util')

var loggingFunctions = {
  trace: 1,
  log: 2,
  info: 3,
  warn: 4,
  error: 5
}

// NOTE: No circular dependencies. This package should not depend on others,
// so we duplicate code here instead of requiring get-nearest-package-json.
var packageName = require('pkg-config')(null, {
  cwd: __filename,
  root: null,
  cache: false
}).name

// Due to how util.format works below console.log, need to process the message
// first and pass into the message template.
var messageTemplate = util.format('%s: %%s', packageName)

module.exports = (function (console) {
  var modifiedConsole = {}

  // By default, report warnings or worse.
  modifiedConsole.logLevel = 4

  for (var prop in console) {
    if (loggingFunctions[prop]) {
      // Control what gets displayed at what level, and also format output.
      modifiedConsole[prop] = function (loggingFunction) {
        if (modifiedConsole.logLevel <= loggingFunctions[loggingFunction]) {
          var args = Array.prototype.slice.call(arguments, 1)
          // Process the message formatting to let caller take advantage of
          // default formatting before prefixing with the package name.
          this[loggingFunction](messageTemplate, util.format.apply(util, args))
        }
      }.bind(console, prop)
    } else {
      // Regular console methods are pass through.
      if (typeof console[prop] === 'function') {
        modifiedConsole[prop] = console[prop].bind(console)
      } else {
        modifiedConsole[prop] = console[prop]
      }
    }
  }
  return modifiedConsole
})(console)


text:
// Copyright (c) 2014 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE

namespace SharpNav.Crowds
{
	/// <summary>
	/// Similar to a boolean, except there is an intermediate variable between true and false.
	/// </summary>
	public enum Status
	{
		/// <summary>
		/// Operation failed to complete
		/// </summary>
		Failure,

		/// <summary>
		/// Operation finished
		/// </summary>
		Success,

		/// <summary>
		/// Operation in progress
		/// </summary>
		InProgress
	}

	/// <summary>
	/// A static class containing extension methods related to the <see cref="Status"/> enum.
	/// </summary>
	public static class StatusExtensions
	{
		/// <summary>
		/// Converts a boolean value to a <see cref="Status"/>.
		/// </summary>
		/// <param name="variable">The boolean value.</param>
		/// <returns>The equivalent status.</returns>
		public static Status ToStatus(this bool variable)
		{
			return variable ? Status.Success : Status.Failure;
		}
	}
}


text:
#include "Person.h"
#include <iostream>

using namespace std;

Person::Person(string first,string last) : firstname(first),lastname(last)
{
}

Person::~Person() {}

string Person::GetName()
{
	return firstname + " " + lastname;
}


text:
namespace Furrovine { namespace Unicode {

	struct jamo_short_name_properties {
	public:
		const char jamo_short_name[ 4 ];
	};

}}