text:
import boto3
import os

class Deployment(object):
	def __init__(self, session, bucket, key):
		self.session = session
		self.bucket = bucket
		self.key = key
		self.s3 = session.resource('s3')
		self.codedeploy = session.client('codedeploy')

	def upload(self, package):
		self.bundleType = os.path.splitext(package)[1].replace('.','')

		try:
			self.s3.meta.client.upload_file(package, self.bucket, self.key)

		except ValueError:
			logging.critical('Unable to upload package to s3.')
			exit(3)

	def deploy(self, application, deploymentGroup, deploymentConfig):

		try:
			deployment = self.codedeploy.create_deployment(
				applicationName=application,
				deploymentGroupName=deploymentGroup,
				revision={
					'revisionType': 'S3',
					's3Location': {
						'bucket': self.bucket,
						'key': self.key,
						'bundleType': self.bundleType,

					}
				},
				deploymentConfigName=deploymentConfig
			)
		except ValueError:
			logging.critical('Failure to deploy to deployment group {0}, consult the aws console for more information'.format(deploymentGroup))
			exit(4)

		self.deploymentId=deployment['deploymentId']

	def __get__(self, obj, objtype):
		return self.val


text:
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'

import { fileShortPath } from '@waiting/shared-core'
import { sleep } from 'zx'

import { user32FindWindowEx } from '../../src/index.fun.js'
import { calcLpszWindow } from '../config.unittest.js'
import { user32, destroyWin } from '../helper.js'

describe(fileShortPath(import.meta.url), () => {
  it('IsIconic()', async () => {
    const child = spawn('calc.exe')
    await sleep(1500)

    const hWnd = await user32FindWindowEx(0, 0, null, calcLpszWindow)
    assert((typeof hWnd === 'string' && hWnd.length > 0) || hWnd > 0, 'invalid hWnd')

    assert(! await user32.IsIconic(hWnd))
    await user32.ShowWindow(hWnd, 2) // minimize
    assert(await user32.IsIconic(hWnd))

    await destroyWin(hWnd)
    child.kill()
  })
})

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by 李 on 2017/3/8.
 */
import { NgModule } from '@angular/core';
import {AppShareModule} from "./app-share.module";
import {SignUpRoutingModule} from "../component/home/signup.router";
import {SignUpComponent} from "../component/home/signup.component";

@NgModule({
    imports: [AppShareModule,SignUpRoutingModule],
    declarations: [SignUpComponent],
    providers: [],
})
export class SignUpModule { }


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

namespace NRules.Diagnostics.Dgml;

internal class Style
{
    public Style(string targetType)
    {
        TargetType = targetType;
    }

    public string TargetType { get; }
    public string GroupLabel { get; set; }
    public string ValueLabel { get; set; }
    public List<Condition> Conditions { get; set; } = new();
    public List<Setter> Setters { get; set; } = new();

    public Style HasCategory(string category)
    {
        return Condition($"HasCategory('{category}')");
    }

    public Style Condition(string expression)
    {
        var condition = new Condition {Expression = expression};
        Conditions.Add(condition);
        return this;
    }

    public Style Setter(string property, string value = null, string expression = null)
    {
        var setter = new Setter {Property = property, Value = value, Expression = expression};
        Setters.Add(setter);
        return this;
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement(nameof(Style));
        writer.WriteAttributeString(nameof(TargetType), TargetType);
        writer.WriteAttributeIfNotNull(nameof(GroupLabel), GroupLabel);
        writer.WriteAttributeIfNotNull(nameof(ValueLabel), ValueLabel);

        foreach (var condition in Conditions)
            condition.WriteXml(writer);

        foreach (var setter in Setters)
            setter.WriteXml(writer);

        writer.WriteEndElement();
    }
}


text:
let logger = require('../services/logger.js');

module.exports = app => {

    let api = {};
    let dao = app.dao.user;

    api.list = (req, res) => {
        dao.list().then(
            usersList => res.json(userList),
            error => res.sendStatus(500)
        );
    };

    api.findById = (req, res) => {
        let id = req.params.id;
        dao.findById(id).then(
            user => res.json(user),
            error => res.sendStatus(500)
        );
    };

    api.findByTeam = (req, res) => {
        let team = req.params.team;
        dao.findByTeam(team).then(
            users => res.json(users),
            error => res.sendStatus(500)
        );
    };

    api.insert = (req, res) => {
        let errors = runExpressValidator(req);
        if (errors) {
            res.status(400).send(errors);
            return;
        }

        dao.insert(req.body).then(
            user => res.json(user),
            error => res.sendStatus(500)
        );
    };

    api.update = (req, res) => {
        let errors = runExpressValidator(req);
        if (errors) {
            res.status(400).send(errors);
            return;
        }

        dao.update(req.params.id, req.body).then(
            user => res.json(user),
            error => es.sendStatus(500)
        );
    };

    api.delete = (req, res) => {
        dao.delete(req.params.id).then(
            success => res.sendStatus(200),
            error => res.sendStatus(500)
        );
    };

    let runExpressValidator = (req) => {
        req.assert("name", "user.name is required").notEmpty();
        req.assert("email", "user.email is required and must be an email").notEmpty().isEmail();
        req.assert("user", "user.user is required and must have between 3 and 15 characters").notEmpty().len(3, 15);
        req.assert("password", "user.password is required and must have between 6 and 20 characters").notEmpty().len(6, 20);
        req.assert("teams", "user.teams is required").notEmpty().isArray();
        req.assert("active", "user.active is required and must be boolean").notEmpty().isBoolean();
        req.assert("admin", "user.admin is required and must be boolean").notEmpty().isBoolean();

        return req.validationErrors();
    }

    return api;
};


text:
#include <string.h>
#include <stdlib.h>
#include "libc_logging.h"

/*
 * __strlcat_chk. Called in place of strlcat() when we know the
 * size of the buffer we're writing into.
 *
 * See
 *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
 *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
 * for details.
 *
 * This strlcat check is called if _FORTIFY_SOURCE is defined and
 * greater than 0.
 */
extern "C" size_t __strlcat_chk(char *dest, const char *src,
              size_t supplied_size, size_t dest_len_from_compiler)
{
    if (__predict_false(supplied_size > dest_len_from_compiler)) {
        __fortify_chk_fail("strlcat buffer overflow", 0);
    }

    return strlcat(dest, src, supplied_size);
}


text:
package org.apache.flink.state.changelog;

import org.apache.flink.api.common.state.State;
import org.apache.flink.api.common.state.StateDescriptor;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.runtime.state.KeyGroupedInternalPriorityQueue;
import org.apache.flink.runtime.state.heap.InternalKeyContext;
import org.apache.flink.runtime.state.internal.InternalKvState;
import org.apache.flink.runtime.state.metainfo.StateMetaInfoSnapshot;
import org.apache.flink.util.FlinkRuntimeException;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/** Maintains the lifecycle of all {@link ChangelogState}s. */
public class ChangelogStateFactory {

    /**
     * Unwrapped changelog states used for recovery (not wrapped into e.g. TTL, latency tracking).
     */
    private final Map<String, ChangelogState> changelogStates;

    private final Map<String, ChangelogKeyGroupedPriorityQueue<?>> priorityQueueStatesByName;

    public ChangelogStateFactory() {
        this.changelogStates = new HashMap<>();
        this.priorityQueueStatesByName = new HashMap<>();
    }

    private static final Map<StateDescriptor.Type, StateFactory> STATE_FACTORIES =
            Stream.of(
                            Tuple2.of(
                                    StateDescriptor.Type.VALUE,
                                    (StateFactory) ChangelogValueState::create),
                            Tuple2.of(
                                    StateDescriptor.Type.LIST,
                                    (StateFactory) ChangelogListState::create),
                            Tuple2.of(
                                    StateDescriptor.Type.REDUCING,
                                    (StateFactory) ChangelogReducingState::create),
                            Tuple2.of(
                                    StateDescriptor.Type.AGGREGATING,
                                    (StateFactory) ChangelogAggregatingState::create),
                            Tuple2.of(
                                    StateDescriptor.Type.MAP,
                                    (StateFactory) ChangelogMapState::create))
                    .collect(Collectors.toMap(t -> t.f0, t -> t.f1));

    public <K, N, V, S extends State> ChangelogState create(
            StateDescriptor<S, V> stateDescriptor,
            InternalKvState<K, N, V> internalKvState,
            KvStateChangeLogger<V, N> kvStateChangeLogger,
            InternalKeyContext<K> keyContext)
            throws Exception {
        ChangelogState changelogState =
                getStateFactory(stateDescriptor)
                        .create(internalKvState, kvStateChangeLogger, keyContext);
        changelogStates.put(stateDescriptor.getName(), changelogState);
        return changelogState;
    }

    public <T> ChangelogKeyGroupedPriorityQueue<T> create(
            String stateName,
            KeyGroupedInternalPriorityQueue<T> internalPriorityQueue,
            StateChangeLogger<T, Void> logger,
            TypeSerializer<T> serializer) {
        ChangelogKeyGroupedPriorityQueue<T> changelogKeyGroupedPriorityQueue =
                new ChangelogKeyGroupedPriorityQueue<>(internalPriorityQueue, logger, serializer);
        priorityQueueStatesByName.put(stateName, changelogKeyGroupedPriorityQueue);
        return changelogKeyGroupedPriorityQueue;
    }

    /**
     * @param name state name
     * @param type state type (the only supported type currently are: {@link
     *     StateMetaInfoSnapshot.BackendStateType#KEY_VALUE key value}, {@link
     *     StateMetaInfoSnapshot.BackendStateType#PRIORITY_QUEUE priority queue})
     * @return an existing state, i.e. the one that was already created. The returned state will not
     *     apply TTL to the passed values, regardless of the TTL settings. This prevents double
     *     applying of TTL (recovered values are TTL values if TTL was enabled). The state will,
     *     however, use TTL serializer if TTL is enabled. WARN: only valid during the recovery.
     * @throws UnsupportedOperationException if state type is not supported
     */
    public ChangelogState getExistingState(String name, StateMetaInfoSnapshot.BackendStateType type)
            throws UnsupportedOperationException {
        ChangelogState state;
        switch (type) {
            case KEY_VALUE:
                state = changelogStates.get(name);
                break;
            case PRIORITY_QUEUE:
                state = priorityQueueStatesByName.get(name);
                break;
            default:
                throw new UnsupportedOperationException(
                        String.format("Unknown state type %s (%s)", type, name));
        }
        return state;
    }

    public void resetAllWritingMetaFlags() {
        for (ChangelogState changelogState : changelogStates.values()) {
            changelogState.resetWritingMetaFlag();
        }

        for (ChangelogKeyGroupedPriorityQueue<?> priorityQueueState :
                priorityQueueStatesByName.values()) {
            priorityQueueState.resetWritingMetaFlag();
        }
    }

    public void dispose() {
        changelogStates.clear();
        priorityQueueStatesByName.clear();
    }

    private <S extends State, V> StateFactory getStateFactory(
            StateDescriptor<S, V> stateDescriptor) {
        StateFactory stateFactory = STATE_FACTORIES.get(stateDescriptor.getType());
        if (stateFactory == null) {
            String message =
                    String.format(
                            "State %s is not supported by %s",
                            stateDescriptor.getClass(), ChangelogKeyedStateBackend.class);
            throw new FlinkRuntimeException(message);
        }
        return stateFactory;
    }

    // Factory function interface
    private interface StateFactory {
        <K, N, SV, S extends State, IS extends S> IS create(
                InternalKvState<K, N, SV> kvState,
                KvStateChangeLogger<SV, N> changeLogger,
                InternalKeyContext<K> keyContext)
                throws Exception;
    }
}


text:
<?php

namespace Sylius\Bundle\MetadataBundle\Form\Type;

use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Kamil Kokot <kamil.kokot@lakion.com>
 */
class MetadataContainerType extends AbstractResourceType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id', 'text', ['read_only' => true])
            ->add('metadata', 'sylius_page_metadata')
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sylius_metadata_container';
    }
}


text:
package gov.nist.registry.ws.serviceclasses;

import gov.nist.registry.common2.exception.XdsErrorCodeException;
import gov.nist.registry.common2.exception.XdsInternalException;
import gov.nist.registry.common2.registry.AdhocQueryResponse;
import gov.nist.registry.common2.registry.MetadataSupport;
import gov.nist.registry.common2.registry.Properties;
import gov.nist.registry.common2.registry.RegistryErrorList;
import gov.nist.registry.common2.registry.RegistryResponse;
import gov.nist.registry.common2.registry.RetrieveMultipleResponse;
import gov.nist.registry.common2.service.AppendixV;
import gov.nist.registry.ws.log.Fields;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;

import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMException;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.Constants;
import org.apache.axis2.context.MessageContext;
import org.apache.commons.logging.LogFactory;
import org.openhealthtools.openxds.XdsFactory;
import org.openhealthtools.openxds.log.Log;
import org.openhealthtools.openxds.log.LoggerException;

public class XdsService extends AppendixV {
	protected Log log = null;
	private final static org.apache.commons.logging.Log logger = LogFactory.getLog(XdsService.class);
	String service_name;
	boolean is_secure;
	static public String technicalFramework = null;
	static public String registerAEndpoint = null;
	static public String registerBEndpoint = null;
	String incoming_ip_address;

	static {
//		BasicConfigurator.configure();
		if (registerAEndpoint == null)
			registerAEndpoint = "http://localhost:9080/" + XdsService.technicalFramework + "/services/xdsregistryainternal";
		if (registerBEndpoint == null)
			registerBEndpoint = "http://localhost:9080/" + XdsService.technicalFramework + "/services/xdsregistryb";
	}

	protected boolean isSecure() { return is_secure; }

	public void useXop() {
		this.return_message_context = MessageContext.getCurrentMessageContext();
		if (return_message_context != null)
			return_message_context.getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
	}

	protected String getClientIPAddress() {
		return incoming_ip_address;
	}

	protected OMElement beginTransaction(String service_name, OMElement request, short actor) {

		// This gets around a bug in Leopard (MacOS X 10.5) on Macs
		// Though removing this property fixes a Mac problem, but it disables transactions via proxy server in a production environment
		//System.setProperty("http.nonProxyHosts", "");

		this.service_name = service_name;

		String incoming_ip_address = null;
		if (getMessageContext().getFrom() != null) {
			incoming_ip_address = getMessageContext().getFrom().getAddress();
		} else {
			incoming_ip_address = (String)getMessageContext().getProperty(MessageContext.REMOTE_ADDR);
		}

//		incoming_ip_address = getMessageContext().getFrom().getAddress();
//		for (int i=1; i<100; i++) {
//			String entry = this.properties.getString("BlockIp" + i);
//			if (entry == null || entry.equals(""))
//				break;
//			if (entry.equals(incoming_ip_address))
//				return start_up_error(request, null, actor, "Continuous jamming from IP " + incoming_ip_address + " - access blocked");
//		}

		logger.info("Start " + service_name + " : " + incoming_ip_address  + " : " + getMessageContext().getTo().toString());
		try {
			startTransactionLog();
			if (log != null && log_message == null) {
//				log_message = log.createMessage(getMessageContext().getFrom().getAddress());
				log_message = log.createMessage(incoming_ip_address);
			}
			log_message.addOtherParam(Fields.service, service_name);
			is_secure = getMessageContext().getTo().toString().indexOf("https://") != -1;
			log_message.addHTTPParam(Fields.isSecure, (is_secure) ? "true" : "false");
			log_message.addHTTPParam(Fields.date, getDateTime());
			log_message.setSecure(is_secure);
			if (request != null)
				log_message.addOtherParam("Request", request.toString());
			else {
				log_message.addErrorParam("Error", "Cannot access request body in XdsService.begin_service()");
				return start_up_error(request, null, actor, "Request body is null");
			}

            HashMap transportHeaders = (HashMap)getMessageContext().getProperty("TRANSPORT_HEADERS");
			for (Object o_key : transportHeaders.keySet()) {
				String key = (String) o_key;
				String value = (String) transportHeaders.get(key);

				if (logger.isDebugEnabled()) {
					logger.debug("request header=" + key +", value=" + value );
				}

				Vector<String> thdrs = new Vector<String>();
				thdrs.add(key + " : " + value);
				addHttp( "HTTP Header", thdrs ) ;
			}

			if ( getMessageContext().getEnvelope().getHeader() != null )
			{

				try {
					addSoap ( "Soap Header", getMessageContext().getEnvelope().getHeader().toStringWithConsume() ) ;
				}  catch (OMException e) {} catch (XMLStreamException e) {}
			}

			if ( getMessageContext().getEnvelope().getBody() != null )
			{
				try
				{
					addSoap( "Soap Envelope", getMessageContext().getEnvelope().toStringWithConsume() );
				}  catch (OMException e) {} catch (XMLStreamException e) {}
			}
//			log_message.addHTTPParam(Fields.fromIpAddress , getMessageContext().getFrom().getAddress() ) ;
			log_message.addHTTPParam(Fields.fromIpAddress , incoming_ip_address ) ;
			log_message.addHTTPParam(Fields.endpoint , getMessageContext().getTo().toString() ) ;

			return null;  // no error
		} catch (LoggerException e) {
			logger.error("LoggerException: new Log: " + e.getMessage());
			e.printStackTrace();
			stopTransactionLog();
			return start_up_error(request, e, actor, "Internal Error:Cannot access Test Log Facility");
		}
	}

	protected void endTransaction(boolean status) {
		logger.info(service_name + " " + " : "
				+ ((status) ? "Pass" : "Fail"));

		stopTransactionLog();
	}

	public void generateLogMessage(OMElement response) {
		try {
			log_message.addOtherParam("Response", response.toString());
		} catch (Exception e) {

		}
	}

	protected OMElement endTransaction(OMElement request, Exception e, short actor, String message) {
		if (message == null || message.equals(""))
			message = e.getMessage();
		logger.error("Exception: " + exception_details(e));
		OMElement response = start_up_error(request, e, actor, message);
		generateLogMessage(response);
		endTransaction(false);
		return response;
	}

	protected OMElement endTransaction(OMElement request, Exception e, short actor, String message, String error_type) {
		if (message == null || message.equals(""))
			message = e.getMessage();
		logger.error("Exception: " + exception_details(e));
		OMElement response = start_up_error(request, e, actor, message, false, error_type);
		generateLogMessage(response);
		endTransaction(false);
		return response;
	}

	public OMElement start_up_error(OMElement request, Exception e, short actor,String message) {
		return start_up_error(request, e, actor, message, false);
	}

	public OMElement start_up_error(OMElement request, Object e, short actor,String message, boolean log) {
		String error_type = (actor == REGISTRY_ACTOR) ? MetadataSupport.XDSRegistryError : MetadataSupport.XDSRepositoryError;

		if (e instanceof XdsErrorCodeException) {
			XdsErrorCodeException ec = (XdsErrorCodeException) e;
			error_type = ec.getErrorCode();
			message = "Forced Error";
		}

		return start_up_error(request, e, actor, message, log, error_type);
	}

	public OMElement start_up_error(OMElement request, Object e, short actor,String message, boolean log, String error_type) {
		try {
			String request_type = (request != null) ? request.getLocalName() : "None";
			OMNamespace ns = (request != null) ? request.getNamespace() : MetadataSupport.ebRSns2;

			if (ns.getNamespaceURI().equals(MetadataSupport.ebRSns2.getNamespaceURI())) {
				// xds.a submitobjectsrequest
				RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_2, log);
				rel.add_error(error_type, message, exception_details(e), log_message);
				return new RegistryResponse(RegistryErrorList.version_2, rel).getResponse();
			}
			if (ns.getNamespaceURI().equals(MetadataSupport.ebRSns3.getNamespaceURI())) {
				// xds.b submitobjectsrequest (could be xds.b retrieve)
				RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_3, log);
				rel.add_error(error_type, message, exception_details(e), log_message);
				return new RegistryResponse(RegistryErrorList.version_3, rel).getResponse();
			}
			if (ns.getNamespaceURI().equals(MetadataSupport.xdsB.getNamespaceURI())) {
				// RetrieveDocumentSet
				RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_3, log);
				rel.add_error(error_type, message, exception_details(e), log_message);
				if (request.getLocalName().equals("RetrieveDocumentSetRequest")) {
					OMElement res = new RetrieveMultipleResponse(rel).getResponse();
					return res;
				} else {
					return new RegistryResponse(RegistryErrorList.version_3, rel).getResponse();
				}

			}
			if (ns.getNamespaceURI().equals(MetadataSupport.ebQns3.getNamespaceURI())) {
				// stored query
				RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_3, log);
				rel.add_error(error_type, message, exception_details(e), log_message);
				return new AdhocQueryResponse(RegistryErrorList.version_3, rel).getResponse();
			}
			if (ns.getNamespaceURI().equals(MetadataSupport.ebQns2.getNamespaceURI())) {
				// sql query
				RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_2, log);
				rel.add_error(error_type, message, exception_details(e), log_message);
				return new AdhocQueryResponse(RegistryErrorList.version_2, rel).getResponse();
			}

			// the default when all else fails
			RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_2, log);
			rel.add_error(error_type, message, exception_details(e), log_message);
			return new RegistryResponse(RegistryErrorList.version_2, rel).getResponse();

		} catch (XdsInternalException e1) {
			try {
				RegistryErrorList rel = new RegistryErrorList(RegistryErrorList.version_2, log);
				rel.add_error(error_type, e1.getMessage(), exception_details(e1), log_message);
				return new RegistryResponse(RegistryErrorList.version_2, rel).getResponse();
			} catch (Exception e2) {
				return null;
			}
		}

	}

	protected void startTransactionLog() throws LoggerException {
		if (log == null) {
			logger.info("+++++++++++++++++++++ start transaction log");
			try {
				log = (Log) XdsFactory.getInstance().getBean("logsService");
			} catch (Exception e) {
				new LoggerException("Exception while creating logsService bean object:" + e.getMessage(), e);
			}

		}
	}

	protected void stopTransactionLog() {
		try {
			if (log != null) {
				if (log_message != null)
					log.writeMessage(log_message);
				logger.info("end " + service_name + " :" +((log_message == null) ? "null"  : log_message.getMessageID()));
				log = null;
				log_message = null;
				logger.info("+++++++++++++++++++++ stop transaction log");
			}
		} catch (LoggerException e) {
			logger.error("LoggerException: " + exception_details(e));
		}
	}

	protected String exception_details(Object e) {
		if (e == null)
			return "No Additional Details Available";
		if (e instanceof Exception)
			return exception_details( (Exception) e );
		if (e instanceof String)
			return exception_details( (String) e);
		return exception_details(e.toString());
	}

	protected String exception_details(Exception e) {
		if (e == null)
			return "No stack trace available";
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		PrintStream ps = new PrintStream(baos);
		e.printStackTrace(ps);

		return "Exception thrown: " + e.getClass().getName() + "\n" + e.getMessage() + "\n" + new String(baos.toByteArray());
	}

	protected String exception_details(String e) {
		return e;
	}

	private void addHttp ( String title , Vector<String> t )
	{
		int i = 0 ;
		StringBuffer buffer = new StringBuffer() ;
		for ( String s : t )
		{
			buffer.append(s + "  ") ;
		}

		try
		{
			log_message.addHTTPParam( title , buffer.toString() ) ;
		} catch (LoggerException e) {}
	}
	private void addSoap ( String t , String s )
	{
		try {
			log_message.addSoapParam( t , s ) ;
		} catch (LoggerException e) {}
	}

	protected void addError ( String s )
	{
		try {
			log_message.addErrorParam( "Error" , s ) ;
		} catch (LoggerException e) {}
	}

	protected void addOther ( String name, String s )
	{
		try {
			log_message.addOtherParam( name , s ) ;
		} catch (LoggerException e) {}
	}

	private String getDateTime() {
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		return dateFormat.format(date);
	}

	protected String getForcedErrorCode() {
		String code = null;
		try {
			code = getMessageContext().getParameter("ForceErrorCode").getValue().toString();
		} catch (Exception e) {

		}
		if (code == null) return null;
		if ("".equals(code)) return null;
		return code;
	}

	protected void forceForcedError() throws XdsErrorCodeException {
		String code = getForcedErrorCode();
		if (code == null) return;
		throw new XdsErrorCodeException("Forced Error", code);
	}

}


text:
from jupyter_core.paths import jupyter_data_dir
import subprocess
import os
import errno
import stat

PEM_FILE = os.path.join(jupyter_data_dir(), 'notebook.pem')

c = get_config()
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.tornado_settings = {"xsrf_cookies": False}

# Prefer JavaScript over SVG when exporting notebooks as HTML--keeps figures interactive
c.NbConvertBase.display_data_priority = [
    'application/vnd.jupyter.widget-state+json',
    'application/vnd.jupyter.widget-view+json',
    'application/javascript',
    'image/svg+xml',
    'text/html',
    'text/markdown',
    'text/latex',
    'image/png',
    'image/jpeg',
    'text/plain'
]

# Set a certificate if USE_HTTPS is set to any value
if 'USE_HTTPS' in os.environ:
    if not os.path.isfile(PEM_FILE):
        # Ensure PEM_FILE directory exists
        dir_name = os.path.dirname(PEM_FILE)
        try:
            os.makedirs(dir_name)
        except OSError as exc: # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(dir_name):
                pass
            else: raise
        # Generate a certificate if one doesn't exist on disk
        subprocess.check_call(['openssl', 'req', '-new',
            '-newkey', 'rsa:2048', '-days', '365', '-nodes', '-x509',
            '-subj', '/C=XX/ST=XX/L=XX/O=generated/CN=generated',
            '-keyout', PEM_FILE, '-out', PEM_FILE])
        # Restrict access to PEM_FILE
        os.chmod(PEM_FILE, stat.S_IRUSR | stat.S_IWUSR)
    c.NotebookApp.certfile = PEM_FILE

# Set a password if PASSWORD is set
if 'PASSWORD' in os.environ:
    from IPython.lib import passwd
    c.NotebookApp.password = passwd(os.environ['PASSWORD'])
    del os.environ['PASSWORD']


text:
'use strict';

var grunt = require('grunt');
var fs = require('fs');
var isWindows = process.platform === 'win32';

exports.copy = {
  main: function(test) {
    test.expect(3);

    var actual = fs.readdirSync('tmp/copy_test_files').sort();
    var expected = fs.readdirSync('test/expected/copy_test_files').sort();
    test.deepEqual(expected, actual, 'should copy several files');

    actual = fs.readdirSync('tmp/copy_test_mix').sort();
    expected = fs.readdirSync('test/expected/copy_test_mix').sort();
    test.deepEqual(expected, actual, 'should copy a mix of folders and files');

    actual = fs.readdirSync('tmp/copy_test_v0.1.0').sort();
    expected = fs.readdirSync('test/expected/copy_test_v0.1.0').sort();
    test.deepEqual(expected, actual, 'should parse both dest and src templates');

    test.done();
  },

  noexpandWild: function(test) {
    test.expect(3);

    ['/', '/test/', '/test/fixtures/'].forEach(function(subpath, i) {
      var actual = fs.readdirSync('tmp/copy_test_noexpandWild' + subpath).sort();
      var expected = fs.readdirSync('test/expected/copy_test_noexpandWild' + subpath).sort();
      test.deepEqual(expected, actual, 'should copy file structure at level ' + i);
    });

    test.done();
  },

  flatten: function(test) {
    test.expect(1);

    var actual = fs.readdirSync('tmp/copy_test_flatten').sort();
    var expected = fs.readdirSync('test/expected/copy_test_flatten').sort();
    test.deepEqual(expected, actual, 'should create a flat structure');

    test.done();
  },

  single: function(test) {
    test.expect(1);

    var actual = grunt.file.read('tmp/single.js');
    var expected = grunt.file.read('test/expected/single.js');
    test.equal(expected, actual, 'should allow for single file copy');

    test.done();
  },

  mode: function(test) {
    test.expect(1);

    test.equal(fs.lstatSync('tmp/mode.js').mode.toString(8).slice(-3), '444');

    test.done();
  },

  modeDir: function(test) {
    test.expect(2);
    // on Windows DIRs do not have 'executable' flag, see
    // https://github.com/nodejs/node/blob/master/deps/uv/src/win/fs.c#L1064
    var expectedMode = isWindows ? '666' : '777';
    test.equal(fs.lstatSync('tmp/copy_test_modeDir/time_folder').mode.toString(8).slice(-3), expectedMode);
    test.equal(fs.lstatSync('tmp/copy_test_modeDir/time_folder/sub_folder').mode.toString(8).slice(-3), expectedMode);
    test.done();
  },

  process: function(test) {
    test.expect(2);
    test.equal(fs.lstatSync('tmp/process/beep.wav').size, fs.lstatSync('test/fixtures/beep.wav').size);
    test.notEqual(fs.lstatSync('tmp/process/test2.js').size, fs.lstatSync('test/fixtures/test2.js').size);

    test.done();
  },

  timestampEqual: function(test) {
    if (isWindows) {
      // Known Issue: this test will not pass on Windows due to a bug in node.js
      // https://github.com/nodejs/node/issues/2069
      test.done();
      return;
    }
    test.expect(2);
    test.equal(fs.lstatSync('tmp/copy_test_timestamp/sub_folder').mtime.getTime(), fs.lstatSync('test/fixtures/time_folder/sub_folder').mtime.getTime());
    test.equal(fs.lstatSync('tmp/copy_test_timestamp/test.js').mtime.getTime(), fs.lstatSync('test/fixtures/time_folder/test.js').mtime.getTime());
    test.done();
  },

  timestampChanged: function(test) {
    test.expect(2);
    test.notEqual(fs.lstatSync('tmp/copy_test_timestamp/test1.js').mtime.getTime(), fs.lstatSync('test/fixtures/time_folder/test.js').mtime.getTime());
    test.notEqual(fs.lstatSync('tmp/copy_test_timestamp/test_process.js').mtime.getTime(), fs.lstatSync('test/fixtures/time_folder/test_process.js').mtime.getTime());
    test.done();
  }
};


text:
package com.cra.figaro.test.algorithm

import com.cra.figaro.algorithm._

private object Test {
  def main(args: Array[String]) = {
    (new ValuesTest).execute()
    (new AlgorithmTest).execute()
    //(new ExpandTest).execute()
    (new AbstractionTest).execute()
  }

}


text:
<?php
/**
 * This is the Roo pagecontroller.
 *
 */
// Include the essential config-file which also creates the $roo variable with its defaults.
include(__DIR__.'/config.php');

$db = new CDatabase($roo['database']);
$user= new CUser($db);

// Logout the user
if(isset($_POST['logout'])) {
   $user->logout();
}

$status=$user->statusIsAuthenticated();

// Do it and store it all in variables in the Roo container.
$roo['title'] = "LOGOUT";

$roo['header'] .= 'Log out!';

$roo['main'] = <<<EOD
<form method=post>
  <fieldset>
  <legend>Login</legend>

<input type='submit' name='logout' value='Logout'/>

  <output>{$status}</output>
  </fieldset>
</form>

.: :.

EOD;

$roo['footer'];

// Finally, leave it all to the rendering phase of roo.
include(ROO_THEME_PATH);


text:
"""
This module implements a transaction manager that can be used to define
transaction handling in a request or view function. It is used by transaction
control middleware and decorators.

The transaction manager can be in managed or in auto state. Auto state means the
system is using a commit-on-save strategy (actually it's more like
commit-on-change). As soon as the .save() or .delete() (or related) methods are
called, a commit is made.

Managed transactions don't do those commits, but will need some kind of manual
or implicit commits or rollbacks.
"""

try:
    import thread
except ImportError:
    import dummy_thread as thread
try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps  # Python 2.3, 2.4 fallback.
from django.db import connection
from django.conf import settings

class TransactionManagementError(Exception):
    """
    This exception is thrown when something bad happens with transaction
    management.
    """
    pass

# The states are dictionaries of lists. The key to the dict is the current
# thread and the list is handled as a stack of values.
state = {}
savepoint_state = {}

# The dirty flag is set by *_unless_managed functions to denote that the
# code under transaction management has changed things to require a
# database commit.
dirty = {}

def enter_transaction_management(managed=True):
    """
    Enters transaction management for a running thread. It must be balanced with
    the appropriate leave_transaction_management call, since the actual state is
    managed as a stack.

    The state and dirty flag are carried over from the surrounding block or
    from the settings, if there is no surrounding block (dirty is always false
    when no current block is running).
    """
    thread_ident = thread.get_ident()
    if thread_ident in state and state[thread_ident]:
        state[thread_ident].append(state[thread_ident][-1])
    else:
        state[thread_ident] = []
        state[thread_ident].append(settings.TRANSACTIONS_MANAGED)
    if thread_ident not in dirty:
        dirty[thread_ident] = False
    connection._enter_transaction_management(managed)

def leave_transaction_management():
    """
    Leaves transaction management for a running thread. A dirty flag is carried
    over to the surrounding block, as a commit will commit all changes, even
    those from outside. (Commits are on connection level.)
    """
    connection._leave_transaction_management(is_managed())
    thread_ident = thread.get_ident()
    if thread_ident in state and state[thread_ident]:
        del state[thread_ident][-1]
    else:
        raise TransactionManagementError("This code isn't under transaction management")
    if dirty.get(thread_ident, False):
        rollback()
        raise TransactionManagementError("Transaction managed block ended with pending COMMIT/ROLLBACK")
    dirty[thread_ident] = False

def is_dirty():
    """
    Returns True if the current transaction requires a commit for changes to
    happen.
    """
    return dirty.get(thread.get_ident(), False)

def set_dirty():
    """
    Sets a dirty flag for the current thread and code streak. This can be used
    to decide in a managed block of code to decide whether there are open
    changes waiting for commit.
    """
    thread_ident = thread.get_ident()
    if thread_ident in dirty:
        dirty[thread_ident] = True
    else:
        raise TransactionManagementError("This code isn't under transaction management")

def set_clean():
    """
    Resets a dirty flag for the current thread and code streak. This can be used
    to decide in a managed block of code to decide whether a commit or rollback
    should happen.
    """
    thread_ident = thread.get_ident()
    if thread_ident in dirty:
        dirty[thread_ident] = False
    else:
        raise TransactionManagementError("This code isn't under transaction management")
    clean_savepoints()

def clean_savepoints():
    thread_ident = thread.get_ident()
    if thread_ident in savepoint_state:
        del savepoint_state[thread_ident]

def is_managed():
    """
    Checks whether the transaction manager is in manual or in auto state.
    """
    thread_ident = thread.get_ident()
    if thread_ident in state:
        if state[thread_ident]:
            return state[thread_ident][-1]
    return settings.TRANSACTIONS_MANAGED

def managed(flag=True):
    """
    Puts the transaction manager into a manual state: managed transactions have
    to be committed explicitly by the user. If you switch off transaction
    management and there is a pending commit/rollback, the data will be
    commited.
    """
    thread_ident = thread.get_ident()
    top = state.get(thread_ident, None)
    if top:
        top[-1] = flag
        if not flag and is_dirty():
            connection._commit()
            set_clean()
    else:
        raise TransactionManagementError("This code isn't under transaction management")

def commit_unless_managed():
    """
    Commits changes if the system is not in managed transaction mode.
    """
    if not is_managed():
        connection._commit()
        clean_savepoints()
    else:
        set_dirty()

def rollback_unless_managed():
    """
    Rolls back changes if the system is not in managed transaction mode.
    """
    if not is_managed():
        connection._rollback()
    else:
        set_dirty()

def commit():
    """
    Does the commit itself and resets the dirty flag.
    """
    connection._commit()
    set_clean()

def rollback():
    """
    This function does the rollback itself and resets the dirty flag.
    """
    connection._rollback()
    set_clean()

def savepoint():
    """
    Creates a savepoint (if supported and required by the backend) inside the
    current transaction. Returns an identifier for the savepoint that will be
    used for the subsequent rollback or commit.
    """
    thread_ident = thread.get_ident()
    if thread_ident in savepoint_state:
        savepoint_state[thread_ident].append(None)
    else:
        savepoint_state[thread_ident] = [None]
    tid = str(thread_ident).replace('-', '')
    sid = "s%s_x%d" % (tid, len(savepoint_state[thread_ident]))
    connection._savepoint(sid)
    return sid

def savepoint_rollback(sid):
    """
    Rolls back the most recent savepoint (if one exists). Does nothing if
    savepoints are not supported.
    """
    if thread.get_ident() in savepoint_state:
        connection._savepoint_rollback(sid)

def savepoint_commit(sid):
    """
    Commits the most recent savepoint (if one exists). Does nothing if
    savepoints are not supported.
    """
    if thread.get_ident() in savepoint_state:
        connection._savepoint_commit(sid)

##############
# DECORATORS #
##############

def autocommit(func):
    """
    Decorator that activates commit on save. This is Django's default behavior;
    this decorator is useful if you globally activated transaction management in
    your settings file and want the default behavior in some view functions.
    """
    def _autocommit(*args, **kw):
        try:
            enter_transaction_management(managed=False)
            managed(False)
            return func(*args, **kw)
        finally:
            leave_transaction_management()
    return wraps(func)(_autocommit)

def commit_on_success(func):
    """
    This decorator activates commit on response. This way, if the view function
    runs successfully, a commit is made; if the viewfunc produces an exception,
    a rollback is made. This is one of the most common ways to do transaction
    control in web apps.
    """
    def _commit_on_success(*args, **kw):
        try:
            enter_transaction_management()
            managed(True)
            try:
                res = func(*args, **kw)
            except:
                # All exceptions must be handled here (even string ones).
                if is_dirty():
                    rollback()
                raise
            else:
                if is_dirty():
                    commit()
            return res
        finally:
            leave_transaction_management()
    return wraps(func)(_commit_on_success)

def commit_manually(func):
    """
    Decorator that activates manual transaction control. It just disables
    automatic transaction control and doesn't do any commit/rollback of its
    own -- it's up to the user to call the commit and rollback functions
    themselves.
    """
    def _commit_manually(*args, **kw):
        try:
            enter_transaction_management()
            managed(True)
            return func(*args, **kw)
        finally:
            leave_transaction_management()

    return wraps(func)(_commit_manually)


text:
/*
	Leaflet.label, a plugin that adds labels to markers and vectors for Leaflet powered maps.
	(c) 2012-2013, Jacob Toye, Smartrak

	https://github.com/Leaflet/Leaflet.label
	http://leafletjs.com
	https://github.com/jacobtoye
*/
(function (window, document, undefined) {
/*
 * Leaflet.label assumes that you have already included the Leaflet library.
 */

L.labelVersion = '0.1.4-dev';

L.Label = L.Popup.extend({

	includes: L.Mixin.Events,

	options: {
		autoPan: false,
		className: '',
		clickable: false,
		closePopupOnClick: false,
		noHide: false,
		offset: new L.Point(12, -15), // 6 (width of the label triangle) + 6 (padding)
		opacity: 1
	},

	onAdd: function (map) {
		this._map = map;

		this._pane = this._source instanceof L.Marker ? map._panes.markerPane : map._panes.popupPane;

		if (!this._container) {
			this._initLayout();
		}
		this._updateContent();

		var animFade = map.options.fadeAnimation;

		if (animFade) {
			L.DomUtil.setOpacity(this._container, 0);
		}
		this._pane.appendChild(this._container);

		map.on('viewreset', this._updatePosition, this);

		if (this._animated) {
			map.on('zoomanim', this._zoomAnimation, this);
		}

		if (L.Browser.touch && !this.options.noHide) {
			L.DomEvent.on(this._container, 'click', this.close, this);
		}

		this._initInteraction();

		this._update();

		this.setOpacity(this.options.opacity);
	},

	onRemove: function (map) {
		this._pane.removeChild(this._container);

		L.Util.falseFn(this._container.offsetWidth); // force reflow

		map.off({
			viewreset: this._updatePosition,
			zoomanim: this._zoomAnimation
		}, this);

		if (map.options.fadeAnimation) {
			L.DomUtil.setOpacity(this._container, 0);
		}

		this._removeInteraction();

		this._map = null;
	},

	close: function () {
		var map = this._map;

		if (map) {
			if (L.Browser.touch && !this.options.noHide) {
				L.DomEvent.off(this._container, 'click', this.close);
			}

			map._label = null;

			map.removeLayer(this);
		}
	},

	updateZIndex: function (zIndex) {
		this._zIndex = zIndex;

		if (this._container && this._zIndex) {
			this._container.style.zIndex = zIndex;
		}
	},

	setOpacity: function (opacity) {
		this.options.opacity = opacity;

		if (this._container) {
			L.DomUtil.setOpacity(this._container, opacity);
		}
	},

	_initLayout: function () {
		this._container = L.DomUtil.create('div', 'leaflet-label ' + this.options.className + ' leaflet-zoom-animated');
		this.updateZIndex(this._zIndex);
	},

	_updateContent: function () {
		if (!this._content) { return; }

		if (typeof this._content === 'string') {
			this._container.innerHTML = this._content;
		}
	},

	_updateLayout: function () {
		// Do nothing
	},

	_updatePosition: function () {
		var pos = this._map.latLngToLayerPoint(this._latlng);

		this._setPosition(pos);
	},

	_setPosition: function (pos) {
		pos = pos.add(this.options.offset);

		L.DomUtil.setPosition(this._container, pos);
	},

	_zoomAnimation: function (opt) {
		var pos = this._map._latLngToNewLayerPoint(this._latlng, opt.zoom, opt.center);

		this._setPosition(pos);
	},

	_initInteraction: function () {
		if (!this.options.clickable) { return; }

		var container = this._container,
			events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];

		L.DomUtil.addClass(container, 'leaflet-clickable');
		L.DomEvent.on(container, 'click', this._onMouseClick, this);

		for (var i = 0; i < events.length; i++) {
			L.DomEvent.on(container, events[i], this._fireMouseEvent, this);
		}
	},

	_removeInteraction: function () {
		if (!this.options.clickable) { return; }

		var container = this._container,
			events = ['dblclick', 'mousedown', 'mouseover', 'mouseout', 'contextmenu'];

		L.DomUtil.removeClass(container, 'leaflet-clickable');
		L.DomEvent.off(container, 'click', this._onMouseClick, this);

		for (var i = 0; i < events.length; i++) {
			L.DomEvent.off(container, events[i], this._fireMouseEvent, this);
		}
	},

	_onMouseClick: function (e) {
		if (this.hasEventListeners(e.type)) {
			L.DomEvent.stopPropagation(e);
		}

		this.fire(e.type, {
			originalEvent: e
		});
	},

	_fireMouseEvent: function (e) {
		this.fire(e.type, {
			originalEvent: e
		});

		// TODO proper custom event propagation
		// this line will always be called if marker is in a FeatureGroup
		if (e.type === 'contextmenu' && this.hasEventListeners(e.type)) {
			L.DomEvent.preventDefault(e);
		}
		if (e.type !== 'mousedown') {
			L.DomEvent.stopPropagation(e);
		} else {
			L.DomEvent.preventDefault(e);
		}
	}
});

// Add in an option to icon that is used to set where the label anchor is
L.Icon.Default.mergeOptions({
	labelAnchor: new L.Point(9, -20)
});

// Have to do this since Leaflet is loaded before this plugin and initializes
// L.Marker.options.icon therefore missing our mixin above.
L.Marker.mergeOptions({
	icon: new L.Icon.Default()
});

L.Marker.include({
	showLabel: function () {
		if (this._label && this._map) {
			this._label.setLatLng(this._latlng);
			this._map.showLabel(this._label);
		}

		return this;
	},

	hideLabel: function () {
		if (this._label) {
			this._label.close();
		}
		return this;
	},

	setLabelNoHide: function (noHide) {
		if (this._labelNoHide === noHide) {
			return;
		}

		this._labelNoHide = noHide;

		if (noHide) {
			this._removeLabelRevealHandlers();
			this.showLabel();
		} else {
			this._addLabelRevealHandlers();
			this.hideLabel();
		}
	},

	bindLabel: function (content, options) {
		var anchor = L.point(this.options.icon.options.labelAnchor) || new L.Point(0, 0);

		anchor = anchor.add(L.Label.prototype.options.offset);

		if (options && options.offset) {
			anchor = anchor.add(options.offset);
		}

		options = L.Util.extend({offset: anchor}, options);

		this._labelNoHide = options.noHide;

		if (!this._label) {
			if (!this._labelNoHide) {
				this._addLabelRevealHandlers();
			}

			this
				.on('remove', this.hideLabel, this)
				.on('move', this._moveLabel, this);

			this._hasLabelHandlers = true;
		}

		this._label = new L.Label(options, this)
			.setContent(content);

		return this;
	},

	unbindLabel: function () {
		if (this._label) {
			this.hideLabel();

			this._label = null;

			if (this._hasLabelHandlers) {
				if (!this._labelNoHide) {
					this._removeLabelRevealHandlers();
				}

				this
					.off('remove', this.hideLabel, this)
					.off('move', this._moveLabel, this);
			}

			this._hasLabelHandlers = false;
		}
		return this;
	},

	updateLabelContent: function (content) {
		if (this._label) {
			this._label.setContent(content);
		}
	},

	getLabel: function () {
		return this._label;
	},

	_addLabelRevealHandlers: function () {
		this
			.on('mouseover', this.showLabel, this)
			.on('mouseout', this.hideLabel, this);

		if (L.Browser.touch) {
			this.on('click', this.showLabel, this);
		}
	},

	_removeLabelRevealHandlers: function () {
		this
			.off('mouseover', this.showLabel, this)
			.off('mouseout', this.hideLabel, this);

		if (L.Browser.touch) {
			this.off('click', this.showLabel, this);
		}
	},

	_moveLabel: function (e) {
		this._label.setLatLng(e.latlng);
	},

	_originalUpdateZIndex: L.Marker.prototype._updateZIndex,

	_updateZIndex: function (offset) {
		var zIndex = this._zIndex + offset;

		this._originalUpdateZIndex(offset);

		if (this._label) {
			this._label.updateZIndex(zIndex);
		}
	},

	_originalSetOpacity: L.Marker.prototype.setOpacity,

	setOpacity: function (opacity, labelHasSemiTransparency) {
		this.options.labelHasSemiTransparency = labelHasSemiTransparency;

		this._originalSetOpacity(opacity);
	},

	_originalUpdateOpacity: L.Marker.prototype._updateOpacity,

	_updateOpacity: function () {
		var absoluteOpacity = this.options.opacity === 0 ? 0 : 1;

		this._originalUpdateOpacity();

		if (this._label) {
			this._label.setOpacity(this.options.labelHasSemiTransparency ? this.options.opacity : absoluteOpacity);
		}
	}
});

L.Path.include({
	bindLabel: function (content, options) {
		if (!this._label || this._label.options !== options) {
			this._label = new L.Label(options, this);
		}

		this._label.setContent(content);

		if (!this._showLabelAdded) {
			this
				.on('mouseover', this._showLabel, this)
				.on('mousemove', this._moveLabel, this)
				.on('mouseout remove', this._hideLabel, this);

			if (L.Browser.touch) {
				this.on('click', this._showLabel, this);
			}
			this._showLabelAdded = true;
		}

		return this;
	},

	unbindLabel: function () {
		if (this._label) {
			this._hideLabel();
			this._label = null;
			this._showLabelAdded = false;
			this
				.off('mouseover', this._showLabel, this)
				.off('mousemove', this._moveLabel, this)
				.off('mouseout remove', this._hideLabel, this);
		}
		return this;
	},

	updateLabelContent: function (content) {
		if (this._label) {
			this._label.setContent(content);
		}
	},

	_showLabel: function (e) {
		this._label.setLatLng(e.latlng);
		this._map.showLabel(this._label);
	},

	_moveLabel: function (e) {
		this._label.setLatLng(e.latlng);
	},

	_hideLabel: function () {
		this._label.close();
	}
});

L.Map.include({
	showLabel: function (label) {
		this._label = label;

		return this.addLayer(label);
	}
});

L.FeatureGroup.include({
	// TODO: remove this when AOP is supported in Leaflet, need this as we cannot put code in removeLayer()
	clearLayers: function () {
		this.unbindLabel();
		this.eachLayer(this.removeLayer, this);
		return this;
	},

	bindLabel: function (content, options) {
		return this.invoke('bindLabel', content, options);
	},

	unbindLabel: function () {
		return this.invoke('unbindLabel');
	},

	updateLabelContent: function (content) {
		this.invoke('updateLabelContent', content);
	}
});

}(this, document));


text:
require 'opal/nodes/base'

module Opal
  module Nodes
    module Args
      # This node is responsible for extracting a single
      # splat keyword argument from $kwargs
      #
      # $kwargs always exist (as argument when inlining is possible
      # and as a local variable when it's not)
      #
      class ExtractKwrestarg < Base
        handle :extract_kwrestarg
        children :name

        def compile
          # def m(**)
          # arguments are assigned to `$kw_rest_arg` for super call
          name = self.name || '$kw_rest_arg'

          add_temp name
          line "#{name} = Opal.kwrestargs($kwargs, #{used_kwargs});"
        end

        def used_kwargs
          args = scope.used_kwargs.map do |arg_name|
            "'#{arg_name}': true"
          end

          "{#{args.join ','}}"
        end
      end
    end
  end
end


text:
using System;
using Gallio.Common.Markup;
using Gallio.Model.Schema;
using Gallio.Runner.Reports.Schema;

namespace Gallio.Runner.Events
{
    /// <summary>
    /// Arguments for an event raised to indicate that a marker block has been started within a test step log stream.
    /// </summary>
    public sealed class TestStepLogStreamBeginMarkerBlockEventArgs : TestStepLogStreamEventArgs
    {
        private readonly Marker marker;

        /// <summary>
        /// Initializes the event arguments.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="test">The test data.</param>
        /// <param name="testStepRun">The test step run.</param>
        /// <param name="logStreamName">The log stream name.</param>
        /// <param name="marker">The marker.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="report"/>, <paramref name="test"/>
        /// <paramref name="testStepRun"/> or <paramref name="logStreamName"/> is null.</exception>
        public TestStepLogStreamBeginMarkerBlockEventArgs(Report report, TestData test, TestStepRun testStepRun, string logStreamName, Marker marker)
            : base(report, test, testStepRun, logStreamName)
        {
            this.marker = marker;
        }

        /// <summary>
        /// Gets the marker.
        /// </summary>
        public Marker Marker
        {
            get { return marker; }
        }
    }
}


text:
package org.estatio.module.lease.subscriptions;

import java.util.List;

import javax.inject.Inject;

import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.services.i18n.TranslatableString;

import org.incode.module.communications.dom.impl.commchannel.CommunicationChannel;
import org.incode.module.communications.dom.impl.comms.Communication;
import org.incode.module.document.dom.impl.docs.Document;
import org.incode.module.document.dom.impl.docs.Document_delete;
import org.incode.module.document.dom.impl.paperclips.Paperclip;
import org.incode.module.document.dom.impl.paperclips.PaperclipRepository;

import org.estatio.module.base.dom.UdoDomainRepositoryAndFactory;

@DomainService(
        nature = NatureOfService.DOMAIN,
        objectType = "estatio.VetoDocumentDeleteIfSent"
)
public class VetoDocumentDeleteIfSent extends UdoDomainRepositoryAndFactory<CommunicationChannel> {

    public String getId() {
        return "estatio.VetoDocumentDeleteIfSent";
    }

    public VetoDocumentDeleteIfSent() {
        super(VetoDocumentDeleteIfSent.class, CommunicationChannel.class);
    }

    @Programmatic
    @com.google.common.eventbus.Subscribe
    @org.axonframework.eventhandling.annotation.EventHandler
    public void on(final Document_delete.ActionDomainEvent ev) {
        final Document document = (Document) ev.getMixedIn();
        switch (ev.getEventPhase()) {
        case DISABLE:
            final List<Paperclip> attachments = paperclipRepository.findByDocument(document);
            for (Paperclip attachment : attachments) {
                if(attachment.getAttachedTo() instanceof Communication) {
                    ev.veto(TranslatableString.tr("Document has already been sent as a communication"));
                }
            }
        }
    }

    @Inject
    PaperclipRepository paperclipRepository;

}


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { AuthenticationService } from '../_services/authentication.services';

@Component({
  moduleId: module.id,
  templateUrl: 'login.component.html'
})

export class LoginComponent implements OnInit {
  model: any = {};
  loading = false;
  error = '';

  constructor(
    private router: Router,
    private authenticationService: AuthenticationService) { }

  ngOnInit() {
    // reset login status
    this.authenticationService.logout();
  }

  login() {
    this.loading = true;
    this.authenticationService.login(this.model.email, this.model.password)
      .subscribe(result => {
        if (result === true) {
          this.router.navigate(['/']);
        } else {
          this.error = 'Nombre de usuario o password incorrecta';
          this.loading = false;
        }
      });
  }
}


text:
namespace chromeos {

namespace {

constexpr int kPrintExpectationDelayMs = 3000;

}  // namespace

SpeechMonitor::SpeechMonitor() {
  content::TtsController::GetInstance()->SetTtsPlatform(this);
}

SpeechMonitor::~SpeechMonitor() {
  content::TtsController::GetInstance()->SetTtsPlatform(
      content::TtsPlatform::GetInstance());
  if (!replay_queue_.empty() || !replayed_queue_.empty())
    CHECK(replay_called_) << "Expectation was made, but Replay() not called.";
}

bool SpeechMonitor::PlatformImplAvailable() {
  return true;
}

void SpeechMonitor::Speak(int utterance_id,
                          const std::string& utterance,
                          const std::string& lang,
                          const content::VoiceData& voice,
                          const content::UtteranceContinuousParameters& params,
                          base::OnceCallback<void(bool)> on_speak_finished) {
  content::TtsController::GetInstance()->OnTtsEvent(
      utterance_id, content::TTS_EVENT_END, static_cast<int>(utterance.size()),
      0, std::string());
  std::move(on_speak_finished).Run(true);
  time_of_last_utterance_ = std::chrono::steady_clock::now();
}

bool SpeechMonitor::StopSpeaking() {
  return true;
}

bool SpeechMonitor::IsSpeaking() {
  return false;
}

void SpeechMonitor::GetVoices(std::vector<content::VoiceData>* out_voices) {
  out_voices->push_back(content::VoiceData());
  content::VoiceData& voice = out_voices->back();
  voice.native = true;
  voice.name = "SpeechMonitor";
  voice.engine_id = extension_misc::kGoogleSpeechSynthesisExtensionId;
  voice.events.insert(content::TTS_EVENT_END);
}

void SpeechMonitor::WillSpeakUtteranceWithVoice(
    content::TtsUtterance* utterance,
    const content::VoiceData& voice_data) {
  utterance_queue_.emplace_back(utterance->GetText(), utterance->GetLang());
  delay_for_last_utterance_ms_ = CalculateUtteranceDelayMS();
  MaybeContinueReplay();
}

bool SpeechMonitor::LoadBuiltInTtsEngine(
    content::BrowserContext* browser_context) {
  return false;
}

std::string SpeechMonitor::GetError() {
  return error_;
}

void SpeechMonitor::ClearError() {
  error_ = std::string();
}

void SpeechMonitor::SetError(const std::string& error) {
  error_ = error;
}

double SpeechMonitor::CalculateUtteranceDelayMS() {
  std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
  std::chrono::duration<double> time_span =
      std::chrono::duration_cast<std::chrono::duration<double>>(
          now - time_of_last_utterance_);
  return time_span.count() * 1000;
}

double SpeechMonitor::GetDelayForLastUtteranceMS() {
  return delay_for_last_utterance_ms_;
}

void SpeechMonitor::ExpectSpeech(const std::string& text,
                                 const base::Location& location) {
  CHECK(!replay_loop_runner_.get());
  replay_queue_.push_back({[this, text]() {
                             for (auto it = utterance_queue_.begin();
                                  it != utterance_queue_.end(); it++) {
                               if (it->text == text) {
                                 // Erase all utterances that came before the
                                 // match as well as the match itself.
                                 utterance_queue_.erase(
                                     utterance_queue_.begin(), it + 1);
                                 return true;
                               }
                             }
                             return false;
                           },
                           "ExpectSpeech(\"" + text + "\") " +
                               location.ToString()});
}

void SpeechMonitor::ExpectSpeechPattern(const std::string& pattern,
                                        const base::Location& location) {
  ExpectSpeechPatternWithLocale(pattern, "", location);
}

void SpeechMonitor::ExpectSpeechPatternWithLocale(
    const std::string& pattern,
    const std::string& locale,
    const base::Location& location) {
  CHECK(!replay_loop_runner_.get());
  replay_queue_.push_back({[this, pattern, locale]() {
                             for (auto it = utterance_queue_.begin();
                                  it != utterance_queue_.end(); it++) {
                               if (base::MatchPattern(it->text, pattern) &&
                                   (locale.empty() || it->lang == locale)) {
                                 // Erase all utterances that came before the
                                 // match as well as the match itself.
                                 utterance_queue_.erase(
                                     utterance_queue_.begin(), it + 1);
                                 return true;
                               }
                             }
                             return false;
                           },
                           "ExpectSpeechPattern(\"" + pattern + "\") " +
                               location.ToString()});
}

void SpeechMonitor::ExpectNextSpeechIsNot(const std::string& text,
                                          const base::Location& location) {
  CHECK(!replay_loop_runner_.get());
  replay_queue_.push_back(
      {[this, text]() {
         if (utterance_queue_.empty())
           return false;

         return text != utterance_queue_.front().text;
       },
       "ExpectNextSpeechIsNot(\"" + text + "\") " + location.ToString()});
}

void SpeechMonitor::ExpectNextSpeechIsNotPattern(
    const std::string& pattern,
    const base::Location& location) {
  CHECK(!replay_loop_runner_.get());
  replay_queue_.push_back({[this, pattern]() {
                             if (utterance_queue_.empty())
                               return false;

                             return !base::MatchPattern(
                                 utterance_queue_.front().text, pattern);
                           },
                           "ExpectNextSpeechIsNotPattern(\"" + pattern +
                               "\") " + location.ToString()});
}

void SpeechMonitor::Call(std::function<void()> func,
                         const base::Location& location) {
  CHECK(!replay_loop_runner_.get());
  replay_queue_.push_back({[func]() {
                             func();
                             return true;
                           },
                           "Call() " + location.ToString()});
}

void SpeechMonitor::Replay() {
  replay_called_ = true;
  MaybeContinueReplay();
}

void SpeechMonitor::MaybeContinueReplay() {
  // This method can be called prior to Replay() being called.
  if (!replay_called_)
    return;

  auto it = replay_queue_.begin();
  while (it != replay_queue_.end()) {
    if (it->first()) {
      // Careful here; the above callback may have triggered more speech which
      // causes |MaybeContinueReplay| to be called recursively. We have to
      // ensure to check |replay_queue_| here.
      if (replay_queue_.empty())
        break;

      replayed_queue_.push_back(it->second);
      it = replay_queue_.erase(it);
    } else {
      break;
    }
  }

  if (!replay_queue_.empty()) {
    base::PostDelayedTask(
        FROM_HERE, {content::BrowserThread::UI},
        base::BindOnce(&SpeechMonitor::MaybePrintExpectations,
                       weak_factory_.GetWeakPtr()),
        base::TimeDelta::FromMilliseconds(kPrintExpectationDelayMs));

    if (!replay_loop_runner_.get()) {
      replay_loop_runner_ = new content::MessageLoopRunner();
      replay_loop_runner_->Run();
    }
  } else if (replay_queue_.empty() && replay_loop_runner_.get()) {
    replay_loop_runner_->Quit();
  }
}

void SpeechMonitor::MaybePrintExpectations() {
  if (CalculateUtteranceDelayMS() < kPrintExpectationDelayMs ||
      replay_queue_.empty())
    return;

  if (last_replay_queue_size_ == replay_queue_.size())
    return;

  last_replay_queue_size_ = replay_queue_.size();
  std::vector<std::string> replay_queue_descriptions;
  for (const auto& pair : replay_queue_)
    replay_queue_descriptions.push_back(pair.second);

  std::vector<std::string> utterance_queue_descriptions;
  for (const auto& item : utterance_queue_)
    utterance_queue_descriptions.push_back("\"" + item.text + "\"");

  LOG(ERROR) << "Still waiting for expectation(s).\n"
             << "Unsatisfied expectations...\n"
             << base::JoinString(replay_queue_descriptions, "\n") << "\n\n"
             << "pending speech utterances...\n"
             << base::JoinString(utterance_queue_descriptions, "\n") << "\n\n"
             << "Satisfied expectations...\n"
             << base::JoinString(replayed_queue_, "\n");
}

}  // namespace chromeos


text:
@interface DismissModalTransitionAnimator : NSObject <UIViewControllerAnimatedTransitioning>

@end


text:
'use strict';

const BearerStrategy = require('passport-http-bearer').Strategy;

class CookieTokenStrategy extends BearerStrategy {
  constructor(options, verify) {
    if (typeof options === 'function') {
      verify = options;
      options = {};
    }
    if (!verify) {
      throw new TypeError('CookieTokenStrategy requires a verify callback');
    }
    super(options, verify);
    const self = this;

    self.name = 'cookie-token';
    self._cookieName = options.cookieName || 'bearerToken';
  }

  authenticate(req) {
    const self = this;
    if (req.cookies && req.cookies[self._cookieName]) {
      let token = req.cookies[self._cookieName];

      req.headers = req.headers || {};
      req.headers.authorization = `Bearer ${token}`;
    }

    return super.authenticate(req);
  }
}

module.exports = CookieTokenStrategy;


text:
	<button class="btn btn-primary"
		ng-if="auth.isRole('ROLE_ADMIN')"
		ng-click="showStreamEditor()"
	>+ New Stream</button>

	Loading...

{{stream.tags.streamName}}

			<button class="btn btn-box-tool" data-widget="collapse">

			</button>
			<button class="btn btn-box-tool" ng-click="showStreamEditor(stream)" ng-if="auth.isRole('ROLE_ADMIN')">

			</button>

					Data Source

					{{stream.tags.dataSource}}

					Stream Name

					{{stream.tags.streamName}}

					Description

					{{stream.desc}}

			Loading...

						Attribute Name
						Display Name
						Type
						Description

						{{meta.tags.attrName}}
						{{meta.attrDisplayName}}
						{{meta.attrType}}
						{{meta.attrDescription}}

				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					×
				</button>

{{!_streamEntity.srcStream ? 'Create' : 'Config'}} Stream

					* Data Source
					<input type="text" class="form-control" placeholder="Data source..." ng-model="_streamEntity.dataSource"
							ng-class="{'has-warning': !_streamEntity.dataSource}" ng-disabled="!!_streamEntity.srcStream" id="dataSource">

					* Stream Name
					<input type="text" class="form-control" placeholder="Stream name..." ng-model="_streamEntity.streamName"
							ng-class="{'has-warning': !_streamEntity.streamName}" ng-disabled="!!_streamEntity.srcStream">

					Description
					<textarea class="form-control" placeholder="Description..." ng-model="_streamEntity.desc"></textarea>

					* Data Source Schema

							Attribute Name
							Display Name
							Type
							Description

							<input type="text" class="form-control" ng-class="{'has-warning': !meta.attrName}" ng-model="meta.attrName" />
							<input type="text" class="form-control" ng-model="meta.attrDisplayName" />

								<select class="form-control" ng-model="meta.attrType">
									<option ng-repeat="type in ['string','bool','long','integer','double','float']">{{type}}</option>
								</select>

							<input type="text" class="form-control" ng-model="meta.attrDescription" />

				+ Add Schema Item

				<button type="button" class="btn btn-danger pull-left" ng-show="_streamEntity.srcStream" ng-click="confirmDeleteStream()" ng-disabled="!checkUpdateStream()">
					Delete
				</button>

				<button type="button" class="btn btn-default" data-dismiss="modal">
					Close
				</button>
				<button type="button" class="btn btn-primary" ng-click="confirmUpateStream()" ng-disabled="!checkUpdateStream()">
					{{!_streamEntity.srcStream ? 'Create' : 'Update'}}
				</button>


text:
require 'mongoid'
require_relative 'image_processor'

class Card
  include Mongoid::Document
  include Mongoid::Timestamps
  include ImageProcessor

  field :text, type: String

  # for image
  embeds_one :descriptor

  belongs_to :deck
  belongs_to :user
  belongs_to :chain

  belongs_to :creator, class_name: 'User', inverse_of: :created_cards

  def initialize(attrs={}, upload=nil, root_path=nil, options={})
    attrs['descriptor'] = persist(upload, root_path)

    super attrs

    small!
  end

  def persisted?
    !self.read_attribute('descriptor').nil?
  end

  def file_dir(root_path)
    @file_dir ||= File.join root_path, 'public', 'uploads', 'cards', Time.now.strftime('%Y%m%d'), 'original'
  end

  def file_path(dir, name)
    @file_path ||= File.join dir, name
  end

  #   def file_path_p(original)
  #     return if original.nil?
  #
  #     parts = original.split('/').map do |segment|
  #       if segment == 'original'
  #         'processed'
  #       else
  #         segment
  #       end
  #     end
  #
  #     dir = File.join parts[0...-1]
  #     FileUtils.mkdir_p dir unless File.directory? dir
  #
  #     File.join parts
  #   end

  def persist(ups, root_path)
    return if ups.nil?

    # try to guess where we are if someone is dumb
    if root_path.nil?
      Dir.chdir '..'
      root_path = Dir.pwd
    end

    # raise InvalidFileType, 'Requires mp3 file!' unless ups && ups.audio?

    file = ups.tempfile
    dir  = file_dir(root_path)
    path = file_path(dir, ups.filename)

    FileUtils.mkdir_p dir unless File.directory? dir

    written = File.open(path, 'wb') { |f| f.write file.read }

    if written > 0
      {
        file_name:      ups.filename,
        file_type:      ups.filetype,
        file_cat:       ups.filecat,
        file_ext:       ups.fileext,
        file_path:      path,
        file_path_orig: path
      }
    else
      raise FileNotWritten, 'Something horrible happened!'
    end
  end
end


text:
Stars - A simple and powerful web service framework for python
===


text:
'''Sample script showing off array basic operations'''

from __future__ import absolute_import, division, print_function
from random import randint

import blaze

def make_test_array(datashape):
    return blaze.ones(datashape) * randint(1, 10)

def test_operations(datashape):
    a = make_test_array(datashape)
    b = make_test_array(datashape)
    print('a:\n', a)
    print('b:\n', b)
    print('a + b:\n', a + b)
    print('a - b:\n', a - b)
    print('a * b:\n', a * b)
    print('a / b:\n', a / b)
    print('blaze.max(a):\n', blaze.max(a))
    print('blaze.min(a):\n', blaze.min(a))
    print('blaze.product(a):\n', blaze.product(a))
    print('blaze.sum(a):\n', blaze.sum(a))

if __name__ == '__main__':
    test_operations('10 * float32')
    test_operations('10 * int32')
    test_operations('10 * 10 * float64')


text:
from flask import render_template

import pajbot.web.utils
from pajbot.utils import find

def init(app):
    def get_commands_list():
        return pajbot.web.utils.get_cached_commands()

    @app.route("/commands")
    def commands():
        custom_commands = []
        point_commands = []
        moderator_commands = []

        bot_commands_list = get_commands_list()

        for command in bot_commands_list:
            if command["level"] > 100 or command["mod_only"]:
                moderator_commands.append(command)
            elif command["cost"] > 0:
                point_commands.append(command)
            else:
                custom_commands.append(command)

        return render_template(
            "commands.html",
            custom_commands=sorted(custom_commands, key=lambda f: f["aliases"]),
            point_commands=sorted(point_commands, key=lambda a: (a["cost"], a["aliases"])),
            moderator_commands=sorted(
                moderator_commands, key=lambda c: (c["level"] if c["mod_only"] is False else 500, c["aliases"])
            ),
        )

    @app.route("/commands/<raw_command_string>")
    def command_detailed(raw_command_string):
        command_string_parts = raw_command_string.split("-")
        command_string = command_string_parts[0]
        command_id = None
        try:
            command_id = int(command_string)
        except ValueError:
            pass

        bot_commands_list = get_commands_list()

        if command_id is not None:
            command = find(lambda c: c["id"] == command_id, bot_commands_list)
        else:
            command = find(lambda c: c["resolve_string"] == command_string, bot_commands_list)

        if command is None:
            # XXX: Is it proper to have it return a 404 code as well?
            return render_template("command_404.html")

        examples = command["examples"]

        return render_template("command_detailed.html", command=command, examples=examples)


text:
package org.rspspin.tests;

import static org.junit.Assert.*;

import org.apache.jena.query.Query;
import org.apache.jena.query.QueryFactory;
import org.junit.Test;
import org.rspspin.lang.rspql.ParserRSPQL;

public class TestParserAndSerializer {

	/* Output stream name as a variable */
	@Test
	public void registerAs1() {
		ParserRSPQL.register();
		String query = "" + "REGISTER STREAM ?out AS SELECT * WHERE { ?a ?b ?c }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Output stream name as a URI */
	@Test
	public void registerAs2() {
		ParserRSPQL.register();
		String query = "" + "REGISTER STREAM <http://example/stream> AS SELECT * WHERE { ?a  ?b  ?c }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window stream name as a variable */
	@Test
	public void physicalWindow1() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON ?stream [ITEM 10 STEP 10] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);

		assertEquals(compress(q.toString()), compress(query));
	}

	/* Input stream as a URL */
	@Test
	public void physicalWindow2() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [ITEM 10 STEP 10] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);

		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window range and step as variables */
	@Test
	public void physicalWindow3() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [ITEM ?range STEP ?step] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Only window range */
	@Test
	public void physicalWindow4() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [ITEM 10] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window stream name as a variable */
	@Test
	public void logicalWindow1() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON ?stream [RANGE PT1H STEP PT1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Input stream as a URL */
	@Test
	public void logicalWindow2() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [RANGE PT1H STEP PT1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window range and step as variables */
	@Test
	public void logicalWindow3() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [RANGE ?range STEP ?step] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);

		assertEquals(compress(q.toString()), compress(query));
	}

	/* Only window range */
	@Test
	public void logicalWindow4() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [RANGE PT1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window stream name as a variable */
	@Test
	public void logicalPastWindow1() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON ?stream [FROM NOW-PT2H TO NOW-PT1H STEP PT1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Input stream as a URL */
	@Test
	public void logicalPastWindow2() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [FROM NOW-PT2H TO NOW-PT1H STEP PT1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window from, to and step as variables */
	@Test
	public void logicalPastWindow3() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [FROM NOW-?from TO NOW-?to STEP ?step] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Window no step */
	@Test
	public void logicalPastWindow4() {
		ParserRSPQL.register();
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [FROM NOW-PT2H TO NOW-PT1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		Query q = QueryFactory.create(query, ParserRSPQL.syntax);
		assertEquals(compress(q.toString()), compress(query));
	}

	/* Test illegal duration format */
	@Test
	public void illegalDuration() {
		ParserRSPQL.register();
		Query q = null;
		String query = ""
				+ "REGISTER STREAM ?out AS "
				+ "SELECT * "
				+ "FROM NAMED WINDOW <http://window> ON <http://stream> [RANGE PT1M1H] "
				+ "WHERE { WINDOW <http://window> { ?a ?b ?c } }";
		try {
			q = QueryFactory.create(query, ParserRSPQL.syntax);
		} catch (Exception e) {}
		assertEquals(q, null);
	}

	public String compress(String s) {
		return s.replaceAll("\\s+", " ").trim();
	}
}


text:
'use strict';

module.exports = function (app) {
  class Bar2 extends app.Service {

  }

  return Bar2;
};


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';

const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;

export default class Icon extends Component {
  render () {
    const { className, colorIndex } = this.props;
    let { a11yTitle, size, responsive } = this.props;
    let { intl } = this.context;

    const classes = classnames(
      CLASS_ROOT,
      `${CLASS_ROOT}-document-time`,
      className,
      {
        [`${CLASS_ROOT}--${size}`]: size,
        [`${CLASS_ROOT}--responsive`]: responsive,
        [`${COLOR_INDEX}-${colorIndex}`]: colorIndex
      }
    );

    a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-time');

    const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
    return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L17,23 M18,1 L18,6 L23,6 M10,23 C13.8659932,23 17,19.8659932 17,16 C17,12.1340068 13.8659932,9 10,9 C6.13400675,9 3,12.1340068 3,16 C3,19.8659932 6.13400675,23 10,23 Z M10,12 L10,16 L13,19"/></svg>;
  }
};

Icon.contextTypes = {
  intl: PropTypes.object
};

Icon.defaultProps = {
  responsive: true
};

Icon.displayName = 'DocumentTime';

Icon.icon = true;

Icon.propTypes = {
  a11yTitle: PropTypes.string,
  colorIndex: PropTypes.string,
  size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
  responsive: PropTypes.bool
};