text:
/*!
 * @file sharedlib.c
 *
 * Beispiel 3
 *@brief Using Semaphores and Shared memory to simulate Server/Client message(sender/receiver)
 *
 * @author Dennis Addo ic16b026
 * @author Robert Niedermaier ic16b089
 * @details More information about the project can be found here
 * @see URL:https://cis.technikum-wien.at/documents/bic/2/bes/semesterplan/lu/beispiel3.html
 *
 * @date 15/05/2017
 *
 * @version 1.0
 *
 * @todo All implentations must be contained in one method structure unless these functions
 *      are required by other programs/methods
 *
 *
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <getopt.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/shm.h>
#include <string.h>
#include "sem182/sem182.h"
#include <ctype.h>
#include "sharedlib.h"

/*! SPERM   This the permission for the shared memory 0700*/
#define SPERM (S_IRUSR | S_IWUSR | S_IXUSR )

/*! SHM_KEY   This the permission for the shared memory */
#define SHM_KEY ((getuid() * 100) + 0)

/*! SEM_KEY   This the key for the semaphores */
#define SEM_KEY ((getuid() * 200) + 1)

static const char *programmName = NULL; /*! programmName   global pointer to hold the program name */
static shmseg *shmsgpr = NULL;          /*! SPERM   This the shared memory segment*/
static int *shmbff = (void *) -1;       /*! SPERM   This the shared memory buffer*/
static size_t shmssize_g = 0;           /*! shmssize_g   global value for the shared memory buffer size*/

static int shmseg_easy_write(int *c);
static int shmseg_easy_read(void);
static void detach(shmseg *shm);
static size_t process_nums(const char *ops);

/*!
 * @brief       process the command options arguments.
 *              This function take a argc and argv from
 *              the main method and process the passed
 *              (command line) arguments
 * @param       argc    The number of arguments.
 * @param       argv     Array of char pointer to the passed
 *                       arguments (command line).
 *@param        shmsizeptr  pointer to the size of the shared memory
 *                       the passed requested size to be copied here
 *
 * @result      An int ( 0 on success and 1 on failure).
 */
int args_parser(int argc, char *argv[], size_t *shmsizeptr) {

    int opt;
    size_t s = 0;
    programmName = argv[0];

    if (argc < 2) {
        fprintf(stderr, "%s ringbuffer size must be specified\n"
                "Usage: %s [-m] <ringbuffer size>\n", programmName, programmName);

        *shmsizeptr = 0;
        return EXIT_FAILURE;
    }

    while ((opt = getopt(argc, argv, ":m:")) != -1) {

        switch (opt) {
            case 'm' :
                s = process_nums(optarg);

                break;
            default:
                fprintf(stderr, "Usage: %s [-m] <ringbuffer size>\n", programmName);
                exit(EXIT_FAILURE);

        }

    }

    if (optind < argc) {
        fprintf(stderr, "%s: Non-option argument: %s\n"
                "Usage: %s [-m] <ringbuffer elements>\n", programmName, optarg, programmName);
        *shmsizeptr = 0;
        exit(EXIT_FAILURE);

    }

    /*This will work on a 32bit linux machine
     * 4096 page --> 1024 * (4 -> 32bit system)
     * or (buf.shmall * sizeof(int)) mostly is 4096/1024 --> 4
     * it is ok for this project. if platform is 64 then the
     * logic for calculating the shm max in (kbytes) will be different
     * ipcs -lm for more details on a 64bit platform
     * */

#if defined(__unix__) && defined(__i386__)

    struct shminfo buf;
    if(shmctl(0, IPC_INFO, (struct shmid_ds *) &buf) < 0){
        fprintf(stderr,"shmctl: %s %s \n",programmName, strerror(errno));
        exit(EXIT_FAILURE);
    }

    if ( s >= (buf.shmall * 4) ) {
        fprintf(stderr, "%s: specified shared memory size too big\n"
                "Usage: %s [-m] <ringbuffer size> \n",programmName,programmName);

        *shmsizeptr = 0;
        return EXIT_FAILURE;
    }

#else

    /*(SIZE_MAX / sizeof(int) +1) == (SIZE_MAX / 4(page size / 1024 (1 kbyte)))
     * the shmall and the ipc calling process shared memory limits is not the same (page size segment and
     * the other in kbytes) (SIZE_MAX / sizeof(int)) see ipcs -lm for more details.
     * on a 64 bit system will this be different. Since are not doing 64bit compatible
     * shared memory is enough for this on "annuminas"
     *
     * on BSD see man ipcs or ipcs -l.
     * on a 32 bit system is SIZE_MAX = 4294967295 like UINT_MAX which after
     * converting to kbytes witht he corresponding page size is less than 1bit than
     * the ipc calling process shm limits ipcs -lm 1073741823 != 1073741824
     * */
    if ( s >= (SIZE_MAX / sizeof(int)) +1) {
        fprintf(stderr, "%s: specified shared memory size too big\n"
                "Usage: %s [-m] <ringbuffer size> \n", programmName, programmName);

        *shmsizeptr = 0;
        return EXIT_FAILURE;
    }
#endif

    *shmsizeptr = s;
    shmssize_g = *shmsizeptr;

    return 0;

}

/*!
 * @brief       convert string to long
 *              This function takes a number string and convert it
 *              to long integer value. It is a simple wrapper for the strtol function
 * @param       ops     The passed number as a string
 * @result      The converted value in size_t otherwise it exit with failure 1.
 */
static size_t process_nums(const char *ops) {

    char *end;
    long val = strtol(ops, &end, 10);

    if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
        || (errno != 0 && val == 0)) {

        fprintf(stderr,"%s: -> %s\n",programmName,strerror(errno));
        fprintf(stderr, "%s: Cannot pass the value <%s> to strtol \n"
                "Usage: %s [-m] <ringbuffer elements>\n", programmName, ops, programmName);
        exit(EXIT_FAILURE);
    }

    if (val <= 0) {

        fprintf(stderr, "%s: Invalid specified shared memory size : ringbuffer size <= %zu \n"
                "Usage: %s [-m] <ringbuffer elements>\n", programmName,(size_t) (SIZE_MAX /sizeof(int)), programmName);

        exit(EXIT_FAILURE);
    } else if (*end != '\0') {
        fprintf(stderr, "%s: Cannot pass the value <%s> to strtol \n"
                "Usage: %s [-m] <ringbuffer elements>\n", programmName, ops, programmName);
        exit(EXIT_FAILURE);
    }

    return (size_t) val;
}

/*!
 * @brief       initialize / create all the required
 *              resources needed - shared memory/ semaphores
 *              This function takes a specided size of the shared memory
 *              the mode (read only / read and write mode) and a pointer to
 *              the shared memory segment.
 * @param       shmsize    The weight of the chicken.
 * @param       mode     The sauce for cooking. Could be a
 *                        NULL pointer.
 *@param        shmsg
 *
 * @result      0 on success and -1 on failure.
 */
int shmseg_easy_init(const size_t *shmsize, const int mode, shmseg *shmsg) {

    shmsg->semid[0] = -1; //write access semaphore
    shmsg->semid[1] = -1; //read access semaphore
    shmsg->shmid = -1;
    shmbff = (void *) -1;

    shmsg->s_read = shmseg_easy_read;
    shmsg->s_write = shmseg_easy_write;
    shmsg->detach = detach;

    for (int i = 0; i < 2; ++i) {

        if ((shmsg->semid[i] = seminit(SEM_KEY + i, 0700, (i % 2 == 0 ? *shmsize : 0))) == -1) {

            if (errno == EEXIST) {
                if ((shmsg->semid[i] = semgrab(SEM_KEY + i)) == -1) {
                    fprintf(stderr, "semgrab: %s %s \n", programmName, strerror(errno));
                    return -1;
                }
            } else {
                fprintf(stderr, "seminit: %s %s \n", programmName, strerror(errno));
                return -1;
            }

        }
    }

    if ( (shmsg->shmid = shmget(SHM_KEY, *shmsize * sizeof(int), IPC_CREAT | SPERM) ) == -1) {
        fprintf(stderr, "shmget: %s %s\n", programmName, strerror(errno));
        /*shmseg_easy_clean(shmsg);*/
        return -1;

    }

    if ( (shmbff = shmat(shmsg->shmid, NULL, mode)) == (void *) -1) {
        fprintf(stderr, "shmat: %s %s\n", programmName, strerror(errno));
        return -1;
    }

    shmsgpr = shmsg;

    return 0;
}

/*!
 * @brief       write the byte specified by c to the shared memory buffer(shmbff).
 *              This function takes int pointer interpreted as
 *              a char that is to be written to the specified shared
 *              memory segment's(shmsgpr) shared  buffer. Using P() and V()
 *              for checking for write acccess and releasing to another process
 *              when done.
 * @param       c    The value to be written.
 *
 * @result      0 on success and -1 on failure.
 */
static int shmseg_easy_write(int *c) {

    if (shmbff == (void *) -1) {
        fprintf(stderr, "Oops: %s ->: Please initialize the shared memory"
                " segment before you can write to buffer\n", programmName);
        return -1;
    }

    static size_t i = 0;
    int l;

    do {
        l = P(shmsgpr->semid[0]);
    } while (l == -1 && errno == EINTR);

    if (l == -1) {
        fprintf(stderr, " P() : %s %s \n", programmName, strerror(errno));
        (void) shmseg_easy_clean(shmsgpr);
        return -1;
    }

    shmbff[(i++) % shmssize_g] = *c;

    do {

        l = V(shmsgpr->semid[1]);
    } while (l == -1 && errno == EINTR);

    if (l == -1) {
        fprintf(stderr, " V() : %s %s \n", programmName, strerror(errno));
        (void) shmseg_easy_clean(shmsgpr);
        return -1;
    }

    return 0;

}

/*!
 * @brief       read a char/integer value from the shared memory buffer (shmbff).
 *              This function takes a pointer to the shared memory
 *              segment and read from it. It checks if it has read access P()
 *              if yes then it decrease the value and reads from the buffer
 *              and release the segment to another process waiting with V().
 *              Then returns the read value.
 *
 * @result      An int ( the read value on success and -1 on failure(or exit(EXIT_FAILURE))).
 */
static int shmseg_easy_read(void) {

    if (shmbff == (void *) -1) {
        fprintf(stderr, "Oops : %s ->: Please initialize the shared memory"
                " segment before you can read from buffer\n", programmName);
        exit(EXIT_FAILURE);
    }

    int data, l;
    static size_t indx = 0;

    do {
        errno = 0;
        l = P(shmsgpr->semid[1]);

    } while (l == -1 && errno == EINTR);

    if (l == -1) {
        fprintf(stderr, " P() : %s %s \n", programmName, strerror(errno));
        (void) shmseg_easy_clean(shmsgpr);
        return -1;
    }

    data = shmbff[(indx++) % shmssize_g];

    do {
        l = V(shmsgpr->semid[0]);

    } while (l == -1 && errno == EINTR);

    if (l == -1) {

        fprintf(stderr, " V() : %s %s \n", programmName, strerror(errno));
        (void) shmseg_easy_clean(shmsgpr);
        return -1;
    }

    return data;

}

/*!
 * @brief       delete all the semaphores and (if detached by others) shared memory.
 *              This function takes a pointer to the shared memory segment to
 *              delete. try to delete the semaphores and detach the shared memory if is
 *              not already done and then delete the shared memory buffer.
 * @param       shm    The shared memory segment to delete.
 *
 * @result      An int ( 0 on success and 1 on failure).
 */
int shmseg_easy_clean(shmseg *shm) {

    if (shm->semid[0] != -1 && shm->semid[1] != -1) {
        for (int i = 0; i < 2; ++i) {
            if (semrm(shm->semid[i]) == -1) {
                fprintf(stderr, "semrm: %s %s\n", programmName, strerror(errno));
                return EXIT_FAILURE;
            }
        }

    }

    shm->detach(shm);

    if (shmbff != (void *) -1) {
        if (shmctl(shm->shmid, IPC_RMID, NULL) == -1) {
            fprintf(stderr, "%s ->  shmctl: %s \n", programmName, strerror(errno));
            return EXIT_FAILURE;
        }
    }

    shmbff = (void *) -1;
    shm->shmid = -1;
    shm->semid[0] = -1;
    shm->semid[1] = -1;

    shm->detach = NULL;
    shm->s_read = NULL;
    shm->s_read = NULL;

    return EXIT_SUCCESS;

}

/**
 * @brief       detaches the shared memory segment
 *              allocated at the shmbff's address
 *@param    void
 *@result   nothing.
 */
static void detach(shmseg *shm) {
    if (shmbff != (void *) -1) {
        //errno = 0;
        if (shmdt(shmbff) == -1) {
            fprintf(stderr, "shmdt: %s %s \n", programmName, strerror(errno));
            shmseg_easy_clean(shm);
            exit(EXIT_FAILURE);
        }
    }
}


text:
module Igdb::CompanyRepresenter
  include Representable::JSON

  property :id # The id of the game.
  property :name # The name of the company.
  property :average_rating # The average rating of all the games the company that has developed or published.
  property :parent # The id of the parent company.
  property :size # The number of companies in the database.

  collection_representer class: Igdb::Game
end

redpajama_set_name: RedPajamaGithub


text:
  public function executeUpdate(sfWebRequest $request)
  {
    $this-><?php echo $this->getSingularName() ?> = $this->getRoute()->getObject();
    $this->form = $this->configuration->getForm($this-><?php echo $this->getSingularName() ?>);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }


text:
import { combineReducers } from 'redux'
import { reducer as formReducer } from 'redux-form'
import { routerReducer } from 'react-router-redux'

// here import all your reducers from all your modules
import userSessionReducer from './userSession.reducer'
import healthcheckReducer from './healthcheck.reducer'
import apiResponseModalReducer from './apiResponse.reducer'
import apiListReducer from './apiList.reducer'
import apiReducer from './api.reducer'
import searchReducer from './search.reducer'
import requestReducer from './request.reducer'
import oAuthServersListReducer from './oAuthServersList.reducer'
import oAuthServerReducer from './oAuthServer.reducer'
import paginationReducer from './pagination.reducer'
import confirmationReducer from './confirmation.reducer'

export default combineReducers({
  // here combine all reducers:
  userSessionReducer,
  healthcheckReducer,
  apiResponseModalReducer,
  apiListReducer,
  apiReducer,
  paginationReducer,
  searchReducer,
  requestReducer,
  oAuthServersListReducer,
  oAuthServerReducer,
  confirmationReducer,
  form: formReducer,
  routing: routerReducer
})


text:
package com.peterphi.std.guice.common.auth;

import com.google.common.base.MoreObjects;
import com.peterphi.std.guice.common.auth.annotations.AuthConstraint;

import java.util.Arrays;
import java.util.List;

public class AuthScope
{
	private final String name;
	private final List<String> roles;
	private final Boolean skip;
	private final Boolean forceSkip;

	public AuthScope(final String name, final List<String> roles, final Boolean skip, final Boolean forceSkip)
	{
		this.name = name;
		this.roles = roles;
		this.skip = skip;
		this.forceSkip = forceSkip;
	}

	/**
	 * Determine the value of "skip" for a given (optionally annotated) method. The rule for this is:
	 *

	 *
If config contains force-skip, use that value

	 *
If AuthConstraint annotation is present and skip is true, the result is true (e.g. for login pages and other open resources)

	 *
Otherwise, if there's a value in config for "skip", use that

	 *
Otherwise, if the AuthConstraint annotation is present, use the skip value from that

	 *
Otherwise (e.g. for no AuthConstraint annotated REST methods), the default is not to skip

	 *

	 *
	 * @param annotation
	 * @return
	 */
	public boolean getSkip(AuthConstraint annotation)
	{
		if (forceSkip != null)
			return forceSkip;
		else if (annotation != null && annotation.skip())
			return true; // N.B. if the annotation instructs that we skip auth then we should do this (since this will be for e.g. login resources)
		else if (this.skip != null)
			return skip;
		else if (annotation != null)
			return annotation.skip();
		else
			return false; // Default to not skipping
	}

	/**
	 * Determine the required role for a given (optionally annotated) method. The rule for this is simple priority:
	 *

	 *
Roles specified in config for this scope id

	 *
Annotated roles

	 *
If no annotation and no configured roles, throw an IllegalArgumentException

	 *

	 *
	 * @param annotation
	 * @return
	 * @throws IllegalArgumentException If no annotation and no configured role
	 */
	public List<String> getRoles(AuthConstraint annotation) throws IllegalArgumentException
	{
		if (this.roles != null)
			return roles;
		else if (annotation != null)
			return Arrays.asList(annotation.role());
		else
			throw new IllegalArgumentException("No override roles and no annotation to default to!");
	}

	@Override
	public String toString()
	{
		return MoreObjects.toStringHelper(this).add("name", name).add("roles", roles).add("skip", skip).toString();
	}
}


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

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>Tree</title>

		Photo Albums

Family

Mom's side

Ohio

Akron

Apple Creek

Barberton

Alabama

California

Dad's side

New York

Manhatton

Rochester

Buffalo

Ohio

Florida

Summer Vacation

Bermuda

Bahama

Aruba

Papa New Guinea

Winter Vacation

Djibouti

New Dehli

Siberia

Home

Garden

Back Yard

Front Yard

Miscellaneous


text:
package com.zobot.client.packet.definitions.clientbound.play

import com.zobot.client.packet.Packet

case class Camera(cameraId: Int) extends Packet {
  override lazy val packetId = 0x39

  override lazy val packetData: Array[Byte] =
    fromVarInt(cameraId)
}


text:
//
//  MKBuyBid.m
//  BitMarkets
//
//  Created by Steve Dekorte on 5/6/14.
//  Copyright (c) 2014 voluntary.net. All rights reserved.
//

#import "MKBuyBid.h"
#import "MKMsg.h"
#import "MKBidMsg.h"
#import "MKAcceptBidMsg.h"
#import "MKRejectBidMsg.h"
#import "MKBuy.h"
#import "MKBuyLockEscrow.h"

@implementation MKBuyBid

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

    /*
    {
        NavActionSlot *slot = [self.navMirror newActionSlotWithName:@"cancelBid"];
        [slot setVisibleName:@"Cancel Bid"];
    }
    */

    return self;
}

// --- titles -------------

- (NSNumber *)nodeSuggestedWidth
{
    return @350;
}

- (NSString *)nodeTitle
{
    return @"Bid";
}

- (NSString *)nodeSubtitle
{
    return self.status;
}

- (NSString *)nodeNote
{
    if (self.isActive)
    {
        return @"●";
    }

    if (self.wasAccepted)
    {
        return @"✓";
    }

    if (self.wasRejected)
    {
        return @"✗";
    }

    return nil;
}

- (void)sortChildren
{
    [super sortChildrenWithKey:@"date"];
}

// messages

- (MKBidMsg *)bidMsg
{
    return [self.children firstObjectOfClass:MKBidMsg.class];
}

- (MKAcceptBidMsg *)acceptMsg
{
    return [self.children firstObjectOfClass:MKAcceptBidMsg.class];
}

- (MKRejectBidMsg *)rejectMsg
{
    return [self.children firstObjectOfClass:MKRejectBidMsg.class];
}

// status

- (BOOL)wasSent
{
    return self.bidMsg != nil;
}

- (BOOL)wasAccepted
{
    return self.acceptMsg != nil;
}

- (BOOL)wasRejected
{
    return self.rejectMsg != nil;
}

// --- status -------------

- (BOOL)isComplete
{
    return self.wasAccepted || self.wasRejected;
}

- (BOOL)isActive
{
    return (self.children.count && !self.isComplete);
}

- (MKBuy *)buy
{
    return (MKBuy *)self.nodeParent;
}

- (NSString *)status
{
    if (self.children.count == 0)
    {
        return @"no bid sent";
    }

    if (self.children.count == 1)
    {
        return @"bid sent, awaiting reply";
    }

    if (self.wasAccepted)
    {
        return @"bid accepted";
    }

    if (self.wasRejected)
    {
        return @"bid rejected";
    }

    // add timeout check

    return nil;
}

// --- messages -------------

- (BOOL)handleMsg:(MKMsg *)msg
{
    if ([msg isKindOfClass:MKAcceptBidMsg.class])
    {
        if ([self addChild:msg])
        {
            [self.buy update];
        }

        [self postParentChainChanged];
        return YES;
    }

    if ([msg isKindOfClass:MKRejectBidMsg.class])
    {
        [self addChild:msg];
        [self postParentChainChanged];
        return YES;
    }

    return NO;
}

// actions

- (void)cancelBid
{

}

@end


text:
package org.cagrid.gaards.dorian.federation;

import org.cagrid.gaards.dorian.stubs.types.DorianInternalFault;
import org.cagrid.gaards.dorian.stubs.types.UserPolicyFault;

/**
 * @author Stephen Langella
 * @author Scott Oster
 * @author Shannon Hastings
 * @version $Id: ArgumentManagerTable.java,v 1.2 2004/10/15 16:35:16 langella
 *          Exp $
 */
public abstract class AccountPolicy {

    private IdentityFederationProperties configuration;

    private UserManager userManager;

    public void configure(IdentityFederationProperties conf, UserManager um) {
        this.configuration = conf;
        this.userManager = um;
    }

    public abstract void applyPolicy(TrustedIdP idp, GridUser user) throws DorianInternalFault, UserPolicyFault;

    public IdentityFederationProperties getConfiguration() {
        return configuration;
    }

    public UserManager getUserManager() {
        return userManager;
    }

    public abstract String getDisplayName();
}


text:
gc() {
  sleep 2
  curl localhost:3000/gc
}

gc_restart() {
  gc
  sleep 2
  curl localhost:3000/shutdown
  sleep 2
}

curl localhost:3000/capture
gc
gc
curl localhost:3000/capture
gc
gc_restart

curl localhost:3000/capture_large_source
gc
gc
gc_restart

ab -c 5 -n 5000 localhost:3000/hello
gc_restart

ab -c 5 -n 5000 localhost:3000/context/basic
gc_restart

ab -c 5 -n 5000 localhost:3000/breadcrumbs/capture
gc_restart

ab -c 5 -n 5000 localhost:3000/breadcrumbs/auto/console
gc_restart

ab -c 5 -n 5000 localhost:3000/breadcrumbs/auto/http
gc_restart

ab -c 5 -n 2000 localhost:3000/hello?doError=true
gc_restart

ab -c 5 -n 2000 localhost:3000/context/basic?doError=true
gc_restart

ab -c 5 -n 2000 localhost:3000/breadcrumbs/capture?doError=true
gc_restart

ab -c 5 -n 2000 localhost:3000/breadcrumbs/auto/console?doError=true
gc_restart

ab -c 5 -n 2000 localhost:3000/breadcrumbs/auto/http?doError=true
gc_restart


text:
namespace app { namespace Uno { namespace Data { namespace Xml { struct XmlValue; } } } }

namespace app {
namespace Uno {
namespace Data {
namespace Xml {

struct XmlNode;

struct XmlNode__uType : ::uClassType
{
    ::app::Uno::Data::Xml::XmlValue*(*__fp_get_Value)(XmlNode*);
    void(*__fp_set_Value)(XmlNode*, ::app::Uno::Data::Xml::XmlValue*);
};

XmlNode__uType* XmlNode__typeof();

void XmlNode___ObjInit(XmlNode* __this);
void XmlNode___ObjInit_1(XmlNode* __this, ::uString* name, int nodeType, ::app::Uno::Data::Xml::XmlValue* value);
::uString* XmlNode__get_Name(XmlNode* __this);
int XmlNode__get_NodeType(XmlNode* __this);
::app::Uno::Data::Xml::XmlValue* XmlNode__get_Value(XmlNode* __this);
void XmlNode__set_Name(XmlNode* __this, ::uString* value);
void XmlNode__set_NodeType(XmlNode* __this, int value);
void XmlNode__set_Value(XmlNode* __this, ::app::Uno::Data::Xml::XmlValue* value);

struct XmlNode : ::uObject
{
    int _NodeType;
    ::uStrong< ::uString*> _Name;
    ::uStrong< ::app::Uno::Data::Xml::XmlValue*> _Value;

    void _ObjInit() { XmlNode___ObjInit(this); }
    void _ObjInit_1(::uString* name, int nodeType, ::app::Uno::Data::Xml::XmlValue* value) { XmlNode___ObjInit_1(this, name, nodeType, value); }
    ::uString* Name() { return XmlNode__get_Name(this); }
    int NodeType() { return XmlNode__get_NodeType(this); }
    ::app::Uno::Data::Xml::XmlValue* Value() { return (((XmlNode__uType*)this->__obj_type)->__fp_get_Value)(this); }
    void Name(::uString* value) { XmlNode__set_Name(this, value); }
    void NodeType(int value) { XmlNode__set_NodeType(this, value); }
    void Value(::app::Uno::Data::Xml::XmlValue* value) { (((XmlNode__uType*)this->__obj_type)->__fp_set_Value)(this, value); }
};

}}}}

#endif


text:
using UnityEngine;
using System.Collections;

public class BGTowerMovement : MonoBehaviour {

    [SerializeField] private float fTowerSetting = 1.0f;

    [SerializeField] private float fSinePower = 1f;
    [SerializeField] private float fSineSpeed = 0.3f;
    [SerializeField] private float fRotateMaxSpeed = 4f;
    private Vector3 OrigPos;

    void Start()
    {
        OrigPos = gameObject.transform.position;
        StartCoroutine("Sine");
    }
    IEnumerator Sine()
    {
        float _Pow = fSinePower * fTowerSetting;
        float _Spd = fSineSpeed * fTowerSetting;
        float _Rot = Random.Range(0f, fRotateMaxSpeed);

        float _RandStart = Random.Range(0f, 15f);
        yield return new WaitForSeconds(_RandStart);

        _RandStart = 0f;
        while (true)
        {
            _RandStart += Time.deltaTime;
            gameObject.transform.position = OrigPos + Vector3.up * Mathf.Sin(_RandStart * _Spd) * _Pow;
            gameObject.transform.Rotate(0f, _Rot * Time.deltaTime, 0f);
            yield return new WaitForEndOfFrame();
        }
    }
}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.lenovo.leoss"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <mvc:resources mapping="/assets/**" location="/WEB-INF/assets/" />
    <mvc:annotation-driven />

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename" value="i18n/messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
    <bean id="/error" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
        <property name="viewName" value="error" />
    </bean>

</beans>


text:
function ProdutosDAO(connection){
  this._connection = connection;
}

ProdutosDAO.prototype.lista = function(callback) {
  this._connection.query('SELECT * FROM produtos', callback);
}

ProdutosDAO.prototype.salva = function(produto,callback) {
  this._connection.query('INSERT INTO produtos set ?', produto, callback);
}

module.exports = function(){
  return ProdutosDAO;
}


text:
import csv
import logging
import tablib
from datetime import datetime
from django.db.models import Model
from django.db.models.fields.files import FieldFile
from unicodedata import normalize
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.template import Context, Template
from django.conf import settings
from django.core.urlresolvers import reverse

def export_as_excel(modeladmin, request, queryset):
    if not request.user.is_staff:
        raise PermissionDenied
    opts = modeladmin.model._meta
    response = HttpResponse(mimetype='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'attachment; filename=%s.xls' % unicode(opts).replace('.', '_')
    try:
        field_names = modeladmin.model.get_csv_fields()
        v_field_names = field_names
    except:
        field_names = [field.name for field in opts.fields]
        v_field_names = [getattr(field, 'verbose_name') or field.name for field in opts.fields]
    v_field_names = map(lambda x: x.encode('utf-8') if x != 'ID' else 'Id', v_field_names)

    ax = []
    headers = v_field_names

    data = []

    data = tablib.Dataset(*data, headers=headers)
    for obj in queryset:
        acc = []
        for field in field_names:
            try:
                uf = getattr(obj, field)()
            except TypeError:
                try:
                    uf = getattr(obj, field)
                except:
                    uf = ' error obteniendo el dato'
            if uf is None:
                uf = ''
            elif isinstance(uf, datetime):
                uf = unicode(uf)
            elif isinstance(uf, Model):
                uf = unicode(uf)
            elif isinstance(uf, FieldFile):
                uf = uf.url
            acc.append(uf)
        data.append(acc)
    response.write(data.xls)
    return response

export_as_excel.short_description = "Exportar como Excel"


text:
declare module qtek {

    export module light {

        interface ISpotLightOption extends ILightOption {
            range?: number;
            umbraAngle?: number;
            penumbraAngle?: number;
            falloffFactor?: number;

            shadowBias?: number;
            shadowSlopeScale?: number;
        }

        export class Spot extends Light {

            constructor(option?: ISpotLightOption);

            range: number;

            umbraAngle: number;

            penumbraAngle: number;

            falloffFactor: number;

            shadowBias: number;

            shadowSlopeScale: number;

            type: string;

            uniformTemplates : {

                spotLightPosition: ILightUniformTemplate<number[]>;

                spotLightRange: ILightUniformTemplate<number>;

                spotLightUmbraAngleCosine: ILightUniformTemplate<number>;

                spotLightPenumbraAngleCosine: ILightUniformTemplate<number>;

                spotLightFalloffFactor: ILightUniformTemplate<number>;

                spotLightDirection: ILightUniformTemplate<number[]>;

                spotLightColor: ILightUniformTemplate<number[]>;
            }
        }
    }
}


text:
#ifndef _ASM_MICROBLAZE_MODULE_H
#define _ASM_MICROBLAZE_MODULE_H

#include <asm-generic/module.h>

/* Microblaze Relocations */
#define R_MICROBLAZE_NONE 0
#define R_MICROBLAZE_32 1
#define R_MICROBLAZE_32_PCREL 2
#define R_MICROBLAZE_64_PCREL 3
#define R_MICROBLAZE_32_PCREL_LO 4
#define R_MICROBLAZE_64 5
#define R_MICROBLAZE_32_LO 6
#define R_MICROBLAZE_SRO32 7
#define R_MICROBLAZE_SRW32 8
#define R_MICROBLAZE_64_NONE 9
#define R_MICROBLAZE_32_SYM_OP_SYM 10
/* Keep this the last entry. */
#define R_MICROBLAZE_NUM 11

typedef struct { volatile int counter; } module_t;

#endif /* _ASM_MICROBLAZE_MODULE_H */


text:
/**
 *
 */
package com.qmx.wxmp.webservice.rest.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qmx.wxmp.webservice.rest.Result;
import com.qmx.wxmp.webservice.rest.Result.Status;
import com.qmx.wxmp.webservice.rest.RsResponse;

/**
 * <p> Title: </p>
 *
 * <p> Description: </p>
 *
 * <p> Copyright: Copyright (c) 2014 by Free-Lancer </p>
 *
 * <p> Company: Free-Lancer </p>
 *
 * @author: free lance
 * @Email: free.lance@Gmail.com
 * @version: 2.0
 * @date: 2014-12-29 上午11:42:24
 *
 */
@Path("/file")
public class FileRestResource {

    private static Logger logger = LoggerFactory.getLogger(FileRestResource.class);

    @Context
    ServletContext context;

    /**
     * 上传文件
     *
     * @param inputStream
     * @param contentDisposition
     * @param context
     * @return
     */
    @POST
    @Path("/upload")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Result<String> uploadFile(@FormDataParam("file") InputStream fileInputStream,
            @FormDataParam("file") FormDataContentDisposition contentDispositionHeader) throws FileNotFoundException,
            IOException {
        String result = "文件上传失败";
        if (contentDispositionHeader != null && contentDispositionHeader.getFileName() != null
                && contentDispositionHeader.getFileName().trim().length() > 0) {
            try {
                // 处理中文编码
                String realPath = context.getRealPath("upload");

                String fileName = new String(contentDispositionHeader.getFileName().getBytes("ISO-8859-1"), "UTF-8");

                String uploadedFileLocation = realPath + File.separatorChar + getUploadCurrentTime() + fileName;

                // save the file to the server
                OutputStream outpuStream = new FileOutputStream(new File(uploadedFileLocation));
                int read = 0;
                // byte[] bytes = new byte[1024];
                byte[] buffer = new byte[4 * 1024];

                outpuStream = new FileOutputStream(new File(uploadedFileLocation));
                while ((read = fileInputStream.read(buffer)) != -1) {
                    outpuStream.write(buffer, 0, read);
                }
                outpuStream.flush();
                outpuStream.close();

                result = "文件:[" + uploadedFileLocation + "]上传成功";

            } catch (RuntimeException e) {
                logger.error(e.getMessage());
                // throw new RuntimeException(Response.Status.EXPECTATION_FAILED+": 文件上传失败");
                throw RsResponse.buildDefaultException(e);
            }
        }

        return Result.buildResult(Status.OK, result);

    }

    // 获取头上上传的当前时间
    private String getUploadCurrentTime() {

        return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    }
}


text:
namespace StudentSystem.Services.Controllers
{
    using System.Collections.Generic;
    using System.Web.Http;

    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.0
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Chameleon.UpdateWallpaper.WinformServiceHost.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Chameleon.UpdateWallpaper.WinformServiceHost.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap about {
            get {
                object obj = ResourceManager.GetObject("about", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap admin {
            get {
                object obj = ResourceManager.GetObject("admin", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
        /// </summary>
        internal static System.Drawing.Icon chameleon {
            get {
                object obj = ResourceManager.GetObject("chameleon", resourceCulture);
                return ((System.Drawing.Icon)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap exit {
            get {
                object obj = ResourceManager.GetObject("exit", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Do you want to stop updating desktop wallpaper and exit Chameleon Desktop service?.
        /// </summary>
        internal static string ExitConfirm {
            get {
                return ResourceManager.GetString("ExitConfirm", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Message.
        /// </summary>
        internal static string MessageBoxTitle {
            get {
                return ResourceManager.GetString("MessageBoxTitle", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to No Chameleon Installed.
        /// </summary>
        internal static string NoChameleonInstalled {
            get {
                return ResourceManager.GetString("NoChameleonInstalled", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Do not find Chameleon Windows Store App in your system, Chameleon App only works on Windows 8.1 and later. Please download Chameleon app from Windows Store: http://apps.microsoft.com/windows/app/fa822ed6-c51d-4e3a-a2de-db7adf81eef0.
        /// </summary>
        internal static string NotDetectChameleonApp {
            get {
                return ResourceManager.GetString("NotDetectChameleonApp", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap running {
            get {
                object obj = ResourceManager.GetObject("running", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap start {
            get {
                object obj = ResourceManager.GetObject("start", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap stop {
            get {
                object obj = ResourceManager.GetObject("stop", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Looks up a localized resource of type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap stopped {
            get {
                object obj = ResourceManager.GetObject("stopped", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
    }
}


text:
module ResourceBundlesHelper
    def add_resource_bundle_link(text, server)
        link_to_function text do |page|
            page[:add_resource_bundle].hide
            page[:new_resource_bundle].appear
        end
    end

    def cancel_add_resource_bundle_button(text, server)
        button_to_function text do |page|
            page[:new_resource_bundle].hide
            page[:add_resource_bundle].appear
        end
    end

   	def start_server_resource_bundle_link(text, server, resource_bundle)
		if resource_bundle.is_default? or resource_bundle.instance_id.blank?
			url = start_server_resource_bundle_url(resource_bundle.server, resource_bundle)
			link_text = image_tag("start.png", :class => 'control-icon', :alt => text)
			options = {
			    :url => url,
			    :method => :post,
			    :with => "'resource_bundle_id=#{resource_bundle.id}'",
			}
			html_options = {
				:title => "Start an instance of this server using this launch configuration",
			    :href => url,
			    :method => :post,
			    :with => "'resource_bundle_id=#{resource_bundle.id}'",
			}
			link_to_remote link_text, options, html_options
		else
			image_tag("start.png",
				:class => 'control-icon-disabled',
				:alt => text,
				:title => "Another instance uses this non-default configuration"
			)
		end
	end

   	def remove_resource_bundle_link(text, server, resource_bundle)
		if resource_bundle.instance_id.blank?
			url = server_resource_bundle_url(server, resource_bundle)
			link_text = image_tag("trash.png", :class => 'control-icon', :alt => text)
	    	options = {
	            :url => url,
	            :method => :delete,
	            :confirm => "Are you sure you want to remove\nthis launch configuration?",
			}
			html_options = {
				:title => "Remove this bundle from server '#{server.name}'",
	            :href => url,
	            :method => :delete,
			}
			link_to_remote link_text, options, html_options
		else
			image_tag("trash.png",
				:class => 'control-icon-disabled',
				:alt => text,
				:title => "This launch configuration is currently in use and cannot be deleted."
			)
		end
	end

   	def make_default_resource_bundle_link(text, server, resource_bundle)
		if resource_bundle.is_default?
			image_tag("acquire.png",
				:class => 'control-icon-disabled',
				:alt => text,
				:title => "This is default configuration"
			)
		else
			url = make_default_server_resource_bundle_url(server, resource_bundle)
			link_text = image_tag("acquire.png", :class => 'control-icon', :alt => text)
			options = {
			    :url => url,
			    :method => :post,
			}
			html_options = {
				:title => "Make this configuration default configuration",
			    :href => url,
			    :method => :post,
			}
			link_to_remote link_text, options, html_options
		end
	end
end


text:
package com.charmyin.cmstudio.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.junit.Test;

public class DateTimeUtil {

	/**
	 * 获取一个月的最后一天
	 *
	 * @param year
	 *            yyyy
	 * @param month
	 *            MM
	 * @return
	 */
	public static String getLastDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));
		return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
	}

	/**
	 * 获取一个月的第一天
	 *
	 * @param year
	 *            yyyy
	 * @param month
	 *            MM
	 * @return
	 */
	public static String getFirstDayOfMonth(int year, int month) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, year);
		cal.set(Calendar.MONTH, month);
		cal.set(Calendar.DAY_OF_MONTH, cal.getMinimum(Calendar.DATE));
		return new SimpleDateFormat("yyyy-MM-dd ").format(cal.getTime());
	}

	/**
	 * 获取某年中某一个月的天数
	 *
	 * @param dyear
	 *            yyyy
	 * @param dmouth
	 *            MM
	 * @return
	 */
	public static int calDayByYearAndMonth(String dyear, String dmouth) {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy/MM");
		Calendar rightNow = Calendar.getInstance();
		try {
			rightNow.setTime(simpleDate.parse(dyear + "/" + dmouth));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);// 根据年月 获取月份天数
	}

	/**
	 * 计算两个日期之间相差的天数
	 *
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		/*smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));*/
		//System.out.println("smdate:"+sdf.format(smdate)+"-----bdate:"+sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 字符串的日期格式的计算
	 *
	 * @param smdate
	 *            yyyy-MM-dd
	 * @param bdate
	 *            yyyy-MM-dd
	 * @return
	 * @throws ParseException
	 */
	public static int daysBetween(String smdate, String bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(smdate));
		long time1 = cal.getTimeInMillis();
		cal.setTime(sdf.parse(bdate));
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 获取当前日期的季度 1.
	 * 第一季度:1月1号,3月31号 2.
	 * 第二季度:4月1号,6月30号 3.
	 * 第三季度:7月1号,9月30号 4.
	 * 第四季度:10月1号,12月31号
	 */
	public static int getCurrentQuarter() throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowDate = sdf.format(new Date());
		Calendar cal = Calendar.getInstance();
		int currentYear = cal.get(Calendar.YEAR);
		if (daysBetween(currentYear + "-4-1", nowDate) < 0) {
			return 1;
		} else if (daysBetween(currentYear + "-7-1", nowDate) < 0) {
			return 2;
		} else if (daysBetween(currentYear + "-10-1", nowDate) < 0) {
			return 3;
		} else {
			return 4;
		}
	}

	/**
	 * 获取当前时间在当前季度中所属天数
	 *
	 * @return
	 * @throws ParseException
	 */
	public static int getCurrentDaysCountInCurrentQuarter() throws ParseException{
    	int i = DateTimeUtil.getCurrentQuarter();
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
   	 	String nowDate = sdf.format(new Date());
	   	Calendar cal = Calendar.getInstance();
		int currentYear = cal.get(Calendar.YEAR);
    	switch(i){
    		case 1:
    			return daysBetween(currentYear + "-1-1", nowDate)+1;
    		case 2:
    			return daysBetween(currentYear + "-4-1", nowDate)+1;
    		case 3:
    			return daysBetween(currentYear + "-7-1", nowDate);
    		case 4:
    			return daysBetween(currentYear + "-10-1", nowDate);
    		default:
    			return 0;
    	}
    }

	/**
	 * 获取日期的季度
	 */
	public static int getQuarterByDateString(String dateStr) {
		return 1;
	}

	public static String dateToString(Date date) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		return sdf.format(date);
	}

}


text:
#pragma once
#include <aws/redshift/Redshift_EXPORTS.h>
#include <aws/redshift/model/ResponseMetadata.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Xml
{
  class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace Redshift
{
namespace Model
{
  class AWS_REDSHIFT_API DescribeStorageResult
  {
  public:
    DescribeStorageResult();
    DescribeStorageResult(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
    DescribeStorageResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);

    /**
     *
The total amount of storage currently used for snapshots.

     */
    inline double GetTotalBackupSizeInMegaBytes() const{ return m_totalBackupSizeInMegaBytes; }

    /**
     *
The total amount of storage currently used for snapshots.

     */
    inline void SetTotalBackupSizeInMegaBytes(double value) { m_totalBackupSizeInMegaBytes = value; }

    /**
     *
The total amount of storage currently used for snapshots.

     */
    inline DescribeStorageResult& WithTotalBackupSizeInMegaBytes(double value) { SetTotalBackupSizeInMegaBytes(value); return *this;}

    /**
     *
The total amount of storage currently provisioned.

     */
    inline double GetTotalProvisionedStorageInMegaBytes() const{ return m_totalProvisionedStorageInMegaBytes; }

    /**
     *
The total amount of storage currently provisioned.

     */
    inline void SetTotalProvisionedStorageInMegaBytes(double value) { m_totalProvisionedStorageInMegaBytes = value; }

    /**
     *
The total amount of storage currently provisioned.

     */
    inline DescribeStorageResult& WithTotalProvisionedStorageInMegaBytes(double value) { SetTotalProvisionedStorageInMegaBytes(value); return *this;}

    inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }

    inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }

    inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }

    inline DescribeStorageResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}

    inline DescribeStorageResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}

  private:

    double m_totalBackupSizeInMegaBytes;

    double m_totalProvisionedStorageInMegaBytes;

    ResponseMetadata m_responseMetadata;
  };

} // namespace Model
} // namespace Redshift
} // namespace Aws


text:
<?php

namespace Swarrot\Processor;

interface InitializableInterface extends ProcessorInterface
{
    /**
     * initialize.
     */
    public function initialize(array $options);
}


text:
require 'rails_helper'

describe DiscoursePoll::PollsUpdater do
  let(:user) { Fabricate(:user) }

  let(:post_with_two_polls) do
    raw = <<-RAW.strip_heredoc
    [poll]
    * 1
    * 2
    [/poll]

    [poll name=test]
    * 1
    * 2
    [/poll]
    RAW

    Fabricate(:post, raw: raw)
  end

  let(:post) do
    raw = <<-RAW.strip_heredoc
    [poll]
    * 1
    * 2
    [/poll]
    RAW

    Fabricate(:post, raw: raw)
  end

  let(:other_post) do
    raw = <<-RAW.strip_heredoc
    [poll]
    * 3
    * 4
    * 5
    [/poll]
    RAW

    Fabricate(:post, raw: raw)
  end

  let(:polls) do
    DiscoursePoll::PollsValidator.new(post).validate_polls
  end

  let(:polls_with_3_options) do
    DiscoursePoll::PollsValidator.new(other_post).validate_polls
  end

  let(:two_polls) do
    DiscoursePoll::PollsValidator.new(post_with_two_polls).validate_polls
  end

  describe '.update' do
    describe 'when post does not contain any polls' do
      it 'should update polls correctly' do
        post = Fabricate(:post)

        message = MessageBus.track_publish do
          described_class.update(post, polls)
        end.first

        expect(post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]).to eq(polls)
        expect(message.data[:post_id]).to eq(post.id)
        expect(message.data[:polls]).to eq(polls)
      end
    end

    describe 'when post contains existing polls' do
      it "should be able to update polls correctly" do
        message = MessageBus.track_publish do
          described_class.update(post, polls_with_3_options)
        end.first

        expect(post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]).to eq(polls_with_3_options)
        expect(message.data[:post_id]).to eq(post.id)
        expect(message.data[:polls]).to eq(polls_with_3_options)
      end
    end

    describe 'when there are no changes' do
      it "should not do anything" do
        messages = MessageBus.track_publish do
          described_class.update(post, polls)
        end

        expect(messages).to eq([])
      end
    end

    context "public polls" do
      let(:post) do
        raw = <<-RAW.strip_heredoc
        [poll public=true]
        - A
        - B
        [/poll]
        RAW

        Fabricate(:post, raw: raw)
      end

      let(:private_poll_post) do
        raw = <<-RAW.strip_heredoc
        [poll]
        - A
        - B
        [/poll]
        RAW

        Fabricate(:post, raw: raw)
      end

      let(:private_poll) do
        DiscoursePoll::PollsValidator.new(private_poll_post).validate_polls
      end

      let(:public_poll) do
        raw = <<-RAW.strip_heredoc
        [poll public=true]
        - A
        - C
        [/poll]
        RAW

        DiscoursePoll::PollsValidator.new(Fabricate(:post, raw: raw)).validate_polls
      end

      before do
        DiscoursePoll::Poll.vote(post.id, "poll", ["5c24fc1df56d764b550ceae1b9319125"], user)
        post.reload
      end

      it "should not allow a private poll with votes to be made public" do
        DiscoursePoll::Poll.vote(private_poll_post.id, "poll", ["5c24fc1df56d764b550ceae1b9319125"], user)
        private_poll_post.reload

        messages = MessageBus.track_publish do
          described_class.update(private_poll_post, public_poll)
        end

        expect(messages).to eq([])

        expect(private_poll_post.errors[:base]).to include(
          I18n.t("poll.default_cannot_be_made_public")
        )
      end

      it "should retain voter_ids when options have been edited" do
        described_class.update(post, public_poll)

        polls = post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]

        expect(polls["poll"]["options"][0]["voter_ids"]).to eq([user.id])
        expect(polls["poll"]["options"][1]["voter_ids"]).to eq([])
      end

      it "should delete voter_ids when poll is set to private" do
        described_class.update(post, private_poll)

        polls = post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]

        expect(post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD])
          .to eq(private_poll)

        expect(polls["poll"]["options"][0]["voter_ids"]).to eq(nil)
        expect(polls["poll"]["options"][1]["voter_ids"]).to eq(nil)
      end
    end

    context "polls of type 'multiple'" do
      let(:min_2_post) do
        raw = <<-RAW.strip_heredoc
        [poll type=multiple min=2 max=3]
        - Option 1
        - Option 2
        - Option 3
        [/poll]
        RAW

        Fabricate(:post, raw: raw)
      end

      let(:min_2_poll) do
        DiscoursePoll::PollsValidator.new(min_2_post).validate_polls
      end

      let(:min_1_post) do
        raw = <<-RAW.strip_heredoc
        [poll type=multiple min=1 max=2]
        - Option 1
        - Option 2
        - Option 3
        [/poll]
        RAW

        Fabricate(:post, raw: raw)
      end

      let(:min_1_poll) do
        DiscoursePoll::PollsValidator.new(min_1_post).validate_polls
      end

      it "should be able to update options" do
        min_2_poll

        message = MessageBus.track_publish do
          described_class.update(min_2_post, min_1_poll)
        end.first

        expect(min_2_post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]).to eq(min_1_poll)
        expect(message.data[:post_id]).to eq(min_2_post.id)
        expect(message.data[:polls]).to eq(min_1_poll)
      end
    end

    describe "when poll edit window has expired" do
      let(:poll_edit_window_mins) { 6 }
      let(:another_post) { Fabricate(:post, created_at: Time.zone.now - poll_edit_window_mins.minutes) }

      before do
        described_class.update(another_post, polls)
        another_post.reload
        SiteSetting.poll_edit_window_mins = poll_edit_window_mins

        DiscoursePoll::Poll.vote(
          another_post.id,
          "poll",
          [polls["poll"]["options"].first["id"]],
          user
        )
      end

      it "should not allow new polls to be added" do
        messages = MessageBus.track_publish do
          described_class.update(another_post, two_polls)
        end

        expect(another_post.errors[:base]).to include(I18n.t(
          "poll.edit_window_expired.cannot_change_polls",
          minutes: poll_edit_window_mins
        ))

        expect(messages).to eq([])
      end

      it "should not allow users to edit options of current poll" do
        messages = MessageBus.track_publish do
          described_class.update(another_post, polls_with_3_options)
        end

        expect(another_post.errors[:base]).to include(I18n.t(
          "poll.edit_window_expired.op_cannot_edit_options",
          minutes: poll_edit_window_mins
        ))

        expect(messages).to eq([])
      end

      context "staff" do
        let(:another_user) { Fabricate(:user) }

        it "should not allow staff to add options if votes have been casted" do
          another_post.update_attributes!(last_editor_id: User.staff.first.id)

          messages = MessageBus.track_publish do
            described_class.update(another_post, polls_with_3_options)
          end

          expect(another_post.errors[:base]).to include(I18n.t(
            "poll.edit_window_expired.staff_cannot_add_or_remove_options",
            minutes: poll_edit_window_mins
          ))

          expect(messages).to eq([])
        end

        it "should allow staff to add options if no votes have been casted" do
          post.update_attributes!(
            created_at: Time.zone.now - 5.minutes,
            last_editor_id: User.staff.first.id
          )

          message = MessageBus.track_publish do
            described_class.update(post, polls_with_3_options)
          end.first

          expect(post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]).to eq(polls_with_3_options)
          expect(message.data[:post_id]).to eq(post.id)
          expect(message.data[:polls]).to eq(polls_with_3_options)
        end

        it "should allow staff to edit options even if votes have been casted" do
          another_post.update!(last_editor_id: User.staff.first.id)

          DiscoursePoll::Poll.vote(
            another_post.id,
            "poll",
            [polls["poll"]["options"].first["id"]],
            another_user
          )

          raw = <<-RAW.strip_heredoc
          [poll]
          * 3
          * 4
          [/poll]
          RAW

          different_post = Fabricate(:post, raw: raw)
          different_polls = DiscoursePoll::PollsValidator.new(different_post).validate_polls

          message = MessageBus.track_publish do
            described_class.update(another_post, different_polls)
          end.first

          custom_fields = another_post.reload.custom_fields

          expect(custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD])
            .to eq(different_polls)

          [user, another_user].each do |u|
            expect(custom_fields[DiscoursePoll::VOTES_CUSTOM_FIELD][u.id.to_s]["poll"])
              .to eq(["68b434ff88aeae7054e42cd05a4d9056"])
          end

          expect(message.data[:post_id]).to eq(another_post.id)
          expect(message.data[:polls]).to eq(different_polls)
        end

        it "should allow staff to edit options if votes have not been casted" do
          post.update_attributes!(last_editor_id: User.staff.first.id)

          raw = <<-RAW.strip_heredoc
          [poll]
          * 3
          * 4
          [/poll]
          RAW

          different_post = Fabricate(:post, raw: raw)
          different_polls = DiscoursePoll::PollsValidator.new(different_post).validate_polls

          message = MessageBus.track_publish do
            described_class.update(post, different_polls)
          end.first

          expect(post.reload.custom_fields[DiscoursePoll::POLLS_CUSTOM_FIELD]).to eq(different_polls)
          expect(message.data[:post_id]).to eq(post.id)
          expect(message.data[:polls]).to eq(different_polls)
        end
      end
    end
  end

  describe '.extract_option_ids' do
    it 'should return an array of the options id' do
      expect(described_class.extract_option_ids(polls)).to eq(
        ["4d8a15e3cc35750f016ce15a43937620", "cd314db7dfbac2b10687b6f39abfdf41"]
      )
    end
  end

  describe '.total_votes' do
    let!(:post) do
      raw = <<-RAW.strip_heredoc
      [poll]
      * 1
      * 2
      [/poll]

      [poll name=test]
      * 1
      * 2
      [/poll]
      RAW

      Fabricate(:post, raw: raw)
    end

    it "should return the right number of votes" do
      expect(described_class.total_votes(polls)).to eq(0)

      polls.each { |key, value| value["voters"] = 2 }

      expect(described_class.total_votes(polls)).to eq(4)
    end
  end
end


text:
package org.spongepowered.common.accessor.network.chat;

import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.resources.ResourceLocation;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.common.UntransformedInvokerError;

@Mixin(Style.class)
public interface StyleAccessor {

    @Invoker("<init>")
    static Style invoker$new(final @Nullable TextColor color, final @Nullable Boolean bold, final @Nullable Boolean italic,
            final @Nullable Boolean underlined, final @Nullable Boolean strikethrough, final @Nullable Boolean obfuscated,
            final @Nullable ClickEvent clickEvent, final @Nullable HoverEvent hoverEvent, final @Nullable String insertion,
            final @Nullable ResourceLocation font) {
        throw new UntransformedInvokerError();
    }

    @Accessor("bold") Boolean accessor$bold();

    @Accessor("italic") Boolean accessor$italic();

    @Accessor("underlined") Boolean accessor$underlined();

    @Accessor("strikethrough") Boolean accessor$strikethrough();

    @Accessor("obfuscated") Boolean accessor$obfuscated();

    @Accessor("font") ResourceLocation accessor$font();

}


text:
import React, { PropTypes } from 'react';
import cx from 'classnames';
// import px from 'lib/px';
import Moment from 'moment';

import Styles from './Styles/main.scss';

import Flag from 'components/Assets/Icons/Flag';

Moment.locale('ru');

export default function Common(props) {
    const { items } = props;

    const scheduleItems = items.map((e, i) => {
        let isCurrent;

        if (items[i + 1]) {
            isCurrent = Moment().isSameOrAfter(e.date) && Moment().isBefore(items[i + 1].date);
        } else if ((Moment().isSameOrAfter(e.date) && i === items.length - 1)
            && (Moment().format('L') === Moment(e.date).format('L'))) {
            isCurrent = true;
        } else {
            isCurrent = false;
        }

        const itemClasses = cx({
            [Styles.item]: true,
            [Styles.now]: isCurrent
        });

        const background = isCurrent ? {
            backgroundImage: `url(${e.show.images.cover})`
        } : null;

        return (

                    { Moment(e.date).format('LT') }
                    сейчас

                <Flag language={ e.episode.language } className={ Styles.flag }/>

{ e.show.title }

{ e.show.description.short }

        );
    });

    return (

            { scheduleItems }

    );
}

Common.propTypes = {
    items: PropTypes.array.isRequired
};


text:
std::unique_ptr<net::ProxyConfigService>
ProxyServiceFactory::CreateProxyConfigService(PrefProxyConfigTracker* tracker) {
  std::unique_ptr<net::ProxyConfigService> base_service(
      net::ConfiguredProxyResolutionService::CreateSystemProxyConfigService(
          base::CreateSingleThreadTaskRunner({web::WebThread::IO})));
  return tracker->CreateTrackingProxyConfigService(std::move(base_service));
}

// static
std::unique_ptr<PrefProxyConfigTracker>
ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
    PrefService* browser_state_prefs,
    PrefService* local_state_prefs) {
  return std::make_unique<PrefProxyConfigTrackerImpl>(
      browser_state_prefs,
      base::CreateSingleThreadTaskRunner({web::WebThread::IO}));
}

// static
std::unique_ptr<PrefProxyConfigTracker>
ProxyServiceFactory::CreatePrefProxyConfigTrackerOfLocalState(
    PrefService* local_state_prefs) {
  return std::make_unique<PrefProxyConfigTrackerImpl>(
      local_state_prefs,
      base::CreateSingleThreadTaskRunner({web::WebThread::IO}));
}

// static
std::unique_ptr<net::ProxyResolutionService>
ProxyServiceFactory::CreateProxyResolutionService(
    net::NetLog* net_log,
    net::URLRequestContext* context,
    net::NetworkDelegate* network_delegate,
    std::unique_ptr<net::ProxyConfigService> proxy_config_service,
    bool quick_check_enabled) {
  DCHECK_CURRENTLY_ON(web::WebThread::IO);
  std::unique_ptr<net::ProxyResolutionService> proxy_resolution_service(
      net::ConfiguredProxyResolutionService::CreateUsingSystemProxyResolver(
          std::move(proxy_config_service), net_log, quick_check_enabled));
  return proxy_resolution_service;
}


text:
require 'rein/util'

module Rein
  module Constraint
    # This module contains methods for defining regex match constraints.
    module Match
      include ActiveRecord::ConnectionAdapters::Quoting

      OPERATORS = {
        accepts: :~,
        accepts_case_insensitive: :"~*",
        rejects: :"!~",
        rejects_case_insensitive: :"!~*"
      }.freeze

      def add_match_constraint(*args)
        reversible do |dir|
          dir.up { _add_match_constraint(*args) }
          dir.down { _remove_match_constraint(*args) }
        end
      end

      def remove_match_constraint(*args)
        reversible do |dir|
          dir.up { _remove_match_constraint(*args) }
          dir.down { _add_match_constraint(*args) }
        end
      end

      private

      def _add_match_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, 'match', options)
        table = Util.wrap_identifier(table)
        attribute = Util.wrap_identifier(attribute)
        conditions = OPERATORS.slice(*options.keys).map do |key, operator|
          value = options[key]
          [attribute, operator, "'#{value}'"].join(' ')
        end.join(' AND ')
        conditions = Util.conditions_with_if(conditions, options)
        sql = "ALTER TABLE #{table} ADD CONSTRAINT #{name} CHECK (#{conditions})"
        execute(Util.add_not_valid_suffix_if_required(sql, options))
      end

      def _remove_match_constraint(table, attribute, options = {})
        name = Util.constraint_name(table, attribute, 'match', options)
        table = Util.wrap_identifier(table)
        execute("ALTER TABLE #{table} DROP CONSTRAINT #{name}")
      end
    end
  end
end


text:
package com.openthinks.easyweb.annotation.configure;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * The request url suffixes, likes: <i>http://www.openthinks.com/api/add.do</i>
 * ".do" is the request url suffixes, it will be used to configure easy web framework.
 * @author minjdai
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RequestSuffixs {
	String value();
}


text:
<?php

namespace Doctrine\Common\Collections\Expr;

/**
 * Walks an expression graph and turns it into a PHP closure.
 *
 * This closure can be used with {@Collection#filter()} and is used internally
 * by {@ArrayCollection#select()}.
 *
 * @author Benjamin Eberlei <kontakt@beberlei.de>
 * @since 2.3
 */
class ClosureExpressionVisitor extends ExpressionVisitor
{
    /**
     * Access the field of a given object. This field has to be public directly
     * or indirectly (through an accessor get* or a magic method, __get, __call).
     *
     * is*() is not supported.
     *
     * @return mixed
     */
    static public function getObjectFieldValue($object, $field)
    {
        $accessor = "get" . $field;

        if (method_exists($object, $accessor) || method_exists($object, '__call')) {
            return $object->$accessor();
        }

        if ($object instanceof \ArrayAccess) {
            return $object[$field];
        }

        return $object->$field;
    }

    /**
     * Helper for sorting arrays of objects based on multiple fields +
     * orientations.
     *
     * @param string $name
     * @param int $orientation
     * @param Closure $next
     * @return Closure
     */
    static public function sortByField($name, $orientation = 1, \Closure $next = null)
    {
        if (!$next) {
            $next = function() {
                return 0;
            };
        }

        return function ($a, $b) use ($name, $next, $orientation) {
            $aValue = ClosureExpressionVisitor::getObjectFieldValue($a, $name);
            $bValue = ClosureExpressionVisitor::getObjectFieldValue($b, $name);

            if ($aValue === $bValue) {
                return $next($a, $b);
            }

            return (($aValue > $bValue) ? 1 : -1) * $orientation;
        };
    }

    /**
     * {@inheritDoc}
     */
    public function walkComparison(Comparison $comparison)
    {
        $field = $comparison->getField();
        $value = $comparison->getValue()->getValue(); // shortcut for walkValue()

        switch ($comparison->getOperator()) {
            case Comparison::EQ:
            case Comparison::IS:
                return function ($object) use ($field, $value) {
                    return ClosureExpressionVisitor::getObjectFieldValue($object, $field) === $value;
                };

            case Comparison::NEQ:
                return function ($object) use ($field, $value) {
                    return ClosureExpressionVisitor::getObjectFieldValue($object, $field) !== $value;
                };

            case Comparison::LT:
                return function ($object) use ($field, $value) {
                    return ClosureExpressionVisitor::getObjectFieldValue($object, $field) < $value;
                };

            case Comparison::LTE:
                return function ($object) use ($field, $value) {
                    return ClosureExpressionVisitor::getObjectFieldValue($object, $field) <= $value;
                };

            case Comparison::GT:
                return function ($object) use ($field, $value) {
                    return ClosureExpressionVisitor::getObjectFieldValue($object, $field) > $value;
                };

            case Comparison::GTE:
                return function ($object) use ($field, $value) {
                    return ClosureExpressionVisitor::getObjectFieldValue($object, $field) >= $value;
                };

            case Comparison::IN:
                return function ($object) use ($field, $value) {
                    return in_array(ClosureExpressionVisitor::getObjectFieldValue($object, $field), $value);
                };

            case Comparison::NIN:
                return function ($object) use ($field, $value) {
                    return ! in_array(ClosureExpressionVisitor::getObjectFieldValue($object, $field), $value);
                };

            default:
                throw new \RuntimeException("Unknown comparison operator: " . $comparison->getOperator());
        }
    }

    /**
     * {@inheritDoc}
     */
    public function walkValue(Value $value)
    {
        return $value->getValue();
    }

    /**
     * {@inheritDoc}
     */
    public function walkCompositeExpression(CompositeExpression $expr)
    {
        $expressionList = array();

        foreach ($expr->getExpressionList() as $child) {
            $expressionList[] = $this->dispatch($child);
        }

        switch($expr->getType()) {
            case CompositeExpression::TYPE_AND:
                return $this->andExpressions($expressionList);

            case CompositeExpression::TYPE_OR:
                return $this->orExpressions($expressionList);

            default:
                throw new \RuntimeException("Unknown composite " . $expr->getType());
        }
    }

    private function andExpressions($expressions)
    {
        return function ($object) use ($expressions) {
            foreach ($expressions as $expression) {
                if ( ! $expression($object)) {
                    return false;
                }
            }
            return true;
        };
    }

    private function orExpressions($expressions)
    {
        return function ($object) use ($expressions) {
            foreach ($expressions as $expression) {
                if ($expression($object)) {
                    return true;
                }
            }
            return false;
        };
    }
}


text:
import React, { Component } from 'react';

export default class Score extends Component {
  constructor(props) {
    super(props);

    this.state = {
      score: '0',
    }
  }

  scoreUp() {
    if (this.props.gameFinished) return;
    this.setState({score: Number(this.state.score) + 2 });
    if (this.state.score === 8) this.props.gameStatus();
    return
  }

  render() {
    return (

{ this.state.score }

        <button onClick={ this.scoreUp.bind(this) }
          className="btn">SCORE</button>

    );
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Bull. Torrey bot. Club 24: 147 (1897)

#### Original name
Cryptophallus Peck

### Remarks
null


text:
namespace CPM_CENTRAL_NS {

std::string centralFunction(CPM_CENTRAL_EXP_NS::CentralExportedClass& myStruct);
std::string centralFunction2(int num);

} // namespace CPM_CENTRAL_NS

#endif


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';

import { HomeComponent } from './home.component';

@NgModule({
  imports: [
    CommonModule,
    SharedModule
  ],
  declarations: [
    HomeComponent
  ]
})
export class HomeModule { }


text:
using System;
using System.Net;

namespace Reactor.Net
{
    public class NetworkCredential : ICredentials , ICredentialsByHost
    {
        // Fields
        private string userName;
        private string password;
        private string domain;

        // Constructors
        public NetworkCredential()
        {
        }

        public NetworkCredential(string userName, string password)
        {
            this.userName = userName;

            this.password = password;
        }

        public NetworkCredential(string userName, string password, string domain) : this(userName, password)
        {
            this.domain = domain;
        }

        // Properties

        public string Domain
        {
            get
            {
                return domain ?? String.Empty;
            }
            set
            {
                domain = value;
            }
        }

        public string UserName
        {
            get
            {
                return userName ?? String.Empty;
            }
            set
            {
                userName = value;
            }
        }

        public string Password
        {
            get
            {
                return password ?? String.Empty;
            }
            set
            {
                password = value;
            }
        }

        public NetworkCredential GetCredential(Uri uri, string authType)
        {
            return this;
        }

        public NetworkCredential GetCredential(string host, int port, string authenticationType)
        {
            return this;
        }

        System.Net.NetworkCredential ICredentialsByHost.GetCredential(string host, int port, string authenticationType)
        {
            throw new NotImplementedException();
        }

        System.Net.NetworkCredential ICredentials.GetCredential(Uri uri, string authType)
        {
            throw new NotImplementedException();
        }
    }
}


text:
package com.digitalpebble.stormcrawler.persistence;

import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.storm.metric.api.IMetric;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.digitalpebble.stormcrawler.Constants;
import com.digitalpebble.stormcrawler.Metadata;
import com.digitalpebble.stormcrawler.util.ConfUtils;
import com.digitalpebble.stormcrawler.util.MetadataTransfer;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * Abstract bolt used to store the status of URLs. Uses the DefaultScheduler and
 * MetadataTransfer.
 **/
@SuppressWarnings("serial")
public abstract class AbstractStatusUpdaterBolt extends BaseRichBolt {

    private static final Logger LOG = LoggerFactory
            .getLogger(AbstractStatusUpdaterBolt.class);

    /**
     * Parameter name to indicate whether the internal cache should be used for
     * discovered URLs. The value of the parameter is a boolean - true by
     * default.
     **/
    public static String useCacheParamName = "status.updater.use.cache";

    /** Number of successive FETCH_ERROR before status changes to ERROR **/
    public static String maxFetchErrorsParamName = "max.fetch.errors";

    /**
     * Parameter name to configure the cache @see
     * http://docs.guava-libraries.googlecode
     * .com/git/javadoc/com/google/common/cache/CacheBuilderSpec.html Default
     * value is "maximumSize=10000,expireAfterAccess=1h"
     **/
    public static String cacheConfigParamName = "status.updater.cache.spec";

    protected OutputCollector _collector;

    private Scheduler scheduler;
    private MetadataTransfer mdTransfer;

    private Cache<Object, Object> cache;
    private boolean useCache = true;

    private int maxFetchErrors = 3;

    private long cacheHits = 0;
    private long cacheMisses = 0;

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void prepare(Map stormConf, TopologyContext context,
            OutputCollector collector) {
        _collector = collector;

        scheduler = Scheduler.getInstance(stormConf);

        mdTransfer = MetadataTransfer.getInstance(stormConf);

        useCache = ConfUtils.getBoolean(stormConf, useCacheParamName, true);

        if (useCache) {
            String spec = ConfUtils.getString(stormConf, cacheConfigParamName);
            cache = CacheBuilder.from(spec).build();

            context.registerMetric("cache", new IMetric() {
                @Override
                public Object getValueAndReset() {
                    Map<String, Long> statsMap = new HashMap<>();
                    statsMap.put("hits", cacheHits);
                    statsMap.put("misses", cacheMisses);
                    statsMap.put("size", cache.size());
                    cacheHits = 0;
                    cacheMisses = 0;
                    return statsMap;
                }
            }, 30);
        }

        maxFetchErrors = ConfUtils
                .getInt(stormConf, maxFetchErrorsParamName, 3);
    }

    @Override
    public void execute(Tuple tuple) {

        String url = tuple.getStringByField("url");
        Status status = (Status) tuple.getValueByField("status");

        boolean potentiallyNew = status.equals(Status.DISCOVERED);

        // if the URL is a freshly discovered one
        // check whether it is already known in the cache
        // if so we've already seen it and don't need to
        // store it again
        if (potentiallyNew && useCache) {
            if (cache.getIfPresent(url) != null) {
                // no need to add it to the queue
                LOG.debug("URL {} already in cache", url);
                cacheHits++;
                _collector.ack(tuple);
                return;
            } else {
                LOG.debug("URL {} not in cache", url);
                cacheMisses++;
            }
        }

        Metadata metadata = (Metadata) tuple.getValueByField("metadata");

        // store last processed or discovery date in UTC
        final String nowAsString = Instant.now().toString();
        if (status.equals(Status.DISCOVERED)) {
            metadata.setValue("discoveryDate", nowAsString);
        } else {
            metadata.setValue("lastProcessedDate", nowAsString);
        }

        // too many fetch errors?
        if (status.equals(Status.FETCH_ERROR)) {
            String errorCount = metadata
                    .getFirstValue(Constants.fetchErrorCountParamName);
            int count = 0;
            try {
                count = Integer.parseInt(errorCount);
            } catch (NumberFormatException e) {
            }
            count++;
            if (count >= maxFetchErrors) {
                status = Status.ERROR;
                metadata.setValue(Constants.STATUS_ERROR_CAUSE,
                        "maxFetchErrors");
            } else {
                metadata.setValue(Constants.fetchErrorCountParamName,
                        Integer.toString(count));
            }
        }

        // delete any existing error count metadata
        // e.g. status changed
        if (!status.equals(Status.FETCH_ERROR)) {
            metadata.remove(Constants.fetchErrorCountParamName);
        }
        // https://github.com/DigitalPebble/storm-crawler/issues/415
        // remove error related key values in case of success
        if (status.equals(Status.FETCHED) || status.equals(Status.REDIRECTION)) {
            metadata.remove(Constants.STATUS_ERROR_CAUSE);
            metadata.remove(Constants.STATUS_ERROR_MESSAGE);
            metadata.remove(Constants.STATUS_ERROR_SOURCE);
        }

        // determine the value of the next fetch based on the status
        Date nextFetch = scheduler.schedule(status, metadata);

        // filter metadata just before storing it, so that non-persisted
        // metadata is available to fetch schedulers
        metadata = mdTransfer.filter(metadata);

        // extensions of this class will handle the storage
        // on a per document basis

        try {
            store(url, status, metadata, nextFetch);
        } catch (Exception e) {
            LOG.error("Exception caught when storing", e);
            _collector.fail(tuple);
            return;
        }

        // gone? notify any deleters. Doesn't need to be anchored
        if (status == Status.ERROR) {
            _collector.emit(Constants.DELETION_STREAM_NAME, new Values(url));
        }

        ack(tuple, url);
    }

    /**
     * Must be overridden for implementations where the actual writing can be
     * delayed e.g. put in a buffer
     **/
    protected void ack(Tuple t, String url) {
        // keep the URL in the cache
        if (useCache) {
            cache.put(url, "");
        }

        _collector.ack(t);
    }

    protected abstract void store(String url, Status status, Metadata metadata,
            Date nextFetch) throws Exception;

    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declareStream(Constants.DELETION_STREAM_NAME,
                new Fields("url"));
    }
}


text:
<?php
namespace Ratchet\Component\WebSocket\Version\Hixie76;
use Ratchet\Component\WebSocket\Version\FrameInterface;

/**
 * This does not entirely follow the protocol to spec, but (mostly) works
 * Hixie76 probably should not even be supported
 */
class Frame implements FrameInterface {
    /**
     * @type string
     */
    protected $_data = '';

    public function isCoalesced() {
        return (boolean)($this->_data[0] == chr(0) && substr($this->_data, -1) == chr(255));
    }

    public function addBuffer($buf) {
        $this->_data .= (string)$buf;
    }

    public function isFinal() {
        return true;
    }

    public function isMasked() {
        return false;
    }

    public function getOpcode() {
        return 1;
    }

    public function getPayloadLength() {
        if (!$this->isCoalesced()) {
            throw new \UnderflowException('Not enough of the message has been buffered to determine the length of the payload');
        }

        return strlen($this->_data) - 2;
    }

    public function getMaskingKey() {
        return '';
    }

    public function getPayload() {
        if (!$this->isCoalesced()) {
            return new \UnderflowException('Not enough data buffered to read payload');
        }

        return substr($this->_data, 1, strlen($this->_data) - 2);
    }
}


text:
using System.Collections.Generic;

namespace Meowplode.DAL.Models
{
    public class Question : BaseModel
    {
        public string Value { get; set; }

        public List<Option> Options { get; set; }
    }
}


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

namespace Enyim
{
	[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)]
	public class AsEventSourceAttribute : Attribute
	{
		public string Name { get; set; }
		public string Guid { get; set; }
	}
}

#region [ License information          ]

#endregion


text:
<?php

/**
 * @see Zym_App_Resource_Abstract
 */
require_once 'Zym/App/Resource/Abstract.php';

/**
 * @see Zym_Cache
 */
require_once 'Zym/Cache.php';

/**
 * Cache component configuration
 *
 * @author Geoffrey Tran
 * @license http://www.zym-project.com/license New BSD License
 * @category Zym
 * @package Zym_App
 * @subpackage Resource
 * @copyright  Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 */
class Zym_App_Resource_Cache extends Zym_App_Resource_Abstract
{
    /**
     * Priority
     *
     * @var integer
     */
    protected $_priority = self::PRIORITY_HIGH;

    /**
     * Default config
     *
     * @var array
     */
    protected $_defaultConfig = array(
        Zym_App::ENV_DEVELOPMENT => array(
            'frontend' => array(
                'core' => array(
                    'caching' => false
                ),

                'output' => array(
                    'caching' => false
                ),

                'function' => array(
                    'caching' => false
                ),

                'class' => array(
                    'caching' => false
                ),

                'file' => array(
                    'caching' => false
                ),

                'page' => array(
                    'caching' => false
                )
            )
        ),

        Zym_App::ENV_TEST => array(
            'frontend' => array(
                'core' => array(
                    'caching' => false
                ),

                'output' => array(
                    'caching' => false
                ),

                'function' => array(
                    'caching' => false
                ),

                'class' => array(
                    'caching' => false
                ),

                'file' => array(
                    'caching' => false
                ),

                'page' => array(
                    'caching' => false
                )
            )
        ),

        Zym_App::ENV_DEFAULT     => array(
            'default_backend' => 'file',

            'frontend' => array(
                'core' => array(
                    'automatic_serialization' => true
                )
            ),

            'backend' => array(
                'file' => array(
                    'cache_dir' => 'cache' // Relative to Zym_App::PATH_DATA
                ),

                'sqlite' => array(
                    'cache_db_complete_path' => 'cache/cache.sqlite'
                )
            )
        )
    );

    /**
     * Setup mail
     *
     * @param Zend_Config $config
     */
    public function setup(Zend_Config $config)
    {
        Zym_Cache::setConfig($config);

        // Set file cache dir
        $this->_prependPath($config->get('backend'));
    }

    /**
     * Prepend temp path to paths
     *
     * @param Zend_Config $config
     */
    protected function _prependPath(Zend_Config $config)
    {
        $app = $this->getApp();

        // File
        $fileOptions = Zym_Cache::getBackendOptions('file');
        if (isset($fileOptions['cache_dir'])) {
            $fileOptions['cache_dir'] = $app->getPath(Zym_App::PATH_DATA, $fileOptions['cache_dir']);
        }

        Zym_Cache::setBackendOptions('file', $fileOptions);

        // Sqlite
        $sqliteOptions = Zym_Cache::getBackendOptions('sqlite');
        if (isset($sqliteOptions['cache_db_complete_path'])) {
            $sqliteOptions['cache_db_complete_path'] = $app->getPath(Zym_App::PATH_TEMP, $sqliteOptions['cache_db_complete_path']);
        }

        Zym_Cache::setBackendOptions('sqlite', $sqliteOptions);
    }
}


text:
.cups
{
	border-bottom: solid black 5px;
	border-left : solid black 5px;
	border-right: solid black 5px;
	padding-left: 0px;
	padding-right: 0px;
	height: 500px;
	/*background-color : blue;*/
}

/*Forced overflow but hides it */
.cups_content
{
	overflow: hidden;
	height: 100%;
	background-color : #3498db;
	color : red;
	font-size : 16px;
	text-align: center;
	padding-left: 0px !important;
	padding-right: 0px !important;
	padding-bottom: 0px !important;
}

.cup_volume_description
{
	height: 50px;
	font-size: 20px;
	font-weight: bold;
		text-align: center;
	/*background-color : #f39c12;
	color: white;

	vertical-align: center;*/
}

#alert_notice
{
	display: none;
	text-align: center;
}

#step_notice
{
	display: none;
	text-align: center;
}

#main_presentation_screen
{
	display: none;
}


text:
exports.info = { FormatID: '1102',
  FormatName: 'Adaptive Multi-Rate Audio',
  FormatVersion: '',
  FormatAliases: '',
  FormatFamilies: '',
  FormatTypes: 'Audio',
  FormatDisclosure: '',
  FormatDescription: 'This is an outline record only, and requires further details, research or authentication to provide information that will enable users to further understand the format and to assess digital preservation risks associated with it if appropriate. If you are able to help by supplying any additional information concerning this entry, please return to the main PRONOM page and select 'Add an Entry'.',
  BinaryFileFormat: 'Text',
  ByteOrders: '',
  ReleaseDate: '',
  WithdrawnDate: '',
  ProvenanceSourceID: '1',
  ProvenanceName: 'Digital Preservation Department / The National Archives',
  ProvenanceSourceDate: '17 Jun 2011',
  ProvenanceDescription: '',
  LastUpdatedDate: '17 Jun 2011',
  FormatNote: '',
  FormatRisk: '',
  TechnicalEnvironment: '',
  FileFormatIdentifier:
   [ { Identifier: 'audio/amr', IdentifierType: 'MIME' },
     { Identifier: 'fmt/356', IdentifierType: 'PUID' } ],
  ExternalSignature:
   { ExternalSignatureID: '1124',
     Signature: 'amr',
     SignatureType: 'File extension' },
  InternalSignature:
   { SignatureID: '524',
     SignatureName: 'Adaptive Multi-Rate Audio',
     SignatureNote: 'Header (ASCII): #!AMR.',
     ByteSequence:
      { ByteSequenceID: '646',
        PositionType: 'Absolute from BOF',
        Offset: '0',
        MaxOffset: '',
        IndirectOffsetLocation: '',
        IndirectOffsetLength: '',
        Endianness: '',
        ByteSequenceValue: '2321414D520A' } },
  RelatedFormat:
   { RelationshipType: 'Can be contained by',
     RelatedFormatID: '1103',
     RelatedFormatName: '3GPP Audio/Video File',
     RelatedFormatVersion: '' } }


text:
package system;

import group.Cluster;
import group.ClusterHealth;
import group.Statistics;
import ninja.lifecycle.Dispose;
import ninja.lifecycle.Start;
import ninja.utils.NinjaProperties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class SysCluster {

	protected static final Logger logger = LoggerFactory
			.getLogger(SysCluster.class);

	private NinjaProperties properties;

	private final Cluster cluster;

	// ~constructors ------------------------------------------------

	@Inject
	public SysCluster(NinjaProperties ninjaProperties) { //TODO get rid of NinjaProperties
		properties = ninjaProperties;

		int TOTAL_BUCKETS = properties.getIntegerWithDefault("cluster.total_buckets", 20);
		int TOTAL_NODES = properties.getIntegerWithDefault("cluster.total_nodes", 1);

		cluster = Cluster.builder()
				.clusterName("AVMCluster")
				.totalBuckets(TOTAL_BUCKETS)
				.totalNodes(TOTAL_NODES).loadTypes(new int[]{-1, 155})
				.build();
	}

	@Start(order = 1)
	public void startCluster() {
		cluster.start();
	}

	@Dispose(order = 100)
	public void stopCluster() {
		cluster.stop();
	}

	@Override
	public String toString() {
		return cluster.toString();
	}

	public ClusterHealth checkClusterHealth(Integer type) {
		return cluster.checkClusterHealth(type, 5000);
	}

	public Statistics getStatistics() {
		return cluster.getStatistics();
	}

}


text:
#ifndef LAZY_SHORTEST_PATH
#define LAZY_SHORTEST_PATH

#include "ShortestPath.h"

/** \brief Lazy shortest path for single-objective shortest path algorithms.

	For details, see \cite Chen1998.
*/
class LazyShortestPath : public ShortestPath {
	public:
		LazyShortestPath(ShortestPath* shPath);
		~LazyShortestPath();

		virtual void calculate(int originIndex);

		virtual void calculate(int originIndex, int destIndex, int odPairIndex);

		virtual FPType getCost(int destIndex) const;

		virtual StarLink* getInComeLink(int destIndex) const;

	private:
		ShortestPath* shPath_;
		int prevOriginIndex_;
		bool originChanged_;
		FPType newPathCost_;

		/** Goes through the stored shortest path to the destination destIndex
			and updates shortest path distance that might have changed after
			flow shifts
		*/
		void updatePathCost(int destIndex);

};
#endif


text:
package foodtruck.linxup;

import java.util.List;

/**
 * @author aviolette
 * @since 7/25/16
 */
class LinxupMapResponse extends LinxupResponse {
  private List<Position> positions;

  LinxupMapResponse(String type, String message) {
    super(type, message);
  }

  LinxupMapResponse(List<Position> positions) {
    this(null, null);
    this.positions = positions;
  }

  List<Position> getPositions() {
    return positions;
  }
}