text:
/*      $NetBSD: limits.h,v 1.9 2008/08/29 19:08:29 matt Exp $  */

/*
 * Copyright (c) 1988 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *      from: @(#)limits.h      7.2 (Berkeley) 6/28/90
 */

//TODO These values have been chosen during porting with the selection criteria
//of being different from ARMv7 in the hope of discovering as many bugs as
//possible as soon as possible. They are NOT authoritative!
// ... (and should be replaced ASAP with more carefully chosen ones)

#ifndef _AARCH64_LIMITS_H_
#define _AARCH64_LIMITS_H_

#include <sys/featuretest.h>

#define __CHAR_BIT        8               /* number of bits in a char */
//#define __MB_LEN_MAX      32              /* no multibyte characters */

#define __SCHAR_MIN       (-0x7f-1)       /* max value for a signed char */
#define __SCHAR_MAX       0x7f            /* min value for a signed char */

#define __UCHAR_MAX       0xff            /* max value for an unsigned char */
#define __CHAR_MAX        0xff            /* max value for a char */
#define __CHAR_MIN        0               /* min value for a char */

#define __USHRT_MAX       0xffff          /* max value for an unsigned short */
#define __SHRT_MAX        0x7fff          /* max value for a short */
#define __SHRT_MIN        (-0x7fff-1)     /* min value for a short */

#define __UINT_MAX        0xffffffffU     /* max value for an unsigned int */
#define __INT_MAX         0x7fffffff      /* max value for an int */
#define __INT_MIN         (-0x7fffffff-1) /* min value for an int */

#define __ULONG_MAX       0xffffffffffffffffUL    /* max value for an unsigned long */
#define __LONG_MAX        0x7fffffffffffffffL     /* max value for a long */
#define __LONG_MIN        (-0x7fffffffffffffffL-1)        /* min value for a long */

#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) || \
    defined(_NETBSD_SOURCE)
#define SSIZE_MAX         LONG_MAX        /* max value for a ssize_t */

#if defined(_ISOC99_SOURCE) || (__STDC_VERSION__ - 0) >= 199901L || \
    defined(_NETBSD_SOURCE)
#define __ULLONG_MAX      0xffffffffffffffffULL   /* max unsigned long long */
#define __LLONG_MAX       0x7fffffffffffffffLL    /* max signed long long */
#define __LLONG_MIN       (-0x7fffffffffffffffLL-1) /* min signed long long */
#endif

#if defined(_NETBSD_SOURCE)
#define SIZE_T_MAX      LONG_MAX        /* max value for a size_t */

#define UQUAD_MAX       0xffffffffffffffffLL            /* max unsigned quad */
#define QUAD_MAX        0x7fffffffffffffffLL            /* max signed quad */
#define QUAD_MIN        (-0x7fffffffffffffffLL-1)       /* min signed quad */

#endif /* _NETBSD_SOURCE */
#endif /* _POSIX_C_SOURCE || _XOPEN_SOURCE || _NETBSD_SOURCE */

#if defined(_XOPEN_SOURCE) || defined(_NETBSD_SOURCE)
#define LONG_BIT        64
#define WORD_BIT        32

#define DBL_DIG         15
#define DBL_MAX         1.7976931348623157E+308
#define DBL_MIN         2.2250738585072014E-308

//#define FLT_DIG         6
//#define FLT_MAX         3.40282347E+38F
//#define FLT_MIN         1.17549435E-38F
#endif

#endif  /* _AARCH64_LIMITS_H_ */


text:
CREATE TABLE [dbo].[Attachments] (
    [Id]          UNIQUEIDENTIFIER CONSTRAINT [DF_Attachments_Id] DEFAULT (newid()) NOT NULL,
    [Filename]    VARCHAR (250)    NOT NULL,
    [ContentType] VARCHAR (200)    NOT NULL,
    [Contents]    VARBINARY (MAX)  NULL,
    [OrderId]     INT              NULL,
    [DateCreated] DATETIME         CONSTRAINT [DF_Attachments_DateCreated] DEFAULT (getdate()) NOT NULL,
    [UserId]      VARCHAR (10)     NOT NULL,
    [Category]    VARCHAR (50)     NULL,
    [MessageId]   VARCHAR (250)    NULL,
    [IsBlob]      BIT              DEFAULT ((0)) NOT NULL,
    CONSTRAINT [PK_Attachments] PRIMARY KEY CLUSTERED ([Id] ASC) WITH (STATISTICS_NORECOMPUTE = ON),
    CONSTRAINT [FK_Attachments_Orders] FOREIGN KEY ([OrderId]) REFERENCES [dbo].[Orders] ([Id]),
    CONSTRAINT [FK_Attachments_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([Id])
);

GO
CREATE NONCLUSTERED INDEX [HistoryReceivedLineItems_UserID_IDX]
    ON [dbo].[Attachments]([OrderId] ASC) WITH (STATISTICS_NORECOMPUTE = ON);

GO
CREATE NONCLUSTERED INDEX [Attachments_UserId_IDX]
    ON [dbo].[Attachments]([UserId] ASC) WITH (STATISTICS_NORECOMPUTE = ON);

GO
CREATE NONCLUSTERED INDEX [Attachments_OrderId_IDX]
    ON [dbo].[Attachments]([OrderId] ASC) WITH (STATISTICS_NORECOMPUTE = ON);

redpajama_set_name: RedPajamaGithub


text:
package algs.blog.graph.freeCell;

import java.io.File;
import java.io.IOException;
import java.util.Stack;

import algs.blog.graph.freeCell.Deal;
import algs.blog.graph.freeCell.FreeCellNode;
import algs.blog.graph.search.DFS;
import algs.blog.graph.search.Result;
import algs.model.searchtree.IMove;
import junit.framework.TestCase;

public class TestFullGame extends TestCase {
	public void testOneGame() {
		try {
			// these can all be solved without increasing default Stack size
			FreeCellNode fcn = Deal.initialize(new File ("artifacts/32000.txt"), 2);
			FreeCellNode copy = (FreeCellNode) fcn.copy();

			DFS<short[]> dfs = new DFS<short[]>();
			Result res = dfs.fullSearch(fcn, Deal.goal(), FreeCellNode.comparator());

			Stack<IMove> sol = res.solution();
			for (int i = 0; i < sol.size(); i++) {
				sol.get(i).execute(copy);
			}

			// get to end board state
			assertEquals (copy, fcn);
			assertTrue (copy.hasWon());
			assertTrue (fcn.hasWon());

		} catch (IOException ioe) {
			fail("unable to locate 32000.txt file.");
		}
	}
}


text:
@implementation Shopping2ShowTransferDialog

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

	[self addLabel:@"List All Transfer Friends ..." Location:[FDWindow shoppingMessageLocation]];

	return self;
}

-(void) onClicked:(CGPoint)location
{
	int selected = 0;

	NSLog(@"Select Friend Index %d", selected);
	id returnedObject = [NSNumber numberWithInt:selected];
	[self onExit:returnedObject];
}

@end


text:
package com.github.tinyretry.retry.tools;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.MessageFormat;
import java.util.Enumeration;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.tinyretry.retry.constants.Constants;
import com.github.tinyretry.retry.domain.RetryJob;
import com.github.tinyretry.retry.domain.Task;
import com.github.tinyretry.timer.domain.McJobGroup;
import com.github.tinyretry.timer.ext.McJobDefinition;

/**
 * <pre>
 * desc:
 * created: 2012-8-23 ÏÂÎç04:47:13
 * author: xiaofeng.zhouxf
 * todo:
 * history:
 * </pre>
 */
public class RetryJobTools {
	private static final Logger logger = LoggerFactory.getLogger(RetryJobTools.class);

	private static final String COLON = ":";
	private static final String SEPARATIVE = "_";

	public static String generateJobName(Task task) {
		return new StringBuilder(StringUtils.isNotBlank(task.getTaskName()) ? task.getTaskName() : StringUtils.EMPTY)
				.append(SEPARATIVE).append(task.getTaskId()).toString();
	}

	public static String generateJobNameByStrId(Task task) {
		return new StringBuilder(StringUtils.isNotBlank(task.getTaskName()) ? task.getTaskName() : StringUtils.EMPTY)
				.append(SEPARATIVE).append(task.getTaskStrId()).toString();
	}

	public static long calculateNextTime(long period, float wight, int currentTime) {
		long nextTime = System.currentTimeMillis();
		nextTime = nextTime + (int) (period
				* Math.pow(
				wight, currentTime
				));

		nextTime = nextTime > 0 ? nextTime : 200;

		return nextTime;
	}

	public static long calculatePreTime(long currentNextTime, long period, float wight, int currentTime) {

		long perTime = currentNextTime - (int) (period
				* Math.pow(
				wight, currentTime
				));

		perTime = perTime > 0 ? perTime : currentNextTime;

		return perTime;
	}

	public static String generateTaskZKNodeName(Long id, String appCode) {
		return MessageFormat.format(Constants.RETRY_ZK_NODE_NAME_TASK, appCode, (id != null ? id.toString() : "999"));
	}

	public static long getAfterNextTime(long addtion) {
		return System.currentTimeMillis() + (addtion != 0 ? addtion : Constants.NEXT_TIME_ADDTINO);
	}

	public static long getBeforeNextTime(long timeOut) {
		return System.currentTimeMillis() - (timeOut != 0 ? timeOut : Constants.NEXT_TIME_TIMEOUT);
	}

	public static RetryJob generateMcJob(McJobDefinition definition) {
		RetryJob job = new RetryJob();
		job.setDefinition(definition);
		return job;
	}

	public static McJobGroup generateMcJobGroup(String groupId, long repeatInterval) {

		McJobGroup jobGroup = new McJobGroup();
		jobGroup.setGroupId(groupId);
		jobGroup.setRepeatInterval(repeatInterval);
		jobGroup.setRepeatCount(0);
		return jobGroup;
	}

	public static McJobDefinition generateMcJobDefinition(String jobName, String groupId, String description) {
		McJobDefinition definition = new McJobDefinition();
		definition.setGroupId(groupId);
		definition.setName(jobName);
		definition.setDescription(description);
		return definition;
	}

	/**
	 * @return ±¾»úIP
	 * @throws java.net.SocketException
	 */
	public static String getIPAddress() {
		String localip = StringUtils.EMPTY;// ±¾µØIP£¬Èç¹ûûÓÐÅäÖÃÍâÍøIPÔò·µ»ØËü
		String netip = StringUtils.EMPTY;// ÍâÍøIP

		Enumeration<NetworkInterface> netInterfaces;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			logger.error("Get Ip exception.", e);
			return StringUtils.EMPTY;
		}
		if (netInterfaces != null) {
			InetAddress ip = null;
			boolean finded = false;// ÊÇ·ñÕÒµ½ÍâÍøIP
			while (netInterfaces.hasMoreElements() && !finded) {
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> address = ni.getInetAddresses();
				while (address.hasMoreElements()) {
					ip = address.nextElement();
					if (!ip.isSiteLocalAddress()
							&& !ip.isLoopbackAddress()
							&& ip.getHostAddress().indexOf(COLON) == -1) {// ÍâÍøIP
						netip = ip.getHostAddress();
						finded = true;
						break;
					} else if (ip.isSiteLocalAddress()
							&& !ip.isLoopbackAddress()
							&& ip.getHostAddress().indexOf(COLON) == -1) {// ÄÚÍøIP
						localip = ip.getHostAddress();
					}
				}
			}
		}
		if (StringUtils.isNotBlank(netip)) {
			return netip;
		} else {
			return localip;
		}
	}

	/**
	 * ¹¹½¨rowkey
	 *
	 * @param appcode
	 * @param type
	 * @param status
	 * @param nextTimestamp
	 * @return
	 */
	public static String generateHbaseRowkey(String appcode, String type, String status, String nextTimestamp) {
		return new StringBuilder(appcode).append(SEPARATIVE).append(type).append(SEPARATIVE).append(status)
				.append(SEPARATIVE).append(nextTimestamp).toString();
	}
}


text:
package gov.nih.nci.ncicb.cadsr.common.persistence.dao;

import gov.nih.nci.ncicb.cadsr.common.resource.ValidValue;

import java.util.Collection;
import java.util.Map;

public interface DataElementDAO {

	public Map<String, ValidValue> getPermissibleValues(Collection<String> deIdSeqs);
	public boolean isDEDerived(String deIdSeq);
}


text:
/*
 * Contains the structures and function APIs for YAFFSFS file system support.
 */

#ifndef _TSK_YAFFSFS_H
#define _TSK_YAFFSFS_H

#include <map>
#include <utility>

#ifdef __cplusplus
extern "C" {
#endif

/*
** Constants
*/
#define YAFFSFS_MAXNAMLEN	255

#define YAFFS_DEFAULT_PAGE_SIZE     2048
#define YAFFS_DEFAULT_SPARE_SIZE    64

#define YAFFS_DEFAULT_MAX_TEST_BLOCKS   400  // Maximum number of blocks to test looking for Yaffs2 spare under auto-detect

#define YAFFS_HELP_MESSAGE   "See http://wiki.sleuthkit.org/index.php?title=YAFFS2 for help on Yaffs2 configuration"

/*
 * Yaffs config file constants and return values
 */
#ifdef TSK_WIN32
#define YAFFS_CONFIG_FILE_SUFFIX          L"-yaffs2.config"
#else
#define YAFFS_CONFIG_FILE_SUFFIX          "-yaffs2.config"
#endif

#define YAFFS_CONFIG_SEQ_NUM_STR          "spare_seq_num_offset"
#define YAFFS_CONFIG_OBJ_ID_STR           "spare_obj_id_offset"
#define YAFFS_CONFIG_CHUNK_ID_STR         "spare_chunk_id_offset"
#define YAFFS_CONFIG_PAGE_SIZE_STR        "flash_page_size"
#define YAFFS_CONFIG_SPARE_SIZE_STR       "flash_spare_size"
#define YAFFS_CONFIG_CHUNKS_PER_BLOCK_STR "flash_chunks_per_block"

typedef enum {
    YAFFS_CONFIG_OK,
    YAFFS_CONFIG_FILE_NOT_FOUND,
    YAFFS_CONFIG_ERROR
} YAFFS_CONFIG_STATUS;

/*
** Yaffs Object Flags
*/
    typedef enum {
        NONE,
        YAFFS_HEADER,
        YAFFS_CHUNK,
        YAFFS_PAGES,
        YAFFS_SPARES,
        YAFFS_PAGES_AND_SPARES,
        UNKNOWN
    } YAFFS_OBJECT_FLAGS;

/*
** Yaffs2 Header Object
*/

#define YAFFS_HEADER_NAME_LENGTH   256
#define YAFFS_HEADER_ALIAS_LENGTH  160
    typedef struct yaffsObj_header {
        uint32_t obj_type;
        uint32_t parent_id;
        char name[YAFFS_HEADER_NAME_LENGTH];
        uint32_t file_mode;
        uint32_t user_id;
        uint32_t group_id;
        uint32_t atime;
        uint32_t mtime;
        uint32_t ctime;
        uint32_t file_size;
        uint32_t equivalent_id;
        char alias[YAFFS_HEADER_ALIAS_LENGTH];
        uint32_t rdev_mode;
        uint32_t win_ctime[2];
        uint32_t win_atime[2];
        uint32_t win_mtime[2];
        uint32_t inband_obj_id;
        uint32_t inband_is_shrink;
        uint32_t file_size_high;
        uint32_t reserved[1];
        int shadows_obj;
        uint32_t is_shrink;
    } YaffsHeader;

/*
** Spare object - this is subject to change...
*/

#define YAFFS_OBJECT_SPACE              0x40000
#define YAFFS_MAX_OBJECT_ID             (YAFFS_OBJECT_SPACE - 1)
#define YAFFS_LOWEST_SEQUENCE_NUMBER    0x00001000
#define YAFFS_HIGHEST_SEQUENCE_NUMBER   0xefffff00
#define YAFFS_SPARE_FLAGS_IS_HEADER     0x80000000
#define YAFFS_SPARE_PARENT_ID_MASK      0x0fffffff
#define YAFFS_SPARE_OBJECT_TYPE_SHIFT   28
#define YAFFS_SPARE_OBJECT_TYPE_MASK    0xf0000000

    typedef struct yaffsObj_spare {
        uint32_t seq_number;
        uint32_t object_id;
        uint32_t chunk_id;

        uint32_t has_extra_fields;
        uint32_t extra_object_type;
        uint32_t extra_parent_id;
    } YaffsSpare;

/*
** Holds the metadata for a single YAFFS2 chunk.
*/
    typedef enum {
        YAFFS_CHUNK_DEAD,       /* Either bad or unallocated */
        YAFFS_CHUNK_META,       /* Contains a header */
        YAFFS_CHUNK_DATA        /* Contains file data */
    } YaffsChunkType;

    typedef struct _YaffsChunk {
        YaffsChunkType type;
        YaffsSpare *spare;
        YaffsHeader *header;
    } YaffsChunk;

/* File system State Values */
#define YAFFSFS_STATE_VALID	0x0001  /* unmounted correctly */
#define YAFFSFS_STATE_ERROR	0x0002  /* errors detected */

/*
 * Special File Objects for the YAFFS2 File system
 */
#define YAFFS_OBJECT_ROOT 1
#define YAFFS_OBJECT_FIRST 1
#define YAFFS_OBJECT_LOSTNFOUND 2
#define YAFFS_OBJECT_UNLINKED 3
#define YAFFS_OBJECT_DELETED 4

#define YAFFS_OBJECT_ROOT_NAME           ""
#define YAFFS_OBJECT_LOSTNFOUND_NAME     "lost+found"
#define YAFFS_OBJECT_UNLINKED_NAME       "<unlinked>"
#define YAFFS_OBJECT_DELETED_NAME        "<deleted>"

/*
 * Yaffs File Types...
 */
#define YAFFS_TYPE_UNKNOWN 0
#define YAFFS_TYPE_FILE    1
#define YAFFS_TYPE_SOFTLINK 2
#define YAFFS_TYPE_DIRECTORY 3
#define YAFFS_TYPE_HARDLINK 4
#define YAFFS_TYPE_SPECIAL 5

    struct _YaffsCacheVersion;
    struct _YaffsCacheChunk;

    typedef struct _YaffsCacheObject {
        struct _YaffsCacheObject *yco_next;

        uint32_t yco_obj_id;

        struct _YaffsCacheVersion *yco_latest;
    } YaffsCacheObject;

#define YAFFS_OBJECT_ID_MASK         0x0003ffff
#define YAFFS_VERSION_NUM_SHIFT      18
#define YAFFS_VERSION_NUM_MASK       0x00003fff

    typedef struct _YaffsCacheVersion {
        struct _YaffsCacheVersion *ycv_prior;

        uint32_t ycv_version;
        uint32_t ycv_seq_number;

        struct _YaffsCacheChunk *ycv_header_chunk;
        struct _YaffsCacheChunk *ycv_first_chunk;
        struct _YaffsCacheChunk *ycv_last_chunk;
    } YaffsCacheVersion;

    typedef struct _YaffsCacheChunk {
        struct _YaffsCacheChunk *ycc_next;
        struct _YaffsCacheChunk *ycc_prev;

        TSK_OFF_T ycc_offset;
        uint32_t ycc_seq_number;
        uint32_t ycc_obj_id;
        uint32_t ycc_chunk_id;
        uint32_t ycc_parent_id;
        uint32_t ycc_n_bytes;
    } YaffsCacheChunk;

    typedef struct _YaffsCacheChunkGroup {
        YaffsCacheChunk *cache_chunks_head;
        YaffsCacheChunk *cache_chunks_tail;
    } YaffsCacheChunkGroup;

    /*
     * Structure of an yaffsfs file system handle.
     */
    typedef struct {
        TSK_FS_INFO fs_info;    /* super class */

        unsigned int page_size;
        unsigned int spare_size;
        unsigned int chunks_per_block;

        uint32_t max_obj_id;
        uint32_t max_version;

        // Offsets into the spare area
        unsigned int spare_seq_offset;
        unsigned int spare_obj_id_offset;
        unsigned int spare_chunk_id_offset;
        unsigned int spare_nbytes_offset;

        tsk_lock_t cache_lock;
        YaffsCacheObject *cache_objects;
         std::map < uint32_t, YaffsCacheChunkGroup > *chunkMap;

        // If the user specified that the image is YAFFS2, print out additional verbose error messages
        int autoDetect;
    } YAFFSFS_INFO;

#define YAFFS_FILE_CONTENT_LEN 0

#ifdef __cplusplus
}
#endif
#endif


text:
module RspecFormatter
  class Formatter
    RSpec::Core::Formatters.register self, :example_group_started, :example_group_finished

    def initialize(_output)
      @group_nesting = 0
    end

    def example_group_started(_example_group)
      @group_nesting += 1
    end

    def example_group_finished(notification)
      @group_nesting -= 1
      if @group_nesting == 0
        puts "rspec_core_formatter:file_path: #{notification.group.file_path}"
      end
    end
  end
end


text:
package org.locationtech.geomesa.tools.status

import com.beust.jcommander.{Parameter, ParameterException, Parameters}
import com.typesafe.config.{Config, ConfigRenderOptions}
import org.locationtech.geomesa.convert.ConverterConfigLoader
import org.locationtech.geomesa.tools.Command
import org.locationtech.geomesa.utils.geotools.{SimpleFeatureTypeLoader, SimpleFeatureTypes}
import org.opengis.feature.simple.SimpleFeatureType

class EnvironmentCommand extends Command {

  override val name = "env"
  override val params = new EnvironmentParameters()
  // TODO accumulo environment?
  override def execute(): Unit = {
    import scala.collection.JavaConverters._

    if (params.sfts == null && params.converters == null && !params.listSfts &&
      !params.listConverters && !params.describeSfts && !params.describeConverters) {
      Command.output.info("No flags given; displaying list of SFTs and Converters.")
      Command.output.info(s"Use 'help $name' to see complete command options.")

      listSftsNames()
      listConverterNames()
    } else {
      if (params.listSfts) {
        listSftsNames()
      }
      if (params.listConverters){
        listConverterNames()
      }
      if (params.describeSfts) {
        listSfts()
      }
      if (params.describeConverters) {
        listConverters()
      }
      if (params.sfts != null) {
        listSfts(params.sfts.asScala.toList)
      }
      if (params.converters != null) {
        listConverters(params.converters.asScala.toList)
      }
    }
  }

  def listSfts(names: List[String] = List.empty): Unit = {
    val all = SimpleFeatureTypeLoader.sfts
    val filtered = if (names.isEmpty) all else names.flatMap(n => all.find(_.getTypeName == n))
    Command.output.info("Simple Feature Types:")
    if (filtered.isEmpty) {
      Command.output.info("None available")
    } else {
      val paramsLower = params.format.toLowerCase
      if (paramsLower == "typesafe" || paramsLower == "spec") {
        val formatFn = paramsLower match {
          case "typesafe" =>
            (sft: SimpleFeatureType) => s"${SimpleFeatureTypes.toConfigString(sft, !params.excludeUserData, params.concise)}"
          case "spec" =>
            (sft: SimpleFeatureType) => s"${SimpleFeatureTypes.encodeType(sft, !params.excludeUserData)}"
        }
        filtered.sortBy(_.getTypeName).map(s => s"${s.getTypeName} = ${formatFn(s)}").foreach(Command.output.info)
      } else {
        throw new ParameterException(s"Unknown format '${params.format}'. Valid values are 'typesafe' or 'spec'")
      }
    }
  }

  def listConverters(names: List[String] = List.empty): Unit = {
    val all = ConverterConfigLoader.confs
    val filtered = if (names.isEmpty) all else names.flatMap(n => all.find(_._1 == n))
    Command.output.info("Simple Feature Type Converters:")
    if (filtered.isEmpty) {
      Command.output.info("None available")
    } else {
      val options = ConfigRenderOptions.defaults().setJson(false).setOriginComments(false)
      def render(c: Config) = c.root().render(options)
      val strings = filtered.map { case (cname, conf)=> s"converter-name=$cname\n${render(conf)}\n" }
      strings.toArray.sorted.foreach(Command.output.info)
    }
  }

  def listSftsNames(): Unit = {
    Command.output.info("Simple Feature Types:")
    val all = SimpleFeatureTypeLoader.sfts
    all.sortBy(_.getTypeName).map(s => s"${s.getTypeName}").foreach(Command.output.info)
  }
  def listConverterNames(): Unit = {
    Command.output.info("Simple Feature Type Converters:")
    val all = ConverterConfigLoader.confs
    all.map { case (cname, conf) => s"$cname"}.toArray.sorted.foreach(Command.output.info)
  }
}

@Parameters(commandDescription = "Examine the current GeoMesa environment")
class EnvironmentParameters {
  @Parameter(names = Array("-s", "--sfts"), description = "Describe specific simple feature types", variableArity = true)
  var sfts: java.util.List[String] = null

  @Parameter(names = Array("-c", "--converters"), description = "Describe specific GeoMesa converters", variableArity = true)
  var converters: java.util.List[String] = null

  @Parameter(names = Array("--list-sfts"), description = "List all the Simple Feature Types")
  var listSfts: Boolean = false

  @Parameter(names = Array("--list-converters"), description = "List all the Converter Names")
  var listConverters: Boolean = false

  @Parameter(names = Array("--describe-sfts"), description = "Describe all the Simple Feature Types")
  var describeSfts: Boolean = false

  @Parameter(names = Array("--describe-converters"), description = "Describe all the Simple Feature Type Converters")
  var describeConverters: Boolean = false

  @Parameter(names = Array("--format"), description = "Formats for sft (comma separated string, allowed values are typesafe, spec)", required = false)
  var format: String = "typesafe"

  @Parameter(names = Array("--concise"), description = "Render in concise format", required = false)
  var concise: Boolean = false

  @Parameter(names = Array("--exclude-user-data"), description = "Exclude user data", required = false)
  var excludeUserData: Boolean = false
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="3dp"
        android:color="@color/colorPrimary" />
</shape>


text:
CREATE OR REPLACE VIEW aws_bill_repository_due_update AS
	SELECT * FROM aws_bill_repository WHERE next_update <= NOW() AND grace_update <= NOW()
;


text:
package org.wso2.siddhi.core.util.collection.operator;

import org.wso2.siddhi.core.aggregation.IncrementalDataAggregator;
import org.wso2.siddhi.core.aggregation.IncrementalExecutor;
import org.wso2.siddhi.core.aggregation.IncrementalExternalTimestampDataAggregator;
import org.wso2.siddhi.core.config.SiddhiAppContext;
import org.wso2.siddhi.core.event.ComplexEvent;
import org.wso2.siddhi.core.event.ComplexEventChunk;
import org.wso2.siddhi.core.event.state.StateEvent;
import org.wso2.siddhi.core.event.stream.MetaStreamEvent;
import org.wso2.siddhi.core.event.stream.StreamEvent;
import org.wso2.siddhi.core.event.stream.StreamEventCloner;
import org.wso2.siddhi.core.event.stream.StreamEventPool;
import org.wso2.siddhi.core.event.stream.populater.ComplexEventPopulater;
import org.wso2.siddhi.core.exception.SiddhiAppRuntimeException;
import org.wso2.siddhi.core.executor.ExpressionExecutor;
import org.wso2.siddhi.core.query.selector.GroupByKeyGenerator;
import org.wso2.siddhi.core.table.Table;
import org.wso2.siddhi.query.api.aggregation.TimePeriod;
import org.wso2.siddhi.query.api.definition.AggregationDefinition;
import org.wso2.siddhi.query.api.definition.Attribute;
import org.wso2.siddhi.query.api.exception.SiddhiAppValidationException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.wso2.siddhi.query.api.expression.Expression.Time.normalizeDuration;

/**
 * Defines the logic to find a matching event from an incremental aggregator (retrieval from incremental aggregator),
 * based on the logical conditions defined herewith.
 */
public class IncrementalAggregateCompileCondition implements CompiledCondition {
    private Map<TimePeriod.Duration, CompiledCondition> withinTableCompiledConditions;
    private CompiledCondition inMemoryStoreCompileCondition;
    private CompiledCondition onCompiledCondition;
    private MetaStreamEvent tableMetaStreamEvent;
    private MetaStreamEvent aggregateMetaStreamEvent;
    private ComplexEventPopulater complexEventPopulater;
    private MatchingMetaInfoHolder alteredMatchingMetaInfoHolder;
    private ExpressionExecutor perExpressionExecutor;
    private ExpressionExecutor startTimeEndTimeExpressionExecutor;
    private boolean isProcessingOnExternalTime;

    private final StreamEventPool streamEventPoolForTableMeta;
    private final StreamEventCloner tableEventCloner;
    private final StreamEventPool streamEventPoolForAggregateMeta;
    private final StreamEventCloner aggregateEventCloner;
    private final List<Attribute> additionalAttributes;

    public IncrementalAggregateCompileCondition(
            Map<TimePeriod.Duration, CompiledCondition> withinTableCompiledConditions,
            CompiledCondition inMemoryStoreCompileCondition, CompiledCondition onCompiledCondition,
            MetaStreamEvent tableMetaStreamEvent, MetaStreamEvent aggregateMetaSteamEvent,
            List<Attribute> additionalAttributes, MatchingMetaInfoHolder alteredMatchingMetaInfoHolder,
            ExpressionExecutor perExpressionExecutor, ExpressionExecutor startTimeEndTimeExpressionExecutor,
            boolean isProcessingOnExternalTime) {
        this.withinTableCompiledConditions = withinTableCompiledConditions;
        this.inMemoryStoreCompileCondition = inMemoryStoreCompileCondition;
        this.onCompiledCondition = onCompiledCondition;
        this.tableMetaStreamEvent = tableMetaStreamEvent;
        this.aggregateMetaStreamEvent = aggregateMetaSteamEvent;

        this.streamEventPoolForTableMeta = new StreamEventPool(tableMetaStreamEvent, 10);
        this.tableEventCloner = new StreamEventCloner(tableMetaStreamEvent, streamEventPoolForTableMeta);

        this.streamEventPoolForAggregateMeta = new StreamEventPool(aggregateMetaSteamEvent, 10);
        this.aggregateEventCloner = new StreamEventCloner(aggregateMetaSteamEvent, streamEventPoolForAggregateMeta);
        this.additionalAttributes = additionalAttributes;
        this.alteredMatchingMetaInfoHolder = alteredMatchingMetaInfoHolder;
        this.perExpressionExecutor = perExpressionExecutor;
        this.startTimeEndTimeExpressionExecutor = startTimeEndTimeExpressionExecutor;
        this.isProcessingOnExternalTime = isProcessingOnExternalTime;
    }

    @Override
    public CompiledCondition cloneCompilation(String key) {
        Map<TimePeriod.Duration, CompiledCondition> copyOfWithinTableCompiledConditions = new HashMap<>();
        for (Map.Entry<TimePeriod.Duration, CompiledCondition> entry : withinTableCompiledConditions.entrySet()) {
            copyOfWithinTableCompiledConditions.put(entry.getKey(), entry.getValue().cloneCompilation(key));
        }
        return new IncrementalAggregateCompileCondition(copyOfWithinTableCompiledConditions,
                inMemoryStoreCompileCondition.cloneCompilation(key),
                onCompiledCondition.cloneCompilation(key), tableMetaStreamEvent, aggregateMetaStreamEvent,
                additionalAttributes, alteredMatchingMetaInfoHolder, perExpressionExecutor,
                startTimeEndTimeExpressionExecutor, isProcessingOnExternalTime);
    }

    public StreamEvent find(StateEvent matchingEvent, AggregationDefinition aggregationDefinition,
                            Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap,
                            Map<TimePeriod.Duration, Table> aggregationTables,
                            List<TimePeriod.Duration> incrementalDurations,
                            List<ExpressionExecutor> baseExecutors,
                            List<ExpressionExecutor> outputExpressionExecutors,
                            SiddhiAppContext siddhiAppContext,
                            List<List<ExpressionExecutor>> aggregateProcessingExecutorsList,
                            List<GroupByKeyGenerator> groupbyKeyGeneratorList,
                            ExpressionExecutor shouldUpdateExpressionExecutor,
                            Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMapForPartitions) {

        ComplexEventChunk<StreamEvent> complexEventChunkToHoldWithinMatches = new ComplexEventChunk<>(true);

        // Retrieve per value
        String perValueAsString = perExpressionExecutor.execute(matchingEvent).toString();
        TimePeriod.Duration perValue;
        try {
            // Per time function verification
            perValue = normalizeDuration(perValueAsString);
        } catch (SiddhiAppValidationException e) {
            throw new SiddhiAppRuntimeException(
                    "Aggregation Query's per value is expected to be of a valid time function of the " +
                            "following " + TimePeriod.Duration.SECONDS + ", " + TimePeriod.Duration.MINUTES + ", "
                            + TimePeriod.Duration.HOURS + ", " + TimePeriod.Duration.DAYS + ", "
                            + TimePeriod.Duration.MONTHS + ", " + TimePeriod.Duration.YEARS + ".");
        }
        if (!incrementalExecutorMap.keySet().contains(perValue)) {
            throw new SiddhiAppRuntimeException("The aggregate values for " + perValue.toString()
                    + " granularity cannot be provided since aggregation definition " +
                    aggregationDefinition.getId() + " does not contain " + perValue.toString() + " duration");
        }

        Table tableForPerDuration = aggregationTables.get(perValue);

        Long[] startTimeEndTime = (Long[]) startTimeEndTimeExpressionExecutor.execute(matchingEvent);
        if (startTimeEndTime == null) {
            throw new SiddhiAppRuntimeException("Start and end times for within duration cannot be retrieved");
        }

        complexEventPopulater.populateComplexEvent(matchingEvent.getStreamEvent(0), startTimeEndTime);

        // Get all the aggregates within the given duration, from table corresponding to "per" duration
        StreamEvent withinMatchFromPersistedEvents = tableForPerDuration.find(matchingEvent,
                withinTableCompiledConditions.get(perValue));
        complexEventChunkToHoldWithinMatches.add(withinMatchFromPersistedEvents);

        // Optimization step.
        long oldestInMemoryEventTimestamp = getOldestInMemoryEventTimestamp(incrementalExecutorMap,
                incrementalDurations, perValue);

        ExpressionExecutor shouldUpdateExpressionExecutorClone =
                (shouldUpdateExpressionExecutor == null) ? null : shouldUpdateExpressionExecutor.cloneExecutor(null);

        //If processing on external time, the in-memory data also needs to be queried
        if (isProcessingOnExternalTime || requiresAggregatingInMemoryData(oldestInMemoryEventTimestamp,
                startTimeEndTime)) {
            List<ExpressionExecutor> clonedBaseExecutors = baseExecutors.stream().map(expressionExecutor ->
                    expressionExecutor.cloneExecutor("")).collect(Collectors.toList());
            IncrementalDataAggregator incrementalDataAggregator = new IncrementalDataAggregator(incrementalDurations,
                    perValue, oldestInMemoryEventTimestamp, clonedBaseExecutors, tableMetaStreamEvent,
                    siddhiAppContext, shouldUpdateExpressionExecutorClone);
            ComplexEventChunk<StreamEvent> aggregatedInMemoryEventChunk;
            // Aggregate in-memory data and create an event chunk out of it
            if (incrementalExecutorMapForPartitions != null) {
                aggregatedInMemoryEventChunk = incrementalDataAggregator
                        .aggregateInMemoryData(incrementalExecutorMapForPartitions);
            } else {
                aggregatedInMemoryEventChunk = incrementalDataAggregator
                        .aggregateInMemoryData(incrementalExecutorMap);
            }

            // Get the in-memory aggregate data, which is within given duration
            StreamEvent withinMatchFromInMemory = ((Operator) inMemoryStoreCompileCondition).find(matchingEvent,
                    aggregatedInMemoryEventChunk, tableEventCloner);
            complexEventChunkToHoldWithinMatches.add(withinMatchFromInMemory);
        }

        ComplexEventChunk<StreamEvent> processedEvents;
        if (isProcessingOnExternalTime) {
            int durationIndex = incrementalDurations.indexOf(perValue);
            List<ExpressionExecutor> expressionExecutors = aggregateProcessingExecutorsList.get(durationIndex);
            GroupByKeyGenerator groupByKeyGenerator = groupbyKeyGeneratorList.get(durationIndex);

            ExpressionExecutor shouldUpdateExpressionExecutorCloneExt =
                    (shouldUpdateExpressionExecutor == null) ? null :
                            shouldUpdateExpressionExecutor.cloneExecutor(null);
            IncrementalExternalTimestampDataAggregator incrementalExternalTimestampDataAggregator =
                    new IncrementalExternalTimestampDataAggregator(expressionExecutors, groupByKeyGenerator,
                    tableMetaStreamEvent, siddhiAppContext, shouldUpdateExpressionExecutorCloneExt);
            processedEvents = incrementalExternalTimestampDataAggregator
                    .aggregateData(complexEventChunkToHoldWithinMatches);
        } else {
            processedEvents = complexEventChunkToHoldWithinMatches;
        }

        // Get the final event chunk from the data which is within given duration. This event chunk contains the values
        // in the select clause of an aggregate definition.
        ComplexEventChunk<StreamEvent> aggregateSelectionComplexEventChunk = createAggregateSelectionEventChunk(
                processedEvents, outputExpressionExecutors);

        // Execute the on compile condition
        return ((Operator) onCompiledCondition).find(matchingEvent, aggregateSelectionComplexEventChunk,
                aggregateEventCloner);
    }

    private ComplexEventChunk<StreamEvent> createAggregateSelectionEventChunk(
            ComplexEventChunk<StreamEvent> complexEventChunkToHoldMatches,
            List<ExpressionExecutor> outputExpressionExecutors) {
        ComplexEventChunk<StreamEvent> aggregateSelectionComplexEventChunk = new ComplexEventChunk<>(true);
        StreamEvent resetEvent = streamEventPoolForTableMeta.borrowEvent();
        resetEvent.setType(ComplexEvent.Type.RESET);

        while (complexEventChunkToHoldMatches.hasNext()) {
            StreamEvent streamEvent = complexEventChunkToHoldMatches.next();
            StreamEvent newStreamEvent = streamEventPoolForAggregateMeta.borrowEvent();
            Object outputData[] = new Object[newStreamEvent.getOutputData().length];
            for (int i = 0; i < outputExpressionExecutors.size(); i++) {
                outputData[i] = outputExpressionExecutors.get(i).execute(streamEvent);
            }
            newStreamEvent.setTimestamp(streamEvent.getTimestamp());
            newStreamEvent.setOutputData(outputData);
            aggregateSelectionComplexEventChunk.add(newStreamEvent);
        }

        for (ExpressionExecutor expressionExecutor : outputExpressionExecutors) {
            expressionExecutor.execute(resetEvent);
        }

        return aggregateSelectionComplexEventChunk;
    }

    private boolean requiresAggregatingInMemoryData(long oldestInMemoryEventTimestamp, Long[] startTimeEndTime) {
        if (oldestInMemoryEventTimestamp == -1) {
            return false;
        }
        long endTimeForWithin = startTimeEndTime[1];
        return endTimeForWithin > oldestInMemoryEventTimestamp;
    }

    private long getOldestInMemoryEventTimestamp(Map<TimePeriod.Duration, IncrementalExecutor> incrementalExecutorMap,
                                                 List<TimePeriod.Duration> incrementalDurations,
                                                 TimePeriod.Duration perValue) {
        long oldestEvent;
        TimePeriod.Duration incrementalDuration;
        for (int i = perValue.ordinal(); i >= incrementalDurations.get(0).ordinal(); i--) {
            incrementalDuration = TimePeriod.Duration.values()[i];
            //If the reduced granularity is not configured
            if (incrementalExecutorMap.containsKey(incrementalDuration)) {
                oldestEvent = incrementalExecutorMap.get(incrementalDuration).getAggregationStartTimestamp();
                if (oldestEvent != -1) {
                    return oldestEvent;
                }
            }
        }
        return -1;
    }

    public void setComplexEventPopulater(ComplexEventPopulater complexEventPopulater) {
        this.complexEventPopulater = complexEventPopulater;
    }

    public List<Attribute> getAdditionalAttributes() {
        return this.additionalAttributes;
    }

    public MatchingMetaInfoHolder getAlteredMatchingMetaInfoHolder() {
        return this.alteredMatchingMetaInfoHolder;
    }
}


text:
package de.iritgo.aktario.core.network;

import de.iritgo.aktario.core.action.Action;
import de.iritgo.aktario.core.iobject.*;
import de.iritgo.aktario.core.logger.Log;
import de.iritgo.aktario.core.thread.Threadable;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.concurrent.*;

import org.apache.mina.core.service.*;
import org.apache.mina.core.session.*;

/**
 *
 */
public class ChannelHandler extends IoHandlerAdapter
{
	public ConcurrentHashMap<IoSession, Channel> channels = new ConcurrentHashMap<IoSession, Channel> ();
	private NetworkService networkService;
	private Channel clientChannel;

	/**
	 * Standard constructor
	 *
	 * @param socket The Socket for input/output action
	 * @param networkService Networkbase for storge received objects
	 */
	public ChannelHandler (NetworkService networkService)
	{
		this.networkService = networkService;
	}

	public ChannelHandler (NetworkService networkService, Channel clientChannel)
	{
		this.networkService = networkService;
		this.clientChannel = clientChannel;
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception
	{
		Channel channel = clientChannel == null ? new Channel (networkService, session) : clientChannel;

		channels.put (session,  channel);
		networkService.addConnectedChannel(channel);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception
	{
		networkService.closeChannel (channels.get(session).getChannelNumber());
		networkService.fireConnectionTerminated(channels.get(session));
		channels.remove(session);
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception
	{
//		System.out.println ("Idle: " + status.toString());
		networkService.fireError(channels.get(session), new SocketTimeoutException());
	}

	/**
	 * Wait for a Object.
	 *
	 */
	@Override
	public void messageReceived (IoSession session, Object message) throws Exception
	{
//		System.out.println("Received-Message: " + ((IObject) message).getTypeId() + ":" + ((IObject) message).getUniqueId());
		channels.get(session).received(message);
	}

	@Override
	public void exceptionCaught (IoSession session, Throwable cause )
	{
		cause.printStackTrace();
		if (cause != null)
		{
			Log.logDebug("network", "Channel", "SocketTimeoutException");
//			networkService.fireConnectionTerminated(this);
		}

//			catch (NoSuchIObjectException x)
//			{
//				Log.logError("network", "Channel", "NoSuchPrototypeRegisteredException: " + x);
//				object = null;
//				setConnectionState(NETWORK_ERROR);
//				networkService.fireError(this, x);
//				networkService.fireConnectionTerminated(this);
//
//				return;
//			}
//			catch (ClassNotFoundException x)
//			{
//				Log.logError("network", "Channel", "ClassNotFoundException");
//				setConnectionState(NETWORK_ERROR);
//				networkService.fireError(this, x);
//				networkService.fireConnectionTerminated(this);
//
//				return;
//			}
//			catch (EOFException x)
//			{
//				Log.logDebug("network", "Channel", "EOFException (ConnectionClosed?!)");
//				setConnectionState(NETWORK_CLOSE);
//				setState(Threadable.CLOSING);
//				networkService.fireError(this, x);
//				networkService.fireConnectionTerminated(this);
//
//				return;
//			}
//			catch (SocketException x)
//			{
//				Log.logDebug("network", "Channel", "SocketClosed.");
//				setConnectionState(NETWORK_CLOSE);
//				setState(Threadable.CLOSING);
//				networkService.fireError(this, x);
//				networkService.fireConnectionTerminated(this);
//
//				return;
//			}
//			catch (IOException x)
//			{
//				setState(Threadable.CLOSING);
//				Log.logError("network", "Channel", "IOException: " + x);
//				x.printStackTrace();
//
//				setConnectionState(NETWORK_ERROR);
//				networkService.fireError(this, x);
//				networkService.fireConnectionTerminated(this);
//
//				return;
//			}
//		}

		return;
	}

	/**
	 * Send a Object over the ObjectStream.
	 *
	 * @param object The Object to send.
	 */
	public void send(Object object)
	{

//		try
//		{
//			Log.logDebug("network", "Channel", "Sending Object (Channel:" + channelNumber + "):" + object);
//
//			++numSendObjects;
//			streamOrganizer.send(object);
//		}
//		catch (IOException e)
//		{
//			Log.logError("network", "Channel", "Serializeable?" + e);
//		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">

    <title>Rebuilding Together, Peninsula - ROOM System</title>
    <link href="/css/lib/bootstrap.css" rel="stylesheet" media="screen">
    <link type="text/css" rel="stylesheet" href="/static/styles.css">

Rebuilding Together Peninsula Invoice

Invoice # {{ order.internal_invoice.get().invoice_number }}

      {% if order.invoice_date %}

Invoice date: {{ order.invoice_date }}

      {% endif %}

      {% include "order_layout.html" %}

      © 2011 Rebuilding Together Peninsula


text:
package base.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/")
public class AppController {

	/*
	 * This method will list all existing employees.
	 */
	@RequestMapping(value = { "/"}, method = RequestMethod.GET)
	public String listEmployees(ModelMap model) {

		return "index";
	}
}


text:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/users');

/* navigate to registration page */
router.get('/', function(req, res, next) {
    res.render('register');
});

/* register request */
router.post('/', function(req, res, next) {
	User.register(new User({
		username: req.body.username,
		firstName: req.body.firstName,
		lastName: req.body.lastName,
		carMake: req.body.carMake,
		carModel: req.body.carModel,
		carColor: req.body.carColor,
		carLicensePlate: req.body.carLicensePlate,
		maxPassengers: req.body.maxPassengers
	})
	, req.body.password
	, function(err, user) {
		if (err) {
			console.log('failed to register user');
			return res.render('register', { user: user });
		}

		console.log('successfully registered user');
		passport.authenticate('local')(req, res, function() {
			res.redirect('/');
		});
	});
});

module.exports = router;


text:
/**
 * 企业文件面包屑集合
 */
 define(function(require, exports, module) {

 	window.FileBreadListDTO = Backbone.Collection.extend({
 		model : EntFileDTO,
 		url : ""
 	});

 });


text:
Translator::Translator(QQmlEngine *engine) {

	m_translator = new QTranslator(this);
	m_engine = engine;
}

void Translator::selectLanguage(const QString &language) {

	qApp->removeTranslator(m_translator);

	if (!m_translator->load(QString(":/i18n/qml_%1").arg(language))) {
		SPDLOG_ERROR("Failed to load QML translation file for language {}, falling back to English", language.toUtf8().data());
		return;
	}

	qApp->installTranslator(m_translator);
	m_engine->retranslate();

	emit languageChanged();
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Boa Vista</logradouro><bairro>Centro</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>01014000</cep></feed>


text:
package com.quizup.qucorelib.translation;

import com.quizup.qucorelib.xml.AbstractXMLSerializer;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;

@XStreamAlias("string")
@XStreamConverter(strings={"value"}, value="Lcom/thoughtworks/xstream/converters/extended/ToAttributedValueConverter;")
public class StringItem extends AbstractXMLSerializer<StringItem>
{

  @XStreamAlias("name")
  public String name;
  public String value;

  public static StringItem build()
  {
    StringItem localStringItem = new StringItem();
    localStringItem.registerAlias();
    return localStringItem;
  }

  public StringItem generateTestInstance()
  {
    this.name = "intro-animation-welcome-to";
    this.value = "Welcome to";
    return this;
  }

  protected void registerAlias()
  {
    AbstractXMLSerializer.xs.alias("string", StringItem.class);
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.quizup.qucorelib.translation.StringItem
 * JD-Core Version:    0.6.2
 */


text:
import socket
import sys

# -----------  Config  ----------
IP_VERSION = 'IPv4'
PORT = 3333
# -------------------------------

if IP_VERSION == 'IPv4':
    family_addr = socket.AF_INET
elif IP_VERSION == 'IPv6':
    family_addr = socket.AF_INET6
else:
    print('IP_VERSION must be IPv4 or IPv6')
    sys.exit(1)

try:
    sock = socket.socket(family_addr, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as msg:
    print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()

try:
    sock.bind(('', PORT))
except socket.error as msg:
    print('Bind failed. Error: ' + str(msg[0]) + ': ' + msg[1])
    sys.exit()

while True:
    try:
        print('Waiting for data...')
        data, addr = sock.recvfrom(1024)
        if not data:
            break
        data = data.decode()
        print('Reply[' + addr[0] + ':' + str(addr[1]) + '] - ' + data)
        reply = 'OK ' + data
        sock.sendto(reply.encode(), addr)
    except socket.error as msg:
        print('Error Code : ' + str(msg[0]) + ' Message ' + msg[1])

sock.close()


text:
package freemarker.ext.beans;

import freemarker.core._DelayedOrdinal;

/**
 * Describes a failed member lookup. Instances of this must not be cached as instances may store the actual argument
 * values.
 */
final class EmptyMemberAndArguments extends MaybeEmptyMemberAndArguments {

    static final EmptyMemberAndArguments WRONG_NUMBER_OF_ARGUMENTS
            = new EmptyMemberAndArguments(
                    "No compatible overloaded variation was found; wrong number of arguments.", true, null);

    private final Object errorDescription;
    private final boolean numberOfArgumentsWrong;
    private final Object[] unwrappedArguments;

    private EmptyMemberAndArguments(
            Object errorDescription, boolean numberOfArgumentsWrong, Object[] unwrappedArguments) {
        this.errorDescription = errorDescription;
        this.numberOfArgumentsWrong = numberOfArgumentsWrong;
        this.unwrappedArguments = unwrappedArguments;
    }

    static EmptyMemberAndArguments noCompatibleOverload(int unwrappableIndex) {
        return new EmptyMemberAndArguments(
                new Object[] { "No compatible overloaded variation was found; can't convert (unwrap) the ",
                new _DelayedOrdinal(Integer.valueOf(unwrappableIndex)), " argument to the desired Java type." },
                false,
                null);
    }

    static EmptyMemberAndArguments noCompatibleOverload(Object[] unwrappedArgs) {
        return new EmptyMemberAndArguments(
                "No compatible overloaded variation was found; declared parameter types and argument value types mismatch.",
                false,
                unwrappedArgs);
    }

    static EmptyMemberAndArguments ambiguous(Object[] unwrappedArgs) {
        return new EmptyMemberAndArguments(
                "Multiple compatible overloaded variations were found with the same priority.",
                false,
                unwrappedArgs);
    }

    static MaybeEmptyMemberAndArguments from(
            EmptyCallableMemberDescriptor emtpyMemberDesc, Object[] unwrappedArgs) {
        if (emtpyMemberDesc == EmptyCallableMemberDescriptor.NO_SUCH_METHOD) {
            return noCompatibleOverload(unwrappedArgs);
        } else if (emtpyMemberDesc == EmptyCallableMemberDescriptor.AMBIGUOUS_METHOD) {
            return ambiguous(unwrappedArgs);
        } else {
            throw new IllegalArgumentException("Unrecognized constant: " + emtpyMemberDesc);
        }
    }

    Object getErrorDescription() {
        return errorDescription;
    }

    /**
     * @return {@code null} if the error has occurred earlier than the full argument list was unwrapped.
     */
    Object[] getUnwrappedArguments() {
        return unwrappedArguments;
    }

    public boolean isNumberOfArgumentsWrong() {
        return numberOfArgumentsWrong;
    }

}


text:
Drools Workbench Showcase Docker image
========================================

JBoss Drools Workbench Showcase [Docker](http://docker.io/) image.

Table of contents
------------------

* Introduction
* Usage
* GIT internal repository access
* Users and roles
* Logging
* Extending this image
* Experimenting
* Notes

Introduction
------------

The image contains:

* JBoss Wildfly 8.1.0.Final
* Drools Workbench 6.2.0.Final

This image inherits from `jboss/drools-workbench:6.2.0.Final` and provides some additional configurations:

* Some KIE examples
* Default users and roles

This is a **ready to run Docker image for Drools Workbench**. Just run it and try our workbench!

Usage
-----

To run a container:

    docker run -P -d --name drools-workbench jboss/drools-workbench-showcase:6.2.0.Final

Once container and web applications started, you can navigate to it using one of the users described in section `Users and roles`.

To find out the application URL:

**Using local host binding port**

If you have run the container using `-P` flag in the `docker` command, the port `8080` has been bind to an available port on your host.

So you have to discover your host's bind port, that can be done by running the command:

    docker ps -a

Example of the above command response:

    CONTAINER ID        IMAGE                                         COMMAND                CREATED              STATUS              PORTS                                              NAMES
    2a55fbe771c0        jboss/drools-workbench-showcase:6.2.0.Final   ./standalone.sh -b 0   About a minute ago   Up About a minute   0.0.0.0:49159->8080/tcp, 0.0.0.0:49160->9990/tcp   drools-workbench-showcase

As you can see, the bind port to use for container's port `8080` is `49159`, so you can navigate to:

    http://localhost:49159/drools-wb

**No bind port for localhost**

In case you run the container without using `-P` flag in the `docker` command, you can navigate to the application at:

    http://<container_ip_address>:8080/drools-wb

You can discover the IP address of your running container by:

    docker inspect --format '{{ .NetworkSettings.IPAddress }}' drools-workbench-showcase

GIT internal repository access
------------------------------

You can clone the GIT internal repositories that Drools Workbench Showcase provides, as well as any ones created by application users.

By default, the protocol used for cloning a GIT repository from the application is `SSH` at port `8001`.

    git clone ssh://admin@localhost:8001/uf-playground

For cloning a repository located inside the Drools Workbench Showcase docker container, you have to discover your host's port bind for the internal port `8001`, by running the `ps` docker command:

    docker ps -a

Example of the above command response:

    CONTAINER ID        IMAGE                                         COMMAND                CREATED              STATUS              PORTS                                                                                NAMES
    2a55fbe771c0        jboss/drools-workbench-showcase:6.2.0.Final   ./standalone.sh -b 0   About a minute ago   Up About a minute   0.0.0.0:49159->8080/tcp, 0.0.0.0:49160->9990/tcp, 0.0.0.0:49161->8001/tcp   drools-workbench-showcase

As you can see, the bind port to use for container's port `8001` is `49161`, so you can do the clone as:

    git clone ssh://admin@localhost:49161/uf-playground

NOTE: Users and password for ssh access are the same that for the web application users defined at the realm files.

Users and roles
----------------

This showcase image contains default users and roles:

    USER        PASSWORD    ROLE
    *************************************************
    admin       admin       admin,analyst,kiemgmt
    krisv       krisv       admin,analyst
    john        john        analyst,Accounting,PM
    mary        mary        analyst,HR
    sales-rep   sales-rep   analyst,sales
    katy        katy        analyst,HR
    jack        jack        analyst,IT
    salaboy     salaboy     admin,analyst,IT,HR,Accounting

Logging
-------

You can see all logs generated by the `standalone` binary running:

    docker logs [-f] <container_id>

You can attach the container by running:

    docker attach <container_id>

The Drools Workbench web application logs can be found inside the container at path:

    /opt/jboss/wildfly/standalone/log/server.log

    Example:
    sudo nsenter -t $(docker inspect --format '{{ .State.Pid }}' $(docker ps -lq)) -m -u -i -n -p -w
    -bash-4.2# tail -f /opt/jboss/wildfly/standalone/log/server.log

Experimenting
-------------

To spin up a shell in one of the containers try:

    docker run -t -i -P jboss/drools-workbench-showcase:6.2.0.Final /bin/bash

You can then noodle around the container and run stuff & look at files etc.

You can run the Drools Workbench web application by running command:

    /opt/jboss/wildfly/bin/standalone.sh -b 0.0.0.0 --server-config=standalone-full-drools.xml

Notes
-----

* Drools Workbench version is `6.2.0.Final`
* Drools Workbench requires running JBoss Wildfly using `full` profile
* No support for clustering
* Use of embedded H2 database server by default
* No support for Wildfly domain mode, just standalone mode
* The context path for Drools Workbench web application is `drools-wb`


text:
var iconv = require('iconv-lite');
exports =module.exports = function(app,models){
	var path = require('path');
	var fs = require('fs');

	var add = function(req,res){
			// console.log(req.files);
			// res.writeHead(200, {'content-type': 'text/plain'});
			// res.write('received upload:\n\n');
			// var util = require('util');
			// res.end(util.inspect({files: req.files}));
			var file = req.files.files;
			var filename = app.randomHex() + '.' + file.extension;//file.name;
			var tmp_path = file.path;
			var new_path = path.join(__dirname, '../public/_images/',filename);
			var attachment = '/_images/' + filename;
			if(file.extension == 'csv'){
 				//** 导入和转化csv
				var reader = fs.createReadStream(tmp_path,{encoding: null});
				var writer = fs.createWriteStream(new_path, {encoding: 'utf8'});
				reader
					.pipe(iconv.decodeStream('GBK'))
					.pipe(iconv.encodeStream('utf8'))
					.pipe(writer);
				file.name = filename;
				file.url = attachment;
				res.send(file);
			}else{
				fs.rename(tmp_path,new_path,function(err){
					if(err) console.error(err);
					if(err) return res.send({code: 40000, errmsg: 'upload error.'});
					file.name = filename;
					file.url = attachment;
					res.send(file);
				});
			}
		};

	var remove = function(req,res){
			var filename = req.body.filename || '';
			var file_path = path.join(__dirname, '../public/',filename);
			fs.unlink(file_path,function(err){
				if(err) console.error(err);
				if(err) return res.send({code: 40100, errmsg: 'delete file error.'});

				res.sendStatus(200);
			});
		};

/**
 * router outline
 */

 	/**
 	 * add an attachment
 	 */
 	app.post('/public/attachments', app.isLogin, add);
 	/**
 	 * remove an attachment
 	 */
 	app.delete('/public/attachments', app.isLogin, remove);
};


text:
package com.iappsam.servlet.systemlog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iappsam.Log;
import com.iappsam.managers.LogManager;
import com.iappsam.managers.exceptions.TransactionException;
import com.iappsam.managers.sessions.LogManagerSession;
import com.iappsam.servlet.Action;

public class ViewSystemLogsAction implements Action {

	@Override
	public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		LogManager l = new LogManagerSession();
		RequestDispatcher view = request.getRequestDispatcher(SystemLogServlet.VIEW_SYSTEM_LOGS);

		List<Log> logs = new ArrayList<Log>();

		try {
			logs = l.viewLogs();
		} catch (TransactionException e) {
			e.printStackTrace();
		}

		request.setAttribute("logs", logs);
		view.forward(request, response);
	}

}


text:
var blog = (function($) {

	// module scope variables
	var
		// constants
		configMap = {
			extended_width: 260,
			extended_title: 'Click to retract',
			retracted_width: 0,
			retracted_title: 'Click to extend'
		},
		// vars
		$chatSlider,
		toggleSlider, onClickSlider, initModule;

	// alternates slider width
	toggleSlider = function() {
		var slider_width = $chatSlider.width();
		// extend slider if fully retracted
		if(slider_width === configMap.retracted_width) {
			$chatSlider.animate({width : configMap.extended_width})
				.attr('title', configMap.extended_title);
			return true;
		} else if(slider_width === configMap.extended_width) {
		// retract slider if fully extended
			$chatSlider.animate({width : configMap.retracted_width})
				.attr('title', configMap.retracted_title);
			return true;
		}
		// do not take action if slider is in transition
		return false;
	};
	// receives click event and calls toggleSlider
	onClickSlider = function(event) {
		toggleSlider();
		return false;
	};
	// sets initial state and provides feature
	initModule = function($container) {
		// initialize slider and width and title
		$chatSlider = $container.find('.sidebar');
		// set the title of the slider
		// bind the user click event to the event handler
		$chatSlider.attr('title', configMap.retracted_title)
			.click(onClickSlider);
		return true;
	};

	// export public methods by returning an object from spa name-space
	return { initModule : initModule };

}(jQuery));


text:
package com.intellij.util.xml.tree.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.util.IconLoader;
import com.intellij.util.xml.ElementPresentationManager;
import com.intellij.util.xml.TypeNameManager;
import com.intellij.util.xml.DomUtil;
import com.intellij.util.xml.tree.BaseDomElementNode;
import com.intellij.util.xml.tree.DomModelTreeView;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

/**
 * User: Sergey.Vasiliev
 */
public class DomElementsToggleAction extends ToggleAction {
  private final DomModelTreeView myTreeView;
  private final Class myClass;
  private final Icon myIcon;
  private final String myText;

  public DomElementsToggleAction(final DomModelTreeView treeView, final Class aClass) {
    myTreeView = treeView;
    myClass = aClass;

    Icon myIcon = ElementPresentationManager.getIcon(myClass);
    if (myIcon == null) {
      myIcon = IconLoader.getIcon("/nodes/pointcut.png");
    }
    this.myIcon = myIcon;
    myText = TypeNameManager.getTypeName(myClass);

    if(getHiders() == null) DomUtil.getFile(myTreeView.getRootElement()).putUserData(BaseDomElementNode.TREE_NODES_HIDERS_KEY, new HashMap<Class, Boolean>());

    if(getHiders().get(myClass) == null) getHiders().put(myClass, true);
  }

  public void update(final AnActionEvent e) {
    super.update(e);

    e.getPresentation().setIcon(myIcon);
    e.getPresentation().setText((getHiders().get(myClass) ? "Hide ":"Show ")+myText);

    e.getPresentation().setEnabled(getHiders() != null && getHiders().get(myClass)!=null);
  }

  public boolean isSelected(AnActionEvent e) {
    return getHiders().get(myClass);
  }

  private Map<Class, Boolean> getHiders() {
    return DomUtil.getFile(myTreeView.getRootElement()).getUserData(BaseDomElementNode.TREE_NODES_HIDERS_KEY);
  }

  public void setSelected(AnActionEvent e, boolean state) {
    getHiders().put(myClass, state);
    myTreeView.getBuilder().updateFromRoot();
  }
}


text:
package org.apache.hadoop.fs.azurebfs.contracts.exceptions;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.azurebfs.contracts.services.AzureServiceErrorCode;

/**
 * Exception to wrap invalid Azure service error responses.
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class InvalidAbfsRestOperationException extends AbfsRestOperationException {
  public InvalidAbfsRestOperationException(
      final Exception innerException) {
    super(
        AzureServiceErrorCode.UNKNOWN.getStatusCode(),
        AzureServiceErrorCode.UNKNOWN.getErrorCode(),
        "InvalidAbfsRestOperationException",
        innerException);
  }
}


text:
package com.gettipsi.stripe.util;

public interface Fun0<R> {
  R call();
}


text:
from flask import g, current_app
import redis
from redlock import RedLockFactory
import cPickle as pickle
from werkzeug._compat import integer_types

import logging
log = logging.getLogger(__name__)

REDIS_DB = 0  # We always use the main redis db for now

class RedisCache(object):
    """
    A wrapper around the redis cache cluster which adds tenancy
    """
    conn = None
    tenant = None
    disabled = False
    redlock = None

    def __init__(self, tenant=None, service_name=None, redis_server=None):
        conn_info = current_app.config.get("redis_connection_info")
        if not redis_server:
            redis_server = current_app.config.get("redis_server", None)
        self.disabled = conn_info.get("disabled", False)
        if self.disabled:
            log.warning("Redis is disabled!")
            return
        if not redis_server:
            try:
                redis_server = g.driftenv_objects["redis_server"]
            except Exception:
                log.info("'redis_server' not found in config. Using default server '%s'",
                         conn_info["host"])
                redis_server = conn_info["host"]
        self.tenant = tenant or g.driftenv["name"]
        self.service_name = service_name or current_app.config["name"]
        self.host = redis_server
        self.port = conn_info["port"]
        self.conn = redis.StrictRedis(
            host=self.host,
            port=self.port,
            socket_timeout=conn_info.get("socket_timeout", 5),
            socket_connect_timeout=conn_info.get("socket_connect_timeout", 5),
            db=REDIS_DB,
        )

        self.key_prefix = "{}.{}:".format(self.tenant, self.service_name)

        self.redlock_factory = RedLockFactory(
            connection_details=[
                {
                    'host': self.host,
                    'port': self.port,
                    'db': REDIS_DB,
                }
            ],
        )

        log.debug("RedisCache initialized. self.conn = %s", self.conn)

    def make_key(self, key):
        """
        Create a redis key with tenant and service embedded into the key
        """
        return self.key_prefix + key

    def dump_object(self, value):
        """Dumps an object into a string for redis.  By default it serializes
        integers as regular string and pickle dumps everything else.
        """
        t = type(value)
        if t in integer_types:
            return str(value).encode('ascii')
        return b'!' + pickle.dumps(value)

    def load_object(self, value):
        """The reversal of :meth:`dump_object`.  This might be called with
        None.
        """
        if value is None:
            return None
        if value.startswith(b'!'):
            try:
                return pickle.loads(value[1:])
            except pickle.PickleError:
                return None
        try:
            return int(value)
        except ValueError:
            return value

    def set(self, key, value, expire=-1):
        compound_key = self.make_key(key)
        dump = self.dump_object(value)
        if expire == -1:
            result = self.conn.set(name=compound_key, value=dump)
        else:
            result = self.conn.setex(name=compound_key, value=dump, time=expire)

        return result

    def get(self, key):
        compound_key = self.make_key(key)
        try:
            ret = self.conn.get(compound_key)
        except redis.RedisError as e:
            self._log_error(e)
            return None

        ret = self.load_object(ret)
        return ret

    def delete(self, key):
        """
        Delete the item with the specified key
        """
        if self.disabled:
            log.info("Redis disabled. Not deleting key '%s'", key)
            return None
        compound_key = self.make_key(key)
        self.conn.delete(compound_key)

    def incr(self, key, amount=1, expire=None):
        """
        Increments the value of 'key' by 'amount'. If no key exists,
        the value will be initialized as 'amount'
        """
        if self.disabled:
            log.info("Redis disabled. Not incrementing key '%s'", key)
            return None
        compound_key = self.make_key(key)
        self.conn.incr(compound_key, amount)
        if expire:
            self.conn.expire(compound_key, expire)

    def lock(self, lock_name):
        return self.redlock_factory.create_lock(self.make_key(lock_name),
                                                retry_times=20,
                                                retry_delay=300)


text:
/**
 * Forward declarations because the compiler doesn't know these types yet.
 */
struct _zend_class_entry;
typedef struct _zend_class_entry zend_class_entry;

namespace Php
{

/**
 * Forward declarations because the compiler doesn't know these types yet.
 */
class Value;

/**
 * Allows access to information on the specified object, basiclly represents the
 * specified PHP object in C++.
 * @author Swen Kooij
 */
class ObjectInfo
{
public:
	/**
	 * Initializes a new instance of the ObjectInfo class, which allows access to
	 * object information on the specified object.
	 * @param value An instance of the Php::Value class, if the specified value is not
	 * 				an object, an exception will be thrown.
	 */
	ObjectInfo(const Value &value);

	/**
	 * Gets the name of the class this object is of.
	 * @returns The name of the class this object is of, if the name could not be retrieved, an empty string will be returned.
	 */
	std::string GetClassName();

	/**
	 * Gets an instance of the Php::Base class, which is the class that all of our objects
	 * inherit from.
	 *
	 * @returns A pointer to an instance of the Base class, which represents this object.
	 * 			Returns NULL if something went wrong.
	 */
	Base * GetObject();

	/**
	 * Gets the amount of references that exist to this object.
	 * @returns An integer, indicating the amount of references that exist to this object.
	 * 			Or, -1 when something went wrong.
	 */
	int GetReferenceCount();

	/**
	 * Gets the name of the file the definition of this class resides in.
	 * @returns A string containing the name of the file this class resides in,
	 * 		    or an empty string if something went wrong.
	 */
	std::string GetFilename();

	/**
	 * Gets a pointer to the underlying object by casting the base object to the specified
	 * type.
	 * @note If the base object could not be retrieved, or the base object could not be
	 *  	 converted into the specified type, NULL will be returned.
	 * @note Do not specify a pointer type in the type specifier, specify a type, a pointer
	 * 		 of the specified type will be returned.
	 * @note Free the damn pointEclipseer when you're done.
	 * @tparam The type to convert (dynamic cast) to retrieved object to.
	 * @returns A pointer to the underlying object.
	 */
	template<typename T>
	T* GetObjectPtr()
	{
		Base * base_obj = GetObject();
		if(base_obj == NULL)
			return NULL;

		return dynamic_cast<T*>(base_obj);
	}

private:
	/**
	 * The value that this instance was initialized with.
	 */
	const Value & 					m_value;
};
} // namespace Php


text:
output(blue, ONBOARDLED, "off", "on").set("on");
input(button1, D3, "released", "pressed").with_threshold(3);


text:
from msrest.serialization import Model

class X12ValidationOverride(Model):
    """X12ValidationOverride.

    :param message_id: The message id on which the validation settings has to
     be applied.
    :type message_id: str
    :param validate_edi_types: The value indicating whether to validate EDI
     types.
    :type validate_edi_types: bool
    :param validate_xsd_types: The value indicating whether to validate XSD
     types.
    :type validate_xsd_types: bool
    :param allow_leading_and_trailing_spaces_and_zeroes: The value indicating
     whether to allow leading and trailing spaces and zeroes.
    :type allow_leading_and_trailing_spaces_and_zeroes: bool
    :param validate_character_set: The value indicating whether to validate
     character Set.
    :type validate_character_set: bool
    :param trim_leading_and_trailing_spaces_and_zeroes: The value indicating
     whether to trim leading and trailing spaces and zeroes.
    :type trim_leading_and_trailing_spaces_and_zeroes: bool
    :param trailing_separator_policy: The trailing separator policy. Possible
     values include: 'NotSpecified', 'NotAllowed', 'Optional', 'Mandatory'
    :type trailing_separator_policy: str or :class:`TrailingSeparatorPolicy
     <azure.mgmt.logic.models.TrailingSeparatorPolicy>`
    """

    _attribute_map = {
        'message_id': {'key': 'messageId', 'type': 'str'},
        'validate_edi_types': {'key': 'validateEDITypes', 'type': 'bool'},
        'validate_xsd_types': {'key': 'validateXSDTypes', 'type': 'bool'},
        'allow_leading_and_trailing_spaces_and_zeroes': {'key': 'allowLeadingAndTrailingSpacesAndZeroes', 'type': 'bool'},
        'validate_character_set': {'key': 'validateCharacterSet', 'type': 'bool'},
        'trim_leading_and_trailing_spaces_and_zeroes': {'key': 'trimLeadingAndTrailingSpacesAndZeroes', 'type': 'bool'},
        'trailing_separator_policy': {'key': 'trailingSeparatorPolicy', 'type': 'TrailingSeparatorPolicy'},
    }

    def __init__(self, message_id=None, validate_edi_types=None, validate_xsd_types=None, allow_leading_and_trailing_spaces_and_zeroes=None, validate_character_set=None, trim_leading_and_trailing_spaces_and_zeroes=None, trailing_separator_policy=None):
        self.message_id = message_id
        self.validate_edi_types = validate_edi_types
        self.validate_xsd_types = validate_xsd_types
        self.allow_leading_and_trailing_spaces_and_zeroes = allow_leading_and_trailing_spaces_and_zeroes
        self.validate_character_set = validate_character_set
        self.trim_leading_and_trailing_spaces_and_zeroes = trim_leading_and_trailing_spaces_and_zeroes
        self.trailing_separator_policy = trailing_separator_policy


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rhus chiangii D.A.Young

### Remarks
null


text:
<?php
/**
 * Daitel Framework
 * Basic Application
 *
 * @author Nikita Fedoseev <agent.daitel@gmail.com>
 * @link https://github.com/daitel/framework
 * @since 0.2.1
 */

//include framework
if (file_exists("../../framework/DfBase.php")) {
    require_once "../../framework/DfBase.php";
} elseif (file_exists("framework/DfBase.php")) {
    require_once "framework/DfBase.php";
} else {
    die("Unable to include framework");
}

//include config
require_once "app/config/config.php";

//start application
DfApp::start($config);


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:duration="300" />
</set>


text:
require File.join(File.dirname(__FILE__), '..', '..', 'test_helper')
require 'shoulda'
require 'fileutils'
require 'mocha/setup'
include EnsureConfigHelper
include MarkusConfigurator

class EnsureConfigHelperTest < ActiveSupport::TestCase

  context 'A configured default language with language file present in config/locales' do
    should 'not raise an exception' do
      EnsureConfigHelper.check_configured_default_language('en')
    end
  end

  context 'A configured default language with language file not present in config/locales' do
    should 'raise an exception' do
      assert_raise RuntimeError do
        EnsureConfigHelper.check_configured_default_language('es')
      end
    end
  end

  context 'setting up the markus_configurator' do

    setup do
      @temp_dir = "./tmp/ensure_config_helper_test_#{rand(1073741824)}"
      @log_dir = "#{@temp_dir}/log"
      @log_info_file = "#{@log_dir}/log_info_file.log"
      @log_error_file = "#{@log_dir}/log_error_file.log"
      @source_repo_dir = "#{@temp_dir}/source_repo_dir"
      @validate_script = "#{@temp_dir}/validate_script.sh"
      MarkusConfigurator.stubs(:markus_config_logging_logfile).returns(@log_info_file)
      MarkusConfigurator.stubs(:markus_config_logging_errorlogfile).returns(@log_error_file)
      MarkusConfigurator.stubs(:markus_config_repository_storage).returns(@source_repo_dir)
      MarkusConfigurator.stubs(:markus_config_validate_file).returns(@validate_script)
      FileUtils.mkdir( @temp_dir )
    end

    teardown do
      FileUtils.rm_r( @temp_dir )
    end

    context 'running ensure config when all required files are missing' do
      should 'throw an exception' do
        assert_raise RuntimeError do
          EnsureConfigHelper.check_config()
        end
      end
    end

    context 'with a log dir' do
      setup do
        FileUtils.mkdir( @log_dir )
      end
      should 'throw an exception because the validate file and repo do not exist' do
        assert_raise RuntimeError do
          EnsureConfigHelper.check_config()
        end
      end

      context 'with a repo dir' do
        setup do
          FileUtils.mkdir( @source_repo_dir )
        end
        should 'throw an exception because the validate file does not exist' do
          #MarkUs on Windows does not support external authentication so skip if Windows platform
          unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
              if RUBY_VERSION > '1.9'
                assert_raise Errno::ENOENT do
                  EnsureConfigHelper.check_config()
                end
              else
                assert_raise RuntimeError do
                  EnsureConfigHelper.check_config()
                end
              end
          end
        end

        context 'with an unexecutable validate file' do
          setup do
            FileUtils.touch([ @validate_script ])
            FileUtils.chmod( 0600, [ @validate_script ])
          end
          should 'throw an exception because the validate file is not executable' do
            #MarkUs on Windows does not support external authentication so skip if Windows platform
            if !(RUBY_PLATFORM =~ /(:?mswin|mingw)/)
              if RUBY_VERSION > '1.9'
                assert_raise Errno::EACCES do
                  EnsureConfigHelper.check_config()
                end
              else
                assert_raise RuntimeError do
                  EnsureConfigHelper.check_config()
                end
              end
            end
          end
        end

        context 'with an executable validate file' do
          setup do
            FileUtils.touch([ @validate_script ])
            FileUtils.chmod( 0700, [ @validate_script ])
            f = File.open( @validate_script, 'w' )
            f.write( "#!/bin/bash\n" )
            f.write( "read user\n" )
            f.write( "read password\n" )
            f.write( 'exit 0' )
            f.close
          end
          should 'accept the configuration because all files and directories are ready' do
            assert_nothing_raised do
              EnsureConfigHelper.check_config()
            end
          end
        end

        context 'with an executable validate file with an escaped space' do
          setup do
            @validate_script = "#{@temp_dir}/validate script.sh"
            FileUtils.touch([ @validate_script ])
            FileUtils.chmod( 0700, [ @validate_script ])
            f = File.open( @validate_script, 'w' )
            f.write( "#!/bin/bash\n" )
            f.write( "read user\n" )
            f.write( "read password\n" )
            f.write( 'exit 0' )
            f.close

            # escaping
            @validate_script = "#{@temp_dir}/validate\\ script.sh"
            MarkusConfigurator.stubs(:markus_config_validate_file).returns(@validate_script)
          end
          should 'accept the configuration because all files and directories are ready' do
            assert_nothing_raised do
              EnsureConfigHelper.check_config()
            end
          end
        end

        context 'with an executable that is not properly escaped' do
          setup do
            @validate_script = "#{@temp_dir}/validate script.sh"
            FileUtils.touch([ @validate_script ])
            FileUtils.chmod( 0700, [ @validate_script ])
            MarkusConfigurator.stubs(:markus_config_validate_file).returns(@validate_script)
            f = File.open( @validate_script, 'w' )
            f.write( "#!/bin/bash\n" )
            f.write( "read user\n" )
            f.write( "read password\n" )
            f.write( 'exit 0' )
            f.close
          end
          should 'not pass the check_if_executes' do
            #External validation is not supported on Windows so skip this test if platform is Windows
            if !(RUBY_PLATFORM =~ /(:?mswin|mingw)/)
              if RUBY_VERSION > '1.9'
                assert_raise Errno::ENOENT do
                  EnsureConfigHelper.check_config()
                end
              else
                assert_raise RuntimeError do
                  EnsureConfigHelper.check_config()
                end
              end
            end
          end
        end

      end
    end
  end
end


text:
package service

import (
	"errors"
	"fmt"
	"path/filepath"
	"strings"

	"github.com/qiniu/logkit/sender"
	"github.com/qiniu/logkit/transforms"
	"github.com/qiniu/logkit/utils"
)

const (
	K8sTagType       = "k8stag"
	K8sPodName       = "k8s_pod_name"
	K8sNamespace     = "k8s_namespace"
	K8sContainerName = "k8s_container_name"
	K8sContainerId   = "k8s_container_id"
)

type K8sTag struct {
	SourceFileKey string `json:"sourcefilefield"`
	stats         utils.StatsInfo
}

func (g *K8sTag) RawTransform(datas []string) ([]string, error) {
	return datas, errors.New("k8stag transformer not support rawTransform")
}

func (g *K8sTag) Transform(datas []sender.Data) ([]sender.Data, error) {
	var err, ferr error
	errnums := 0
	for i := range datas {
		val, ok := datas[i][g.SourceFileKey]
		if !ok {
			errnums++
			err = fmt.Errorf("transform key %v not exist in data", g.SourceFileKey)
			continue
		}
		strval, ok := val.(string)
		if !ok {
			errnums++
			err = fmt.Errorf("transform key %v data type is not string", g.SourceFileKey)
			continue
		}
		strval = filepath.Base(strval)
		splits := strings.Split(strval, "_")
		if len(splits) < 3 {
			errnums++
			err = fmt.Errorf("k8stag transform sourcefile must has more than 2 sperated field but now only %v fields of %v", len(splits), strval)
			continue
		}
		datas[i][K8sPodName] = splits[0]
		datas[i][K8sNamespace] = splits[1]
		container_info := strings.TrimSuffix(strings.Join(splits[2:], "_"), ".log")
		container_info_splits := strings.Split(container_info, "-")
		datas[i][K8sContainerId] = container_info_splits[len(container_info_splits)-1]
		datas[i][K8sContainerName] = strings.Join(container_info_splits[0:len(container_info_splits)-1], "-")
	}
	if err != nil {
		g.stats.LastError = err.Error()
		ferr = fmt.Errorf("find total %v erorrs in transform k8stag, last error info is %v", errnums, err)
	}
	g.stats.Errors += int64(errnums)
	g.stats.Success += int64(len(datas) - errnums)
	return datas, ferr
}

func (g *K8sTag) Description() string {
	//return "k8stag will get kubernetes tags from sourcefile name"
	return "从sourcefile name中获取kubernetes tags"
}

func (g *K8sTag) Type() string {
	return K8sTagType
}

func (g *K8sTag) SampleConfig() string {
	return `{
		"type":"k8stag",
		"sourcefilefield":"datasource"
	}`
}

func (g *K8sTag) ConfigOptions() []utils.Option {
	return []utils.Option{
		transforms.KeyStageAfterOnly,
		transforms.KeyFieldName,
	}
}

func (g *K8sTag) Stage() string {
	return transforms.StageAfterParser
}

func (g *K8sTag) Stats() utils.StatsInfo {
	return g.stats
}

func init() {
	transforms.Add(K8sTagType, func() transforms.Transformer {
		return &K8sTag{}
	})
}