text:
<?xml version="1.0" encoding="UTF-8"?>

<objects xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
         xmlns:t="http://prism.evolveum.com/xml/ns/public/types-3"
         xmlns:xsd="http://www.w3.org/2001/XMLSchema"
         xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"
         xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
         xmlns:icfc="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/connector-schema-3"
         xmlns:my="http://whatever.com/my"
         xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3"
         xmlns:mr="http://prism.evolveum.com/xml/ns/public/matching-rule-3">

    <resource oid="ef2bc95b-76e0-48e2-86d6-3d4f02d3e1a2">

        <name>Localhost OpenDJ</name>

        <description>
            LDAP resource using an Identity Connector Framework LDAP connector. It contains configuration
            for use with stock OpenDJ and OpenDS servers.

            This resource definition contains also definition to enable synchronization.
        </description>

        <connectorRef type="ConnectorType">
            <description>
                Reference to the ICF LDAP connector. This is dynamic reference, it will be translated to
                OID during import.
            </description>
            <filter>
                <q:equal>
				<q:path>c:connectorType</q:path>
                    <q:value>com.evolveum.polygon.connector.ldap.LdapConnector</q:value>
                </q:equal>
            </filter>
        </connectorRef>

		<connectorConfiguration>
			<icfc:configurationProperties
				xmlns:icfcldap="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector">
				<icfcldap:port>1389</icfcldap:port>
				<icfcldap:host>localhost</icfcldap:host>
				<icfcldap:baseContext>dc=example,dc=com</icfcldap:baseContext>
				<icfcldap:bindDn>uid=idm,ou=Administrators,dc=example,dc=com</icfcldap:bindDn>
				<icfcldap:bindPassword>
	                    <t:clearValue>secret</t:clearValue>
	            </icfcldap:bindPassword>
	            <icfcldap:pagingStrategy>auto</icfcldap:pagingStrategy>
	            <icfcldap:vlvSortAttribute>entryUUID</icfcldap:vlvSortAttribute>

				<icfcldap:operationalAttributes>ds-pwp-account-disabled</icfcldap:operationalAttributes>
	 			<icfcldap:operationalAttributes>isMemberOf</icfcldap:operationalAttributes>
			</icfc:configurationProperties>
            <icfc:resultsHandlerConfiguration>
				<icfc:enableNormalizingResultsHandler>false</icfc:enableNormalizingResultsHandler>
				<icfc:enableFilteredResultsHandler>false</icfc:enableFilteredResultsHandler>
				<icfc:enableAttributesToGetSearchResultsHandler>false</icfc:enableAttributesToGetSearchResultsHandler>
			</icfc:resultsHandlerConfiguration>
		</connectorConfiguration>

	<schemaHandling>
		<objectType>
			<kind>account</kind>
			<displayName>Normal Account</displayName>
			<default>true</default>
			<objectClass>ri:inetOrgPerson</objectClass>
			<attribute>
				<ref>ri:dn</ref>
				<displayName>Distinguished Name</displayName>
				<limitations>
					<minOccurs>0</minOccurs>
					<access>
                        <read>true</read>
						<add>true</add>
						<modify>true</modify>
					</access>
				</limitations>
				<matchingRule>mr:stringIgnoreCase</matchingRule>
				<outbound>
					<source>
						<path>$user/name</path>
					</source>
					<expression>

					</expression>
				</outbound>
			</attribute>
			<attribute>
				<ref>ri:entryUUID</ref>
				<displayName>Entry UUID</displayName>
				<limitations>
					<access>
                        <read>true</read>
						<add>false</add>
						<modify>true</modify>
					</access>
				</limitations>
				<matchingRule>mr:stringIgnoreCase</matchingRule>
			</attribute>
			<attribute>
				<ref>ri:cn</ref>
				<displayName>Common Name</displayName>
				<limitations>
					<minOccurs>0</minOccurs>
					<access>
                        <read>true</read>
						<add>true</add>
						<modify>true</modify>
					</access>
				</limitations>

				<outbound>
					<source>
						<path>$user/fullName</path>
					</source>
				</outbound>
				<inbound>
					<target>
						<path>$user/fullName</path>
					</target>
				</inbound>
			</attribute>
			<attribute>
				<ref>ri:sn</ref>
				<displayName>Surname</displayName>
				<limitations>
					<minOccurs>0</minOccurs>
				</limitations>
				<outbound>
					<source>

						<path>familyName</path>
					</source>
				</outbound>
				<inbound>
					<target>

						<path>familyName</path>
					</target>
				</inbound>
			</attribute>
			<attribute>
				<ref>ri:givenName</ref>
				<displayName>Given Name</displayName>
				<outbound>
					<source>

						<path>$c:user/c:givenName</path>
					</source>
				</outbound>
				<inbound>
					<target>
						<path>$c:user/c:givenName</path>
					</target>
				</inbound>
			</attribute>
			<attribute>
				<ref>ri:uid</ref>
				<displayName>Login Name</displayName>
				<matchingRule>mr:stringIgnoreCase</matchingRule>
				<outbound>
					<strength>weak</strength>
					<source>
						<description>Source may have description</description>
						<path>$user/name</path>
					</source>

					<expression>

					</expression>
				</outbound>
				<inbound>
					<target>
						<description>Targets may have description</description>
						<path>$c:user/c:name</path>
                    </target>
				</inbound>
			</attribute>
			<attribute>
				<ref>ri:description</ref>
				<outbound>
					<strength>weak</strength>
					<expression>
						<description>Expression that assigns a fixed value</description>
						<value>Created by IDM</value>
					</expression>
				</outbound>
			</attribute>
			<attribute>
				<ref>ri:l</ref>
				<displayName>Location</displayName>
				<outbound>
					<source>
						<path>$user/locality</path>
					</source>
				</outbound>
			</attribute>
			<attribute>
				<ref>ri:employeeType</ref>
				<displayName>Employee Type</displayName>
				<tolerant>false</tolerant>
				<outbound>
					<source>
						<path>$user/employeeType</path>
					</source>
				</outbound>
			</attribute>

			<iteration>
				<maxIterations>5</maxIterations>
			</iteration>

			<protected>
				<filter>
					<q:equal>
						<q:matching>http://prism.evolveum.com/xml/ns/public/matching-rule-3#distinguishedName</q:matching>
						<q:path>attributes/ri:dn</q:path>
						<q:value>uid=idm,ou=Administrators,dc=example,dc=com</q:value>
					</q:equal>
				</filter>
			</protected>

			<activation>
                <administrativeStatus>
                    <outbound/>
                    <inbound>
                    	<strength>weak</strength>
                        <expression>
                            <asIs/>
                        </expression>
                    </inbound>
                </administrativeStatus>
            </activation>

            <credentials>
                <password>
                    <outbound>
                    	<expression>
                        	<asIs/>
                        </expression>
                    </outbound>
                    <inbound>
                    	<strength>weak</strength>
                        <expression>
                            <generate/>
                        </expression>
                    </inbound>
                </password>
            </credentials>

		</objectType>
	</schemaHandling>

    <capabilities xmlns:cap="http://midpoint.evolveum.com/xml/ns/public/resource/capabilities-3">
    	<configured>
            <cap:activation>
                <cap:status>
                    <cap:attribute>ri:ds-pwp-account-disabled</cap:attribute>
                    <cap:enableValue/>
                    <cap:disableValue>true</cap:disableValue>
                </cap:status>
            </cap:activation>
    	</configured>
    </capabilities>

        <synchronization>
        	<objectSynchronization>

	            <enabled>true</enabled>

	            <correlation>
	                <q:description>
	                    Correlation expression is a search query.
	                    Following search queury will look for users that have "name"
	                    equal to the "uid" attribute of the account. Simply speaking,
	                    it will look for match in usernames in the IDM and the resource.
	                    The correlation rule always looks for users, so it will not match
	                    any other object type.
	                </q:description>
	                <q:equal>
	                    <q:path>name</q:path>
	                    <expression>
							<path>
								declare namespace ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance-3";
								$account/attributes/ri:uid
							</path>
	                    </expression>
	                </q:equal>
	            </correlation>

	            <reaction>
	                <situation>linked</situation>
	                <synchronize>true</synchronize>
	            </reaction>
	            <reaction>
	                <situation>deleted</situation>
	                <synchronize>true</synchronize>
		            <action>
		            	<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#unlink</handlerUri>
		            </action>
	            </reaction>

	            <reaction>
	                <situation>unlinked</situation>
	                <synchronize>true</synchronize>
		            <action>
		            	<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#link</handlerUri>
		            </action>
	            </reaction>
	            <reaction>
	                <situation>unmatched</situation>
	                <synchronize>true</synchronize>
		            <action>
		            	<handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/action-3#addFocus</handlerUri>
		            </action>
	            </reaction>
			</objectSynchronization>
        </synchronization>

    </resource>

    <task oid="91919192-76e0-59e2-86d6-3d4f02d3ffff">
        <name>Synchronization: Embedded Test OpenDJ (no extensions schema)</name>
        <description>
            Definition of a live synchronization task. It will poll changelog and pull in changes
        </description>
        <taskIdentifier>91919191-76e0-59e2-86d6-3d4f02d3ffff</taskIdentifier>
        <ownerRef oid="00000000-0000-0000-0000-000000000002"/>
        <executionStatus>runnable</executionStatus>

        <handlerUri>http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3</handlerUri>
        <objectRef oid="ef2bc95b-76e0-48e2-86d6-3d4f02d3e1a2" type="ResourceType"/>
        <recurrence>recurring</recurrence>
        <binding>tight</binding>
        <schedule>
            <interval>5</interval>

        </schedule>
    </task>

</objects>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.gen;

import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.BytecodeNode;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.ParameterizedType;
import com.facebook.presto.bytecode.Scope;
import com.facebook.presto.bytecode.control.TryCatch;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.relational.CallExpression;
import com.facebook.presto.sql.relational.RowExpression;
import com.google.common.primitives.Primitives;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodType;
import java.util.List;
import java.util.Map;

import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.spi.StandardErrorCode.DIVISION_BY_ZERO;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static com.facebook.presto.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static com.facebook.presto.spi.StandardErrorCode.NUMERIC_VALUE_OUT_OF_RANGE;
import static com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary;
import static com.facebook.presto.sql.gen.BytecodeUtils.invoke;
import static com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary;
import static com.facebook.presto.util.Reflection.methodHandle;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.getOnlyElement;
import static java.lang.invoke.MethodType.methodType;

public class TryCodeGenerator
        implements BytecodeGenerator
{
    private static final String EXCEPTION_HANDLER_NAME = "tryExpressionExceptionHandler";

    private final Map<CallExpression, MethodDefinition> tryMethodsMap;

    public TryCodeGenerator(Map<CallExpression, MethodDefinition> tryMethodsMap)
    {
        this.tryMethodsMap = tryMethodsMap;
    }

    @Override
    public BytecodeNode generateExpression(Signature signature, BytecodeGeneratorContext context, Type returnType, List<RowExpression> arguments)
    {
        checkArgument(arguments.size() == 1, "try methods only contain a single expression");
        checkArgument(getOnlyElement(arguments) instanceof CallExpression, "try methods must contain a call expression");

        CallExpression innerCallExpression = (CallExpression) getOnlyElement(arguments);
        checkState(tryMethodsMap.containsKey(innerCallExpression), "try methods map does not contain this try call");

        BytecodeBlock bytecodeBlock = new BytecodeBlock()
                .comment("load required variables")
                .getVariable(context.getScope().getVariable("this"));

        MethodDefinition definition = tryMethodsMap.get(innerCallExpression);

        definition.getParameters().stream()
                .map(parameter -> context.getScope().getVariable(parameter.getName()))
                .forEach(bytecodeBlock::getVariable);

        bytecodeBlock.comment("call dynamic try method: " + definition.getName())
                .invokeVirtual(definition)
                .append(unboxPrimitiveIfNecessary(context.getScope(), Primitives.wrap(innerCallExpression.getType().getJavaType())));

        return bytecodeBlock;
    }

    public static MethodDefinition defineTryMethod(
            BytecodeExpressionVisitor innerExpressionVisitor,
            ClassDefinition classDefinition,
            String methodName,
            List<Parameter> inputParameters,
            Class<?> returnType,
            RowExpression innerRowExpression,
            CallSiteBinder callSiteBinder)
    {
        MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), methodName, type(returnType), inputParameters);
        Scope calleeMethodScope = method.getScope();

        BytecodeNode innerExpression = innerRowExpression.accept(innerExpressionVisitor, calleeMethodScope);

        MethodType exceptionHandlerType = methodType(returnType, PrestoException.class);
        MethodHandle exceptionHandler = methodHandle(TryCodeGenerator.class, EXCEPTION_HANDLER_NAME, PrestoException.class).asType(exceptionHandlerType);
        Binding binding = callSiteBinder.bind(exceptionHandler);

        method.comment("Try projection: %s", innerRowExpression.toString());
        method.getBody()
                .append(new TryCatch(
                        new BytecodeBlock()
                                .append(innerExpression)
                                .append(boxPrimitiveIfNecessary(calleeMethodScope, returnType)),
                        new BytecodeBlock()
                                .append(invoke(binding, EXCEPTION_HANDLER_NAME)),
                        ParameterizedType.type(PrestoException.class)))
                .ret(returnType);

        return method;
    }

    public static Object tryExpressionExceptionHandler(PrestoException e)
            throws PrestoException
    {
        int errorCode = e.getErrorCode().getCode();
        if (errorCode == DIVISION_BY_ZERO.toErrorCode().getCode()
                || errorCode == INVALID_CAST_ARGUMENT.toErrorCode().getCode()
                || errorCode == INVALID_FUNCTION_ARGUMENT.toErrorCode().getCode()
                || errorCode == NUMERIC_VALUE_OUT_OF_RANGE.toErrorCode().getCode()) {
            return null;
        }

        throw e;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Core\UserBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Doctrine\ORM\EntityManagerInterface;
use Core\UserBundle\Entity\User;
use Core\CommonBundle\Exception\NotFoundEntityException;
use Core\UserBundle\Entity\Admin;

class UniqueEmailValidator extends ConstraintValidator
{
    protected $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * This method collect the all emails except the current user's and validate that is the given email in the all emails array.
     *
     * @param User       $user
     * @param Constraint $constraint
     *
     * @throws NotFoundEntityException
     */
    public function validate($user, Constraint $constraint)
    {
        if ($user instanceof User) {
            $emails = $this->getUsedEmails($user);
        } elseif ($user instanceof Admin) {
            $emails = $this->em->getRepository('CoreUserBundle:Admin')->findAll();
        } else {
            throw new NotFoundEntityException('user.not_found');
        }

        $userEmails = $this->getUserEmails($user);

        // If the $entity's email is in $emails, then it returns an error
        foreach ($userEmails as $userEmail) {
            if (in_array($userEmail, $emails)) {
                $this->context->buildViolation($constraint->message)
                        ->atPath('emailCanonical')
                        ->addViolation();
                break;
            }
        }
    }

    /**
     * Returns all emails which belong to $user.
     *
     * @param User $user
     *
     * @return array
     */
    private function getUserEmails(User $user)
    {
        $emails = array($user->getEmailCanonical());

        if ($user->isCompany()) {
            return $emails;
        }

        if (false === is_null($user->getFacebookAccount()) && false === in_array($user->getFacebookAccount()->getEmail(), $emails)) {
            $emails[] = $user->getFacebookAccount()->getEmail();
        }
        if (false === is_null($user->getGoogleAccount()) && false === in_array($user->getGoogleAccount()->getEmail(), $emails)) {
            $emails[] = $user->getGoogleAccount()->getEmail();
        }
        if (false === is_null($user->getTwitterAccount()) && false === in_array($user->getTwitterAccount()->getEmail(), $emails)) {
            $emails[] = $user->getTwitterAccount()->getEmail();
        }

        return $emails;
    }

    /**
     * Returns all emails which cannot be same as $user's email.
     *
     * @param User $user
     *
     * @return array
     */
    private function getUsedEmails(User $user)
    {
        $allEmails = array();

        if (false === is_null($user->getId())) {
            $allUsersExceptTheGiven = $this->em->getRepository('CoreUserBundle:User')->findAllExceptOne($user->getId());
        } else {
            $allUsersExceptTheGiven = $this->em->getRepository('CoreUserBundle:User')->findAll();
        }

        foreach ($allUsersExceptTheGiven as $exceptUser) {
            $allEmails = array_merge($allEmails, $this->getAllEmailsFromAUser($exceptUser));
        }

        return $allEmails;
    }

    /**
     * Returns all email addresses from a user (including social accounts' email address).
     *
     * @param User $user
     *
     * @return array
     */
    private function getAllEmailsFromAUser(User $user)
    {
        $allEmails = array();

        $allEmails[] = $user->getEmail();

        if ($user->isCompany()) {
            return $allEmails;
        }

        if (false === is_null($user->getFacebookAccount())) {
            $allEmails[] = $user->getFacebookAccount()->getEmail();
        }
        if (false === is_null($user->getGoogleAccount())) {
            $allEmails[] = $user->getGoogleAccount()->getEmail();
        }
        if (false === is_null($user->getTwitterAccount())) {
            $allEmails[] = $user->getTwitterAccount()->getEmail();
        }

        return $allEmails;
    }
}


text:
require 'spec_helper'

describe SourceParser::Upcoming do
  fixtures :all

  describe "when extracting Upcoming event id" do
    it 'should extract from verbose URL' do
      SourceParser::Upcoming._upcoming_url_to_event_id('http://upcoming.yahoo.com/event/3082817/OR/Portland/Ignite-Portland-7/').should == '3082817'
    end

    it "should extract from terse URL" do
      SourceParser::Upcoming._upcoming_url_to_event_id('http://upcoming.yahoo.com/event/3082817/').should == '3082817'
    end

    it "should extract from truncated URL" do
      SourceParser::Upcoming._upcoming_url_to_event_id('http://upcoming.yahoo.com/event/3082817').should == '3082817'
    end

    it "should extract from mobile URL" do
      SourceParser::Upcoming._upcoming_url_to_event_id('http://m.upcoming.yahoo.com/event/3082817').should == '3082817'
    end
  end

  it "should parse a v1 API response" do
    content = read_sample('upcoming_v1.xml')
    events = SourceParser::Upcoming.to_abstract_events(:content => content,
                                                       :url => 'http://upcoming.yahoo.com/event/3082817')

    events.size.should == 1
    event = events.first
    location = event.location

    event.title.should == 'Ignite Portland 7'
    event.description.should =~ /^NEW DATE.+Ignite Portland 7 will happen/m
    event.start_time.should == Time.parse('2009-11-19 7:00PM')
    # NOTE: Upcoming's API used to emit sensible "utc_end" date-times which the below test relied on, but nothing in the "end_date" or "end_time" fields. However, the v2 API has incorrect "utc_end" date-times and only has "end_date" and "end_time" fields. Therefore, we can't tell when this event ends any more:
    event.end_time.should == nil # Was: Time.parse('2009-11-19 10:00PM')
    event.url.should == 'http://www.igniteportland.com'
    event.tags.should == ['upcoming:event=3082817']

    location.street_address.should == '3702 S.E. Hawthorne Blvd'
    location.locality.should == 'Portland'
    location.region.should == 'Oregon'
    location.postal_code.should == '97214'
    location.tags.should == ['upcoming:venue=61559']
  end

  it "should parse a v2 API response with invalid UTC dates" do
    content = read_sample('upcoming_v2_with_invalid_utc_dates.xml')
    events = SourceParser::Upcoming.to_abstract_events(:content => content,
                                                       :url => 'http://upcoming.yahoo.com/event/8237694')

    events.size.should == 1
    event = events.first
    location = event.location

    event.title.should == "Portland JavaScript Admirers' Monthly Meeting"
    event.description.should =~ /^The monthly meeting of Portland's first JavaScript and ECMAscript users' group./
    event.start_time.should == Time.parse('Oct 26 19:00:00 2011')
    event.end_time.should == Time.parse('Oct 26 21:00:00 2011')
    event.url.should be_blank
    event.tags.should == ['upcoming:event=8237694']

    location.street_address.should == '915 SW Stark St., Suite 400'
    location.locality.should == 'Portland'
    location.region.should == 'Oregon'
    location.postal_code.should == '97205'
    location.tags.should == ['upcoming:venue=591135']
  end
end


text:
package com.defano.wyldcard.editor;

import com.defano.wyldcard.editor.help.ExampleModel;
import com.defano.wyldcard.editor.help.ParameterModel;
import com.defano.wyldcard.editor.help.SyntaxHelpModel;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.fife.ui.autocomplete.Completion;
import org.fife.ui.autocomplete.CompletionProvider;
import org.fife.ui.autocomplete.TemplateCompletion;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collection;

public class AutoCompletionBuilder {

    private String codePrefix;
    private String templateName;
    private ArrayList<String> templates = new ArrayList<>();
    private String summary;
    private String description;
    private String categoryName;
    private Icon icon;
    private ArrayList<String> examplesCode = new ArrayList<>();
    private ArrayList<String> examplesDescription = new ArrayList<>();
    private ArrayList<String> parameterNames = new ArrayList<>();
    private ArrayList<String> parameterDescriptions = new ArrayList<>();

    private AutoCompletionBuilder() {}

    public static AutoCompletionBuilder fromSyntaxHelpModel(SyntaxHelpModel model, String categoryName, Icon icon) {
        AutoCompletionBuilder builder = new AutoCompletionBuilder();

        builder.categoryName = categoryName;
        builder.codePrefix = model.getCodePrefix();
        builder.templateName = model.getTitle();
        builder.templates.addAll(model.getTemplates());
        builder.summary = model.getSummary();
        builder.description = model.getDescription();
        builder.icon = icon;

        for (ExampleModel thisExample : model.getExamples()) {
            builder.examplesCode.add(thisExample.getCode());
            builder.examplesDescription.add(thisExample.getDescription());
        }

        for (ParameterModel thisParam : model.getParameters()) {
            builder.parameterNames.add(thisParam.getParameter());
            builder.parameterDescriptions.add(thisParam.getDescription());
        }

        return builder;
    }

    public void buildInto(Collection<Completion> completions, CompletionProvider provider) {
        completions.add(build(provider));
    }

    public TemplateCompletion build(CompletionProvider provider) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(getSummaryMarkdown());
        String summary = HtmlRenderer.builder().build().render(document);

        TemplateCompletion tc = new TemplateCompletion(provider, codePrefix, templateName, templates.get(0), null, summary);
        tc.setIcon(icon);
        return tc;
    }

    private String getSummaryMarkdown() {
        StringBuilder builder = new StringBuilder();

        if (templateName != null) {
            builder.append("### ")
                    .append(templateName)
                    .append(" (")
                    .append(categoryName)
                    .append(")")
                    .append("\n\n");
        }

        if (summary != null) {
            builder.append(summary).append("\n\n");
        }

        for (String template : templates) {
            template = template.replace("$", "");
            builder.append(makeCodeBlock(0, template));
        }

        builder.append("\n");

        if (!parameterNames.isEmpty()) {
            builder.append("**Where**").append("\n");
            for (int index = 0; index < parameterNames.size(); index++) {
                builder.append("* ").append("`{").append(parameterNames.get(index)).append("}`: ");
                builder.append(parameterDescriptions.get(index)).append("\n");
            }
        }

        if (description != null) {
            builder.append("\n").append(description).append("\n\n");
        }

        if (!examplesCode.isEmpty()) {

            for (int index = 0; index < examplesDescription.size(); index++) {
                if (examplesDescription.size() > 1) {
                    builder.append("\n**Example ").append(index + 1).append(":** ");
                } else {
                    builder.append("\n**Example:** ");
                }

                if (examplesDescription.get(index) != null) {
                    builder.append(examplesDescription.get(index)).append("\n\n");
                } else {
                    builder.append("\n\n");
                }

                builder.append(makeCodeBlock(0, examplesCode.get(index))).append("\n\n");
            }
        }

        return builder.toString();
    }

    /**
     * Converts a string of text into a code block.
     *
     * The Commonmark markdown processor does not appear to properly render triple-backtick code blocks, so this code
     * attempts to synthesize each line as a single-backtick code span. Note that \t characters will be replaced by
     * two non-breaking spaces.
     *
     * @param indent Indent depth to be applied to every line in the block.
     * @param codeBlock The \n-delimited block of code.
     * @return Synthesized Markdown
     */
    private String makeCodeBlock(int indent, String codeBlock) {
        StringBuilder builder = new StringBuilder();

        // Padding before/after backtick is important; two adjacent (``) is illegal
        codeBlock = codeBlock.replace("\t", " `   ` ");

        for (String thisLine : codeBlock.split("\n")) {
            for (int index = 0; index < indent; index++) {
                builder.append(">");
            }

            builder.append("`").append(thisLine).append(" `").append("<br>\n");
        }

        return builder.toString();
    }
}


text:
<?php

namespace Scool\Curriculum\Http\Controllers;

use Illuminate\Http\Request;

use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use Scool\Curriculum\Http\Requests\DepartmentCreateRequest;
use Scool\Curriculum\Http\Requests\DepartmentUpdateRequest;
use Scool\Curriculum\Repositories\DepartmentRepository;
use Scool\Curriculum\Validators\DepartmentValidator;

class DepartmentsController extends Controller
{

    /**
     * @var DepartmentRepository
     */
    protected $repository;

    /**
     * @var DepartmentValidator
     */
    protected $validator;

    public function __construct(DepartmentRepository $repository, DepartmentValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));
        $departments = $this->repository->all();

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $departments,
            ]);
        }

        return view('departments.index', compact('departments'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  DepartmentCreateRequest $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(DepartmentCreateRequest $request)
    {

        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);

            $department = $this->repository->create($request->all());

            $response = [
                'message' => 'Department created.',
                'data'    => $department->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $department = $this->repository->find($id);

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $department,
            ]);
        }

        return view('departments.show', compact('department'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

        $department = $this->repository->find($id);

        return view('departments.edit', compact('department'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  DepartmentUpdateRequest $request
     * @param  string            $id
     *
     * @return Response
     */
    public function update(DepartmentUpdateRequest $request, $id)
    {

        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);

            $department = $this->repository->update($id, $request->all());

            $response = [
                'message' => 'Department updated.',
                'data'    => $department->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {

            if ($request->wantsJson()) {

                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $deleted = $this->repository->delete($id);

        if (request()->wantsJson()) {

            return response()->json([
                'message' => 'Department deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'Department deleted.');
    }
}


text:
package ch.demo.dom;

import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import ch.demo.dom.jpa.JPAPhoneNumberConverter;

/**
 * Models a student.
 *
 * @author hostettler
 */
@Entity
@NamedQuery(name = "findAllStudentsByFirstName", query = "SELECT s FROM Student s WHERE s.lastName = :lastname")
@Table(name = "STUDENTS")
public class Student implements Serializable {

	/** The serial-id. */
	private static final long serialVersionUID = -6146935825517747043L;

	/** The unique id in a technical sense. */
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "ID")
	private Long id;

	/** The student unique id in a business sense. */
	@NotNull
	@Column(name = "STUDENT_ID")
	private Integer studentId;

	/** The student last name. */
	@NotNull
	@Size(min = 2, max = 35)
	@Column(name = "LAST_NAME")
	private String lastName;

	/** The student first name. */
	@NotNull
	@Size(min = 2, max = 35)
	@Column(name = "FIRST_NAME")
	private String firstName;

	/** The student birth date. */
	@Temporal(TemporalType.DATE)
	@NotNull
	@Column(name = "BIRTH_DATE")
	private Date birthDate;

	/** The student phone number. */
	@Convert(converter = JPAPhoneNumberConverter.class)
	@Column(name = "PHONE_NUMBER")
	private PhoneNumber phoneNumber;

	/** The student's gender. */
	private transient Gender gender;

	/** The address of the student. */
	@Embedded
	private Address address;

	/** The set of grades of the student. */

	// /** A picture of the student. */
	// @Lob
	// @Basic(fetch = FetchType.LAZY)
	// @Column(table = "PICTURES", name = "PICTURE", nullable = true)
	transient private byte[] picture;

	public Student() {
	}

	/**
	 *
	 * @param lastName
	 *            The student last name.
	 * @param firstName
	 *            The student first name.
	 * @param birthDate
	 *            The student birth date.
	 */
	public Student(final String lastName, final String firstName, final Date birthDate, PhoneNumber phone) {
		this.firstName = firstName;
		this.lastName = lastName;
		this.birthDate = birthDate;
		this.phoneNumber = phone;
	}

	@Override
	public int hashCode() {
		return Objects.hash(studentId, firstName, lastName, birthDate);
	}

	@Override
	public boolean equals(final Object obj) {
		if (obj == null || getClass() != obj.getClass()) {
			return false;
		}
		final Student other = (Student) obj;
		return Objects.equals(this.studentId, other.studentId) && Objects.equals(this.lastName, other.lastName)
				&& Objects.equals(this.firstName, other.firstName) && Objects.equals(this.birthDate, other.birthDate);
	}

	@Override
	public String toString() {
		return "{id:" +  id + ", studentId:" + studentId + ", lastName:" + lastName + ", firstName:"
				+ firstName + ", birthDate:" + birthDate + ", phoneNumber:" + phoneNumber + ", gender:" + gender
				+ ", address:" + address + "}";
	}

	public Long getId() {
		return id;
	}

	/** -----------------Getters and setters. **/
	/**
	 * @return the phoneNumber
	 */
	public final PhoneNumber getPhoneNumber() {
		return phoneNumber;
	}

	/**
	 * @param phoneNumber
	 *            the phoneNumber to set
	 */
	public final void setPhoneNumber(final PhoneNumber pPhoneNumber) {
		this.phoneNumber = pPhoneNumber;
	}

	/**
	 * @return the lastName
	 */
	public final String getLastName() {
		return lastName;
	}

	/**
	 * @param lastName
	 *            the lastName to set
	 */
	public final void setLastName(final String pLastName) {
		this.lastName = pLastName;
	}

	/**
	 * @return the firstName
	 */
	public final String getFirstName() {
		return firstName;
	}

	/**
	 * @param firstName
	 *            the firstName to set
	 */
	public final void setFirstName(final String pFirstName) {
		this.firstName = pFirstName;
	}

	/**
	 * @return the birthDate
	 */
	public final Date getBirthDate() {
		return birthDate;
	}

	/**
	 * @param birthDate
	 *            the birthDate to set
	 */
	public final void setBirthDate(final Date pBirthDate) {
		birthDate = pBirthDate;
	}

	/**
	 * @return the gender
	 */
	public final Gender getGender() {
		return gender;
	}

	/**
	 * @param gender
	 *            the gender to set
	 */
	public final void setGender(final Gender pGender) {
		gender = pGender;
	}

	/**
	 * @return the address
	 */
	public final Address getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address to set
	 */
	public final void setAddress(final Address pAddress) {
		this.address = pAddress;
	}

	/**
	 * @return the picture
	 */
	public final byte[] getPicture() {
		return picture;
	}

	/**
	 * @param picture
	 *            the picture to set
	 */
	public void setPicture(final byte[] pPicture) {
		this.picture = pPicture;
	}

	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the studentId
	 */
	public Integer getStudentId() {
		return studentId;
	}

	/**
	 * @param studentId
	 *            the studentId to set
	 */
	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}

	public void copyBusinessFieldsFrom(Student student) {
		this.setAddress(student.getAddress());
		this.setBirthDate(student.getBirthDate());
		this.setLastName(student.getLastName());
		this.setFirstName(student.getFirstName());
		this.setPhoneNumber(student.getPhoneNumber());
		this.setGender(student.getGender());
	}
}


text:
"""
Author: Asish Panda
email: asishrocks95@gmail.com

The main module to parse user's input for an output. This is meant to be used directly by the
main module responisble for running the whole server. The user's input should be converted
to string and passed here.
"""

from parse import client_parse, general_parse
from KEYS import LOCATION, STATE, CLIENTS

class main:

    def __init__(self, string):
        #Best way would be to check each parse class
        #and give the most accurate result

        self.cp = client_parse(string)
        self.gp = general_parse(string)

    def do():
        value = self.cp.extract()
        if value:
            #do something with value

        else:
            #do something with gp parser
            #self.gp.extract()

if __name__ == '__main__':
    #get user's input
    #string = voice()
    #do = main(string)


text:
package com.intellij.packaging.artifacts;

import org.jetbrains.annotations.NotNull;

public class ArtifactAdapter implements ArtifactListener {
  @Override
  public void artifactAdded(@NotNull Artifact artifact) {
  }

  @Override
  public void artifactRemoved(@NotNull Artifact artifact) {
  }

  @Override
  public void artifactChanged(@NotNull Artifact artifact, @NotNull String oldName) {
  }
}


text:
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using TankView.Properties;

namespace TankView.ViewModel {
    public class RecentLocations : ObservableCollection<string> {
        List<string> CachedLocations = new List<string>();

        public RecentLocations() {
            if (Settings.Default.RecentLocations == null) {
                Settings.Default.RecentLocations = new StringCollection();
            }

            string[] locations = new string[Settings.Default.RecentLocations.Count];
            CachedLocations = Settings.Default.RecentLocations.Cast<string>().ToList();
            foreach (string location in CachedLocations) {
                base.Add(location);
            }
        }

        public new void Add(string path) {
            if (CachedLocations.Contains(path)) {
                Remove(path);
            }

            Insert(0, path);
            while (CachedLocations.Count > 7) {
                Remove(CachedLocations.ElementAt(7));
            }

            Settings.Default.RecentLocations = new StringCollection();
            Settings.Default.RecentLocations.AddRange(CachedLocations.ToArray());
            Settings.Default.Save();
        }

        public new void Remove(string path) {
            CachedLocations.Remove(path);
            base.Remove(path);
        }

        public new void Insert(int i, string path) {
            CachedLocations.Insert(i, path);
            base.Insert(i, path);
        }
    }
}


text:
layout: post
title: just plain folk
date: 2009-05-07 02:49
comments: false
categories: [poems]
---

many people here,
making sounds of ruffling leaves
falling from the sky.


text: export { FolderAdd24 as default } from "../../";


text:
#ifndef __BASE_CC_PLATFORM_CONFIG_H__
#define __BASE_CC_PLATFORM_CONFIG_H__
/// @cond DO_NOT_SHOW

/**
  Config of cocos2d-x project, per target platform.

  THIS FILE MUST NOT INCLUDE ANY OTHER FILE
*/

//////////////////////////////////////////////////////////////////////////
// pre configure
//////////////////////////////////////////////////////////////////////////

// define supported target platform macro which CC uses.
#define CC_PLATFORM_UNKNOWN            0
#define CC_PLATFORM_IOS                1
#define CC_PLATFORM_ANDROID            2
#define CC_PLATFORM_WIN32              3
#define CC_PLATFORM_MARMALADE          4
#define CC_PLATFORM_LINUX              5
#define CC_PLATFORM_BADA               6
#define CC_PLATFORM_BLACKBERRY         7
#define CC_PLATFORM_MAC                8
#define CC_PLATFORM_NACL               9
#define CC_PLATFORM_EMSCRIPTEN        10
#define CC_PLATFORM_TIZEN             11
#define CC_PLATFORM_QT5               12
#define CC_PLATFORM_WINRT             13

// Determine target platform by compile environment macro.
#define CC_TARGET_PLATFORM             CC_PLATFORM_UNKNOWN

// Apple: Mac and iOS
#if defined(__APPLE__) && !defined(ANDROID) // exclude android for binding generator.
    #include <TargetConditionals.h>
    #if TARGET_OS_IPHONE // TARGET_OS_IPHONE includes TARGET_OS_IOS TARGET_OS_TV and TARGET_OS_WATCH. see TargetConditionals.h
        #undef  CC_TARGET_PLATFORM
        #define CC_TARGET_PLATFORM         CC_PLATFORM_IOS
    #elif TARGET_OS_MAC
        #undef  CC_TARGET_PLATFORM
        #define CC_TARGET_PLATFORM         CC_PLATFORM_MAC
    #endif
#endif

// android
#if defined(ANDROID)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_ANDROID
#endif

// win32
#if defined(_WIN32) && defined(_WINDOWS)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_WIN32
#endif

// linux
#if defined(LINUX) && !defined(__APPLE__)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM         CC_PLATFORM_LINUX
#endif

// marmalade
#if defined(MARMALADE)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM         CC_PLATFORM_MARMALADE
#endif

// bada
#if defined(SHP)
#undef  CC_TARGET_PLATFORM
#define CC_TARGET_PLATFORM         CC_PLATFORM_BADA
#endif

// qnx
#if defined(__QNX__)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_BLACKBERRY
#endif

// native client
#if defined(__native_client__)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_NACL
#endif

// Emscripten
#if defined(EMSCRIPTEN)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_EMSCRIPTEN
#endif

// tizen
#if defined(TIZEN)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_TIZEN
#endif

// qt5
#if defined(CC_TARGET_QT5)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM     CC_PLATFORM_QT5
#endif

// WinRT (Windows 8.1 Store/Phone App)
#if defined(WINRT)
    #undef  CC_TARGET_PLATFORM
    #define CC_TARGET_PLATFORM          CC_PLATFORM_WINRT
#endif

//////////////////////////////////////////////////////////////////////////
// post configure
//////////////////////////////////////////////////////////////////////////

// check user set platform
#if ! CC_TARGET_PLATFORM
    #error  "Cannot recognize the target platform; are you targeting an unsupported platform?"
#endif

#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#ifndef __MINGW32__
#pragma warning (disable:4127)
#endif
#endif  // CC_PLATFORM_WIN32

#if ((CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) || (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_TIZEN))
    #define CC_PLATFORM_MOBILE
#else
    #define CC_PLATFORM_PC
#endif

/// @endcond
#endif  // __BASE_CC_PLATFORM_CONFIG_H__


text:
// Copyright (c) 2010-2020 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)

using System.Collections.Generic;

namespace SIL.DictionaryServices.Model
{
	public interface IExtensible
	{
		List<LexTrait> Traits { get; }
		List<LexField> Fields { get; }
	}
}


text:
package uk.ac.ebi.embl.api.validation.helper;

import java.io.*;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.StringUtils;

import uk.ac.ebi.embl.api.validation.FileType;

/**
 * Created by IntelliJ IDEA.
 * User: lbower
 * Date: 08-Feb-2012
 * Time: 16:08:06
 */
public class FileUtils {

	public static final String embl_filetoken = "ID";
	public static final String genbank_filetoken = "LOCUS";
	public static final String gff_filetoken = "##gff-version 3";
	public static final String fasta_filetoken = ">";

    public static void copyFile(File src,
                                File dst) throws IOException, FileNotFoundException, SecurityException {

        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

    public static String readFile(InputStream inputStream) throws IOException {

        if (inputStream != null) {
            BufferedInputStream stream = new BufferedInputStream(inputStream);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer fileData = new StringBuffer(1000);

            char[] buf = new char[1024];
            int numRead = 0;
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
            reader.close();

            return fileData.toString();
        }
        return null;
    }

    public static void moveFile(String oldFileString, String newFileDirString) throws Exception
	{
		File oldFile = new File(oldFileString);
		File newFileDir = new File(newFileDirString);

		if (!oldFile.exists())
		{
			throw new Exception("file does not exist " + oldFileString);
		}

		if (!newFileDir.isDirectory())
		{
			throw new Exception("copy file is not a directory " + newFileDirString);
		}

		boolean success = oldFile.renameTo(new File(newFileDir, oldFile.getName()));

		if (!success)
		{
			throw new Exception("problem moving file\n " + oldFileString + " to \n " + newFileDirString);
		}
}

	public static String getdeCompressedFile(String file) throws IOException
	{
		if (file == null)
		{
			return null;
		}
		File zipFile = new File(file);
		if (!zipFile.exists())
		{
			return null;
		}

		if (!zipFile.getName().matches("^.+\\.gz$"))
		{
			return file;
		}
		byte[] buffer = new byte[1024];
		GZIPInputStream zis = new GZIPInputStream(new FileInputStream(zipFile));
		File tempFile = new File(zipFile.getParent() + File.separator + zipFile.getName().substring(0, zipFile.getName().lastIndexOf(".gz")));
		if (!tempFile.exists())
		{
			tempFile.createNewFile();
		}

		FileOutputStream fos = new FileOutputStream(tempFile);
		int len;
		while ((len = zis.read(buffer)) > 0)
		{
			fos.write(buffer, 0, len);
		}

		fos.close();

		zis.close();

		return tempFile.getAbsolutePath();
	}

	public static FileType getFileType(File formatFile) throws IOException
	{
		BufferedReader fileFormatReader = new BufferedReader(new FileReader(formatFile));
		// FINDING THE TYPE OF FILE BY READING THE FIRST LINE OF THE FILE
		String firstLineofFile = fileFormatReader.readLine();
		fileFormatReader.close();
		if (firstLineofFile.startsWith(embl_filetoken))
			{
				return FileType.EMBL;
			}
	   else if (firstLineofFile.startsWith(genbank_filetoken))
			{
			  return FileType.GENBANK;
			}
	  else if (firstLineofFile.startsWith(gff_filetoken))
			{
			 return FileType.GFF3;
			}
	   else if (firstLineofFile.startsWith(fasta_filetoken))
			{
			return FileType.FASTA;
			}
		return null;
	}

}


text:
<?php

final class PhameBlogHeaderPictureController
  extends PhameBlogController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $id = $request->getURIData('id');

    $blog = id(new PhameBlogQuery())
      ->setViewer($viewer)
      ->withIDs(array($id))
      ->needHeaderImage(true)
      ->requireCapabilities(
        array(
          PhabricatorPolicyCapability::CAN_VIEW,
          PhabricatorPolicyCapability::CAN_EDIT,
        ))
      ->executeOne();
    if (!$blog) {
      return new Aphront404Response();
    }

    $blog_uri = '/phame/blog/manage/'.$id;

    $supported_formats = PhabricatorFile::getTransformableImageFormats();
    $e_file = true;
    $errors = array();
    $delete_header = ($request->getInt('delete') == 1);

    if ($request->isFormPost()) {
      if ($request->getFileExists('header')) {
        $file = PhabricatorFile::newFromPHPUpload(
          $_FILES['header'],
          array(
            'authorPHID' => $viewer->getPHID(),
            'canCDN' => true,
          ));
      } else if (!$delete_header) {
        $e_file = pht('Required');
        $errors[] = pht(
          'You must choose a file when uploading a new blog header.');
      }

      if (!$errors && !$delete_header) {
        if (!$file->isTransformableImage()) {
          $e_file = pht('Not Supported');
          $errors[] = pht(
            'This server only supports these image formats: %s.',
            implode(', ', $supported_formats));
        }
      }

      if (!$errors) {
        if ($delete_header) {
          $new_value = null;
        } else {
          $file->attachToObject($blog->getPHID());
          $new_value = $file->getPHID();
        }

        $xactions = array();
        $xactions[] = id(new PhameBlogTransaction())
          ->setTransactionType(PhameBlogTransaction::TYPE_HEADERIMAGE)
          ->setNewValue($new_value);

        $editor = id(new PhameBlogEditor())
          ->setActor($viewer)
          ->setContentSourceFromRequest($request)
          ->setContinueOnMissingFields(true)
          ->setContinueOnNoEffect(true);

        $editor->applyTransactions($blog, $xactions);

        return id(new AphrontRedirectResponse())->setURI($blog_uri);
      }
    }

    $title = pht('Edit Blog Header');

    $upload_form = id(new AphrontFormView())
      ->setUser($viewer)
      ->setEncType('multipart/form-data')
      ->appendChild(
        id(new AphrontFormFileControl())
          ->setName('header')
          ->setLabel(pht('Upload Header'))
          ->setError($e_file)
          ->setCaption(
            pht('Supported formats: %s', implode(', ', $supported_formats))))
      ->appendChild(
        id(new AphrontFormCheckboxControl())
          ->setName('delete')
          ->setLabel(pht('Delete Header'))
          ->addCheckbox(
            'delete',
            1,
            null,
            null))
      ->appendChild(
        id(new AphrontFormSubmitControl())
          ->addCancelButton($blog_uri)
          ->setValue(pht('Upload Header')));

    $upload_box = id(new PHUIObjectBoxView())
      ->setHeaderText(pht('Upload New Header'))
      ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
      ->setForm($upload_form);

    $crumbs = $this->buildApplicationCrumbs();
    $crumbs->addTextCrumb(
      pht('Blogs'),
      $this->getApplicationURI('blog/'));
    $crumbs->addTextCrumb(
      $blog->getName(),
      $this->getApplicationURI('blog/view/'.$id));
    $crumbs->addTextCrumb(pht('Blog Header'));
    $crumbs->setBorder(true);

    $header = id(new PHUIHeaderView())
      ->setHeader(pht('Edit Blog Header'))
      ->setHeaderIcon('fa-camera');

    $view = id(new PHUITwoColumnView())
      ->setHeader($header)
      ->setFooter(array(
        $upload_box,
      ));

    return $this->newPage()
      ->setTitle($title)
      ->setCrumbs($crumbs)
      ->appendChild(
        array(
          $view,
      ));

  }
}


text:
from __future__ import unicode_literals

from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import re

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='GenerationRule',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('freq', models.PositiveSmallIntegerField(blank=True, choices=[(0, 'Yearly'), (1, 'Monthly'), (2, 'Weekly'), (3, 'Daily'), (4, 'Hourly'), (5, 'Minutely')], default=3)),
                ('dtstart', models.DateTimeField(blank=True, null=True)),
                ('interval', models.PositiveIntegerField(blank=True, null=True)),
                ('count', models.PositiveIntegerField(blank=True, null=True)),
                ('until', models.DateTimeField(blank=True, null=True)),
                ('bysetpos', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('bymonth', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('bymonthday', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('byyearday', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('byweekno', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('byweekday', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('byhour', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
                ('byminute', models.CharField(blank=True, max_length=64, validators=[django.core.validators.RegexValidator(re.compile('^\\d+(?:,\\d+)*\\Z', 32), code='invalid', message='Enter only digits separated by commas.')])),
            ],
        ),
        migrations.CreateModel(
            name='GenerationTime',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('timestamp', models.DateTimeField(auto_now=True)),
            ],
            options={
                'ordering': ['-timestamp'],
                'get_latest_by': 'timestamp',
            },
        ),
        migrations.CreateModel(
            name='Generator',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('object_id', models.PositiveIntegerField()),
                ('generating', models.BooleanField(default=False)),
                ('generation_time', models.DateTimeField(null=True)),
                ('task_id', models.TextField()),
                ('force_generate', models.BooleanField(default=True)),
                ('autogenerate', models.BooleanField(default=True)),
                ('allow_pauses', models.BooleanField(default=True)),
                ('minimum_between_generations', models.PositiveIntegerField(blank=True, null=True)),
                ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
            ],
        ),
        migrations.CreateModel(
            name='Pause',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('object_id', models.PositiveIntegerField()),
                ('timestamp', models.DateTimeField(auto_now=True)),
                ('reason', models.TextField()),
                ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
                ('generator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='pauses', to='turngeneration.Generator')),
                ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Ready',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('object_id', models.PositiveIntegerField()),
                ('timestamp', models.DateTimeField(auto_now=True)),
                ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')),
                ('generator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='readies', to='turngeneration.Generator')),
                ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='generationtime',
            name='generator',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='timestamps', to='turngeneration.Generator'),
        ),
        migrations.AddField(
            model_name='generationrule',
            name='generator',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rules', to='turngeneration.Generator'),
        ),
        migrations.AlterUniqueTogether(
            name='ready',
            unique_together=set([('content_type', 'object_id', 'generator')]),
        ),
        migrations.AlterUniqueTogether(
            name='pause',
            unique_together=set([('content_type', 'object_id', 'generator')]),
        ),
        migrations.AlterUniqueTogether(
            name='generator',
            unique_together=set([('content_type', 'object_id')]),
        ),
    ]


text:
from __future__ import print_function
try:
    import cPickle as pickle
except ImportError:
    import pickle

try:
    from cStringIO import StringIO
except ImportError:
    from io import StringIO
import functools
import inspect
import linecache
import optparse
import os
import sys

from _line_profiler import LineProfiler as CLineProfiler

# Python 2/3 compatibility utils
# ===========================================================
PY3 = sys.version_info[0] == 3

# exec (from https://bitbucket.org/gutworth/six/):
if PY3:
    import builtins
    exec_ = getattr(builtins, "exec")
    del builtins
else:
    def exec_(_code_, _globs_=None, _locs_=None):
        """Execute code in a namespace."""
        if _globs_ is None:
            frame = sys._getframe(1)
            _globs_ = frame.f_globals
            if _locs_ is None:
                _locs_ = frame.f_locals
            del frame
        elif _locs_ is None:
            _locs_ = _globs_
        exec("""exec _code_ in _globs_, _locs_""")

# ============================================================

CO_GENERATOR = 0x0020

def is_generator(f):
    """ Return True if a function is a generator.
    """
    isgen = (f.__code__.co_flags & CO_GENERATOR) != 0
    return isgen

class LineProfiler(CLineProfiler):
    """ A profiler that records the execution times of individual lines.
    """

    def __call__(self, func):
        """ Decorate a function to start the profiler on function entry and stop
        it on function exit.
        """
        self.add_function(func)
        if is_generator(func):
            wrapper = self.wrap_generator(func)
        else:
            wrapper = self.wrap_function(func)
        return wrapper

    def wrap_generator(self, func):
        """ Wrap a generator to profile it.
        """
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            g = func(*args, **kwds)
            # The first iterate will not be a .send()
            self.enable_by_count()
            try:
                item = next(g)
            finally:
                self.disable_by_count()
            input = (yield item)
            # But any following one might be.
            while True:
                self.enable_by_count()
                try:
                    item = g.send(input)
                finally:
                    self.disable_by_count()
                input = (yield item)
        return wrapper

    def wrap_function(self, func):
        """ Wrap a function to profile it.
        """
        @functools.wraps(func)
        def wrapper(*args, **kwds):
            self.enable_by_count()
            try:
                result = func(*args, **kwds)
            finally:
                self.disable_by_count()
            return result
        return wrapper

    def dump_stats(self, filename):
        """ Dump a representation of the data to a file as a pickled LineStats
        object from `get_stats()`.
        """
        lstats = self.get_stats()
        with open(filename, 'wb') as f:
            pickle.dump(lstats, f, pickle.HIGHEST_PROTOCOL)

    def print_stats(self, stream=None, stripzeros=False, sort_by_total_time=False):
        """ Show the gathered statistics.
        """
        lstats = self.get_stats()
        show_text(
            lstats.timings,
            lstats.unit,
            stream=stream,
            stripzeros=stripzeros,
            sort_by_total_time=sort_by_total_time
        )

    def run(self, cmd):
        """ Profile a single executable statment in the main namespace.
        """
        import __main__
        main_dict = __main__.__dict__
        return self.runctx(cmd, main_dict, main_dict)

    def runctx(self, cmd, globals, locals):
        """ Profile a single executable statement in the given namespaces.
        """
        self.enable_by_count()
        try:
            exec_(cmd, globals, locals)
        finally:
            self.disable_by_count()
        return self

    def runcall(self, func, *args, **kw):
        """ Profile a single function call.
        """
        self.enable_by_count()
        try:
            return func(*args, **kw)
        finally:
            self.disable_by_count()

    def add_module(self, mod):
        """ Add all the functions in a module and its classes.
        """
        from inspect import isclass, isfunction

        nfuncsadded = 0
        for item in mod.__dict__.values():
            if isclass(item):
                for k, v in item.__dict__.items():
                    if isfunction(v):
                        self.add_function(v)
                        nfuncsadded += 1
            elif isfunction(item):
                self.add_function(item)
                nfuncsadded += 1

        return nfuncsadded

def show_func(filename, start_lineno, func_name, timings, unit, stream=None, stripzeros=False):
    """ Show results for a single function.
    """
    if stream is None:
        stream = sys.stdout

    template = '%6s %9s %12s %8s %8s  %-s'
    d = {}
    total_time = 0.0
    linenos = []
    for lineno, nhits, time in timings:
        total_time += time
        linenos.append(lineno)

    if stripzeros and total_time == 0:
        return

    stream.write("Total time: %g s\n" % (total_time * unit))
    if os.path.exists(filename) or filename.startswith("<ipython-input-"):
        stream.write("File: %s\n" % filename)
        stream.write("Function: %s at line %s\n" % (func_name, start_lineno))
        if os.path.exists(filename):
            # Clear the cache to ensure that we get up-to-date results.
            linecache.clearcache()
        all_lines = linecache.getlines(filename)
        sublines = inspect.getblock(all_lines[start_lineno-1:])
    else:
        stream.write("\n")
        stream.write("Could not find file %s\n" % filename)
        stream.write("Are you sure you are running this program from the same directory\n")
        stream.write("that you ran the profiler from?\n")
        stream.write("Continuing without the function's contents.\n")
        # Fake empty lines so we can see the timings, if not the code.
        nlines = max(linenos) - min(min(linenos), start_lineno) + 1
        sublines = [''] * nlines
    for lineno, nhits, time in timings:
        d[lineno] = (nhits, time, '%5.1f' % (float(time) / nhits),
            '%5.1f' % (100*time / total_time))
    linenos = range(start_lineno, start_lineno + len(sublines))
    empty = ('', '', '', '')
    header = template % ('Line #', 'Hits', 'Time', 'Per Hit', '% Time',
        'Line Contents')
    stream.write("\n")
    stream.write(header)
    stream.write("\n")
    stream.write('=' * len(header))
    stream.write("\n")
    for lineno, line in zip(linenos, sublines):
        nhits, time, per_hit, percent = d.get(lineno, empty)
        txt = template % (lineno, nhits, time, per_hit, percent,
                          line.rstrip('\n').rstrip('\r'))
        stream.write(txt)
        stream.write("\n")
    stream.write("\n")

def show_text(stats, unit, stream=None, stripzeros=False, sort_by_total_time=False):
    """ Show text for the given timings.
    """
    if stream is None:
        stream = sys.stdout

    stream.write('Timer unit: %g s\n\n' % unit)
    if sort_by_total_time:
        stats_to_print = sorted(stats.items(), key=lambda x: sum([v[2] for v in x[1]]))
    else:
        stats_to_print = sorted(stats.items())
    for (fn, lineno, name), timings in stats_to_print:
        show_func(fn, lineno, name, stats[fn, lineno, name], unit, stream=stream, stripzeros=stripzeros)

# A %lprun magic for IPython.
def magic_lprun(self, parameter_s=''):
    """ Execute a statement under the line-by-line profiler from the
    line_profiler module.

    Usage:
      %lprun -f func1 -f func2 <statement>

    The given statement (which doesn't require quote marks) is run via the
    LineProfiler. Profiling is enabled for the functions specified by the -f
    options. The statistics will be shown side-by-side with the code through the
    pager once the statement has completed.

    Options:

    -f <function>: LineProfiler only profiles functions and methods it is told
    to profile.  This option tells the profiler about these functions. Multiple
    -f options may be used. The argument may be any expression that gives
    a Python function or method object. However, one must be careful to avoid
    spaces that may confuse the option parser. Additionally, functions defined
    in the interpreter at the In[] prompt or via %run currently cannot be
    displayed.  Write these functions out to a separate file and import them.

    -m <module>: Get all the functions/methods in a module

    One or more -f or -m options are required to get any useful results.

    -D <filename>: dump the raw statistics out to a pickle file on disk. The
    usual extension for this is ".lprof". These statistics may be viewed later
    by running line_profiler.py as a script.

    -T <filename>: dump the text-formatted statistics with the code side-by-side
    out to a text file.

    -r: return the LineProfiler object after it has completed profiling.

    -s: strip out all entries from the print-out that have zeros.
    """
    # Local imports to avoid hard dependency.
    from distutils.version import LooseVersion
    import IPython
    ipython_version = LooseVersion(IPython.__version__)
    if ipython_version < '0.11':
        from IPython.genutils import page
        from IPython.ipstruct import Struct
        from IPython.ipapi import UsageError
    else:
        from IPython.core.page import page
        from IPython.utils.ipstruct import Struct
        from IPython.core.error import UsageError

    # Escape quote markers.
    opts_def = Struct(D=[''], T=[''], f=[], m=[])
    parameter_s = parameter_s.replace('"', r'\"').replace("'", r"\'")
    opts, arg_str = self.parse_options(parameter_s, 'rsf:m:D:T:', list_all=True)
    opts.merge(opts_def)

    global_ns = self.shell.user_global_ns
    local_ns = self.shell.user_ns

    # Get the requested functions.
    funcs = []
    for name in opts.f:
        try:
            funcs.append(eval(name, global_ns, local_ns))
        except Exception as e:
            raise UsageError('Could not find function %r.\n%s: %s' % (name,
                e.__class__.__name__, e))

    profile = LineProfiler(*funcs)

    # Get the modules, too
    for modname in opts.m:
        try:
            mod = __import__(modname, fromlist=[''])
            profile.add_module(mod)
        except Exception as e:
            raise UsageError('Could not find module %r.\n%s: %s' % (name,
                e.__class__.__name__, e))

    # Add the profiler to the builtins for @profile.
    if PY3:
        import builtins
    else:
        import __builtin__ as builtins

    if 'profile' in builtins.__dict__:
        had_profile = True
        old_profile = builtins.__dict__['profile']
    else:
        had_profile = False
        old_profile = None
    builtins.__dict__['profile'] = profile

    try:
        try:
            profile.runctx(arg_str, global_ns, local_ns)
            message = ''
        except SystemExit:
            message = """*** SystemExit exception caught in code being profiled."""
        except KeyboardInterrupt:
            message = ("*** KeyboardInterrupt exception caught in code being "
                "profiled.")
    finally:
        if had_profile:
            builtins.__dict__['profile'] = old_profile

    # Trap text output.
    stdout_trap = StringIO()
    profile.print_stats(stdout_trap, stripzeros='s' in opts)
    output = stdout_trap.getvalue()
    output = output.rstrip()

    if ipython_version < '0.11':
        page(output, screen_lines=self.shell.rc.screen_length)
    else:
        page(output)
    print(message, end="")

    dump_file = opts.D[0]
    if dump_file:
        profile.dump_stats(dump_file)
        print('\n*** Profile stats pickled to file %r. %s' % (
            dump_file, message))

    text_file = opts.T[0]
    if text_file:
        pfile = open(text_file, 'w')
        pfile.write(output)
        pfile.close()
        print('\n*** Profile printout saved to text file %r. %s' % (
            text_file, message))

    return_value = None
    if 'r' in opts:
        return_value = profile

    return return_value

def load_ipython_extension(ip):
    """ API for IPython to recognize this module as an IPython extension.
    """
    ip.define_magic('lprun', magic_lprun)

def load_stats(filename):
    """ Utility function to load a pickled LineStats object from a given
    filename.
    """
    with open(filename, 'rb') as f:
        return pickle.load(f)

def main():
    usage = "usage: %prog profile.lprof"
    parser = optparse.OptionParser(usage=usage, version='%prog 1.0b2')

    options, args = parser.parse_args()
    if len(args) != 1:
        parser.error("Must provide a filename.")
    lstats = load_stats(args[0])
    show_text(lstats.timings, lstats.unit)

if __name__ == '__main__':
    main()


text:
<?php
namespace Aditus\Form;

use Doctrine\Common\Persistence\ObjectManager;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Form;
use Aditus\Form\AssessmentDetailsFieldset;

class AssessmentDetailsForm extends Form
{
    public function __construct(ObjectManager $objectManager)
    {
        parent::__construct('assessment-details-form');

        // The form will hydrate an object of type "Assessments"
        $this->setHydrator(new DoctrineHydrator($objectManager));

        // Add the user fieldset, and set it as the base fieldset
        $assessmentDetailsFieldset = new AssessmentDetailsFieldset($objectManager);
        $assessmentDetailsFieldset->setUseAsBaseFieldset(true);
        $this->add($assessmentDetailsFieldset);

        // … add CSRF and submit elements …

        // Optionally set your validation group here
    }
}


text:
libraryinit(acno)
function main() {
	return RECORD.a(5) ^ VM ^ RECORD.a(6);
}
libraryexit(acno)

libraryinit(authorised)
#include <authorised.h>
#include <validcode2.h>
var positive;
var msg;
function main() {

	//ALLOWPARTIALACCESS
	//market code is not currently data entered in suppliers but validate it anyway
	ANS = 0;

	if (authorised("MEDIA/PRODUCTION TYPE ACCESS", msg)) {
		positive = "";
	}else{
		positive = "#";
	}

	if (authorised(positive ^ "MEDIA/PRODUCTION TYPE ACCESS " ^ ID.quote(), msg )) {
		var compcode = calculate("company_code");
		if (compcode) {
			var xx;
			if (validcode2(compcode, "", "", xx, msg)) {
				ANS = 1;
			}
		}else{
			ANS = 1;
		}
	}
	//also check access to group (perhaps this should be checked first for speed)
	if (ANS) {
		if (not(authorised(positive ^ "MEDIA/PRODUCTION TYPE ACCESS " ^ RECORD.a(10).quote(), msg ))) {
			ANS = 0;
		}
	}
	return ANS;
}
libraryexit(authorised)

libraryinit(cost_accname)
function main() {
	return RECORD.a(6, 1, 2).xlate("ACCOUNTS", 1, "X");
}
libraryexit(cost_accname)

libraryinit(cost_acno2)
function main() {
	return RECORD.a(6, 1, 1);
}
libraryexit(cost_acno2)

libraryinit(cost_tax_acno2)
function main() {
	return RECORD.a(14, 1, 1);
}
libraryexit(cost_tax_acno2)

libraryinit(group_code)
function main() {
	ANS = RECORD.a(10);
	if (not ANS) {
		ANS = ID;
	}
	return ANS;
}
libraryexit(group_code)

libraryinit(group_name)
function main() {
	if (RECORD.a(10) == "") {
		return RECORD.a(1);
	}else{
		return RECORD.a(10).xlate("JOB_TYPES", 1, "X");
	}
}
libraryexit(group_name)

libraryinit(has_accs)
function main() {
	return (RECORD.a(5) ^ RECORD.a(6)) ne "";
}
libraryexit(has_accs)

libraryinit(income_accname)
function main() {
	return RECORD.a(5, 1, 2).xlate("ACCOUNTS", 1, "X");
}
libraryexit(income_accname)

libraryinit(income_account_seq)
function main() {
	return RECORD.a(5, 1, 2).xlate("ACCOUNTS", 26, "X");
}
libraryexit(income_account_seq)

libraryinit(income_acno2)
function main() {
	return RECORD.a(5, 1, 1);
}
libraryexit(income_acno2)

libraryinit(mjt)
function main() {
	if (RECORD.a(12)) {
		return "T";
	}
	if (RECORD.a(3) == "Y") {
		return "J";
	}else{
		return "M";
	}
}
libraryexit(mjt)

libraryinit(rawname)
function main() {
	return RECORD.a(1).ucase().convert("\'" " \".,/-", "");
}
libraryexit(rawname)

libraryinit(tax_acno2)
function main() {
	return RECORD.a(13, 1, 1);
}
libraryexit(tax_acno2)

libraryinit(year_period)
function main() {
	return "";
}
libraryexit(year_period)


text: Example API built using Express routers


text:
package org.swiften.xtestkit.android.type;

import org.jetbrains.annotations.NotNull;

/**
 * Created by haipham on 4/9/17.
 */
public interface DeviceUIDProviderType {
    @NotNull String deviceUID();
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BasecampAPI;

namespace Scout
{
	public partial class AddListDialog : BaseDialog
	{
		Project project;

		public AddListDialog()
			: this(null)
		{
		}

		public AddListDialog(Project project)
		{
			InitializeComponent();

			if (project != null)
			{
				this.project = project;
				comboBox1.Items.Add("NONE");

				List<Milestone> stones = project.GetMilestones();
				comboBox1.Items.AddRange(stones.ToArray());
				comboBox1.SelectedIndex = 0;
				ok.Click += new EventHandler(ok_Click);
			}
			else
			{
				ok.Enabled = false;
			}

			comboBox1.Enabled = comboBox1.Items.Count > 1;
		}

		public ToDoList NewList;

		void ok_Click(object sender, EventArgs e)
		{
			if (title.Text.Trim().Length == 0)
			{
				MessageBox.Show("Please enter a title for the list.");
				title.Select();
				return;
			}

			NewList = project.CreateToDoList(title.Text.Trim(), string.Empty, comboBox1.SelectedItem as Milestone);
			Close();
		}
	}
}


text:
import unittest
import mock

from google.datalab.contrib.pipeline.composer._composer import Composer

class TestCases(unittest.TestCase):

  @mock.patch('google.datalab.Context.default')
  @mock.patch('google.datalab.storage.Bucket')
  @mock.patch('google.datalab.contrib.pipeline.composer._api.Api.get_environment_details')
  def test_deploy(self, mock_environment_details, mock_bucket_class, mock_default_context):
      # Happy path
      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs://foo_bucket/dags'
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      test_composer.deploy('foo_name', 'foo_dag_string')
      mock_bucket_class.assert_called_with('foo_bucket')
      mock_bucket_class.return_value.object.assert_called_with('dags/foo_name.py')
      mock_bucket_class.return_value.object.return_value.write_stream.assert_called_with(
          'foo_dag_string', 'text/plain')

      # Only bucket with no path
      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs://foo_bucket'
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      test_composer.deploy('foo_name', 'foo_dag_string')
      mock_bucket_class.assert_called_with('foo_bucket')
      mock_bucket_class.return_value.object.assert_called_with('foo_name.py')
      mock_bucket_class.return_value.object.return_value.write_stream.assert_called_with(
          'foo_dag_string', 'text/plain')

      # GCS dag location has additional parts
      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs://foo_bucket/foo_random/dags'
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      test_composer.deploy('foo_name', 'foo_dag_string')
      mock_bucket_class.assert_called_with('foo_bucket')
      mock_bucket_class.return_value.object.assert_called_with('foo_random/dags/foo_name.py')
      mock_bucket_class.return_value.object.return_value.write_stream.assert_called_with(
          'foo_dag_string', 'text/plain')

  @mock.patch('google.datalab.contrib.pipeline.composer._api.Api.get_environment_details')
  def test_gcs_dag_location(self, mock_environment_details):
      # Composer returns good result
      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs://foo_bucket/dags'
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      self.assertEqual('gs://foo_bucket/dags/', test_composer.gcs_dag_location)

      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs://foo_bucket'  # only bucket
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      self.assertEqual('gs://foo_bucket/', test_composer.gcs_dag_location)

      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs://foo_bucket/'  # with trailing slash
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      self.assertEqual('gs://foo_bucket/', test_composer.gcs_dag_location)

      # Composer returns empty result
      mock_environment_details.return_value = {}
      test_composer = Composer('foo_zone', 'foo_environment')
      with self.assertRaisesRegexp(
              ValueError, 'Dag location unavailable from Composer environment foo_environment'):
        test_composer.gcs_dag_location

      # Composer returns empty result
      mock_environment_details.return_value = {
        'config': {}
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      with self.assertRaisesRegexp(
              ValueError, 'Dag location unavailable from Composer environment foo_environment'):
        test_composer.gcs_dag_location

      # Composer returns None result
      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': None
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      with self.assertRaisesRegexp(
              ValueError,
              'Dag location None from Composer environment foo_environment is in incorrect format'):
        test_composer.gcs_dag_location

      # Composer returns incorrect formats
      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'gs:/foo_bucket'
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      with self.assertRaisesRegexp(
              ValueError,
              ('Dag location gs:/foo_bucket from Composer environment foo_environment is in'
               ' incorrect format')):
        test_composer.gcs_dag_location

      mock_environment_details.return_value = {
        'config': {
          'gcsDagLocation': 'as://foo_bucket'
        }
      }
      test_composer = Composer('foo_zone', 'foo_environment')
      with self.assertRaisesRegexp(
              ValueError,
              ('Dag location as://foo_bucket from Composer environment foo_environment is in'
               ' incorrect format')):
        test_composer.gcs_dag_location


text:
Various reflected attacks used in DDoS. Simple proof of concepts for lab demos.

## Requirements ##

*	Python
*	Scapy (2.3.x)

## dns.py / dns6.py ##

Uses spoofed packets to request large responses from a recursive/cacheing DNS server.

## ntp.py / ntp6.py ##

Uses spoofed packets to request monlist from affected NTP servers.

## snmp.py / snmp6.py ##

Uses spoofed packets to make large snmpbulk requests from a server.

*	Uses logic from http://www.prolexic.com/kcresources/white-paper/white-paper-snmp-ntp-chargen-reflection-attacks-drdos/analysis-of-drdos-dns-reflection-white-paper_i.html
*	Uses improved request from http://www.nothink.org/misc/snmp_reflected.php

## Disclaimer ##

This information is provided to assist network administrators in defending their own networks. It is not intended to assist with DoSing remote sites or exploiting services on those sites, or for information gathering purposes beyond those allowed by law. I hereby disclaim any responsibility for actions taken based upon the code in this package, and urge all who seek information towards a destructive end to reconsider their life, and do something constructive instead.

Obviously these tools can be disruptive if not used in a lab environment. My arguement for having them public is, if the bad guys are already doing this, they already know how. We all need to be able to test equipment under these types of load, this code is a place to start testing them under.


text:
@interface TWCollectionViewCell: UICollectionViewCell
@property (strong, nonatomic) UILabel *label;
@end
@implementation TWCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.label = [[UILabel alloc] init];
        [self.contentView addSubview:self.label];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.label.frame = self.contentView.bounds;
}

@end

static NSString *const kCollectionViewCellIdent = @"kCollectionViewCellIdent";

@interface TWViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation TWViewController
{
    UICollectionView *_collectionView;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

	// Do any additional setup after loading the view, typically from a nib.
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc] init];
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowlayout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[TWCollectionViewCell class]
        forCellWithReuseIdentifier:kCollectionViewCellIdent];
    [self.view addSubview:_collectionView];

#ifdef BUG_ON
    UILabel *label = [[UILabel alloc] init];
    label.text = @"ERROR / Bug: This should not be empty or white here.\nYou shoud see the rows for section 1. Scroll down to see SOME rows (starting with 9) of section 1.\nSection 0 has one row with height of 0.\n\n\n You can select the Scheme UseWorkaround to see how it should look like. The workaround makes a height of 0.1 for the 1st row in the 1st section";
    label.numberOfLines = 0;
    [label sizeToFit];
    label.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    label.frame = self.view.bounds;
    [self.view addSubview:label];
#endif

}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
            return 1;
            break;
        case 1:
            return 20;
            break;

        default:
            break;
    }

    return 0;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 0.0f;
    switch (indexPath.section) {
        case 0:
            break;
        case 1:
            height = 50.0f;
            break;
        default:
            break;
    }

#ifdef BUG_WORKAROUND
    if (height == 0.0f) {
        height = 0.1f;
    }
#endif

    return CGSizeMake(collectionView.bounds.size.width, height);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TWCollectionViewCell *cell = (TWCollectionViewCell*)[collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCellIdent forIndexPath:indexPath];

    cell.layer.borderWidth = 1.0;
    cell.layer.borderColor = [UIColor blackColor].CGColor;

    switch (indexPath.section) {
        case 0:
            cell.backgroundColor = [UIColor yellowColor];
            break;
        case 1:
            cell.backgroundColor = [UIColor darkGrayColor];
            break;

        default:
            break;
    }

    cell.label.text = [NSString stringWithFormat:@"section: %ld, row: %ld", (long)indexPath.section, indexPath.row];

    return cell;
}

@end


text:
package com.jonatasleon.pokedex;

import com.google.gson.annotations.SerializedName;

/**
 * Created by jonatasleon on 25/03/17.
 */

public class Sprite {

    @SerializedName("name")
    private String name;

    @SerializedName("resource_uri")
    private String resourceUri;

    public Sprite(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getResourceUri() {
        return resourceUri.substring(1);
    }

    public void setResourceUri(String resourceUri) {
        this.resourceUri = resourceUri;
    }
}


text:
<?php

/**
 * Smarty Method LoadFilter
 *
 * Smarty::loadFilter() method
 *
 * @package    Smarty
 * @subpackage PluginsInternal
 * @author     Uwe Tews
 */
class Smarty_Internal_Method_LoadFilter
{
    /**
     * Valid for Smarty and template object
     *
     * @var int
     */
    public $objMap = 3;

    /**
     * Valid filter types
     *
     * @var array
     */
    private $filterTypes = array('pre' => true, 'post' => true, 'output' => true, 'variable' => true);

    /**
     * load a filter of specified type and name
     *
     * @api  Smarty::loadFilter()
     *
     * @link https://www.smarty.net/docs/en/api.load.filter.tpl
     *
     * @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
     * @param string                                                          $type filter type
     * @param string                                                          $name filter name
     *
     * @return bool
     * @throws SmartyException if filter could not be loaded
     */
    public function loadFilter(Smarty_Internal_TemplateBase $obj, $type, $name)
    {
        $smarty = $obj->_getSmartyObj();
        $this->_checkFilterType($type);
        $_plugin = "smarty_{$type}filter_{$name}";
        $_filter_name = $_plugin;
        if (is_callable($_plugin)) {
            $smarty->registered_filters[ $type ][ $_filter_name ] = $_plugin;
            return true;
        }
        if ($smarty->loadPlugin($_plugin)) {
            if (class_exists($_plugin, false)) {
                $_plugin = array($_plugin, 'execute');
            }
            if (is_callable($_plugin)) {
                $smarty->registered_filters[ $type ][ $_filter_name ] = $_plugin;
                return true;
            }
        }
        throw new SmartyException("{$type}filter '{$name}' not found or callable");
    }

    /**
     * Check if filter type is valid
     *
     * @param string $type
     *
     * @throws \SmartyException
     */
    public function _checkFilterType($type)
    {
        if (!isset($this->filterTypes[ $type ])) {
            throw new SmartyException("Illegal filter type '{$type}'");
        }
    }
}


text:
WORLD_BEGIN_C_DECLS

// Commands for FFT (This is the same as FFTW)
#define FFT_FORWARD 1
#define FFT_BACKWARD 2
#define FFT_ESTIMATE 3

// Complex number for FFT
typedef double fft_complex[2];
// Struct used for FFT
typedef struct {
  int n;
  int sign;
  unsigned int flags;
  fft_complex *c_in;
  double *in;
  fft_complex *c_out;
  double *out;
  double *input;
  int *ip;
  double *w;
} fft_plan;

fft_plan fft_plan_dft_1d(int n, fft_complex *in, fft_complex *out, int sign,
  unsigned int flags);
fft_plan fft_plan_dft_c2r_1d(int n, fft_complex *in, double *out,
  unsigned int flags);
fft_plan fft_plan_dft_r2c_1d(int n, double *in, fft_complex *out,
  unsigned int flags);
void fft_execute(fft_plan p);
void fft_destroy_plan(fft_plan p);

WORLD_END_C_DECLS

#endif  // WORLD_FFT_H_


text:
<?php

namespace Hostnet\Bundle\FormHandlerBundle\Functional;

use Hostnet\Bundle\FormHandlerBundle\Functional\Fixtures\HandlerType\FullFormHandler;
use Hostnet\Bundle\FormHandlerBundle\Functional\Fixtures\HandlerType\FullFormHandler27;
use Hostnet\Bundle\FormHandlerBundle\Functional\Fixtures\TestData;
use Hostnet\Bundle\FormHandlerBundle\Functional\Fixtures\TestKernel;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Kernel;

class HandlerTest extends KernelTestCase
{
    /**
     * BC for current tests, new tests should get their own config.
     */
    protected function setUp()
    {
        static::bootKernel(['config_file' => TestKernel::getLegacyConfigFilename()]);
    }

    protected static function createKernel(array $options = array())
    {
        return new TestKernel($options);
    }

    public function testValid()
    {
        if (Kernel::VERSION_ID < 20800) {
            self::markTestSkipped(sprintf('Symfony version %s not supported by test', Kernel::VERSION));
        }

        $container       = self::$kernel->getContainer();
        $handler_factory = $container->get('hostnet.form_handler.factory');
        $request         = Request::create('/', 'POST', ['test' => ['test' => 'foobar']]);

        $handler = $handler_factory->create(FullFormHandler::class);
        $data    = new TestData();

        $response = $handler->handle($request, $data);

        self::assertInstanceOf(RedirectResponse::class, $response);
        self::assertEquals('http://success.nl/', $response->getTargetUrl());
    }

    public function testInvalid()
    {
        if (Kernel::VERSION_ID < 20800) {
            self::markTestSkipped(sprintf('Symfony version %s not supported by test', Kernel::VERSION));
        }

        $container       = self::$kernel->getContainer();
        $handler_factory = $container->get('hostnet.form_handler.factory');
        $request         = Request::create('/', 'POST', ['test' => ['test' => null]]);

        $handler = $handler_factory->create(FullFormHandler::class);
        $data    = new TestData();

        $response = $handler->handle($request, $data);

        self::assertInstanceOf(RedirectResponse::class, $response);
        self::assertEquals('http://failure.nl/', $response->getTargetUrl());
    }

    /**
     * @group legacy
     */
    public function testValid27()
    {
        if (Kernel::VERSION_ID >= 30000) {
            self::markTestSkipped(sprintf('Symfony version %s not supported by test', Kernel::VERSION));
        }

        $container       = self::$kernel->getContainer();
        $handler_factory = $container->get('hostnet.form_handler.factory');
        $request         = Request::create('/', 'POST', ['test' => ['test' => 'foobar']]);

        $handler = $handler_factory->create(FullFormHandler27::class);
        $data    = new TestData();

        $response = $handler->handle($request, $data);

        self::assertInstanceOf(RedirectResponse::class, $response);
        self::assertEquals('http://success.nl/', $response->getTargetUrl());
    }

    /**
     * @group legacy
     */
    public function testInvalid27()
    {
        if (Kernel::VERSION_ID >= 30000) {
            self::markTestSkipped(sprintf('Symfony version %s not supported by test', Kernel::VERSION));
        }

        $container       = self::$kernel->getContainer();
        $handler_factory = $container->get('hostnet.form_handler.factory');
        $request         = Request::create('/', 'POST', ['test' => ['test' => null]]);

        $handler = $handler_factory->create(FullFormHandler27::class);
        $data    = new TestData();

        $response = $handler->handle($request, $data);

        self::assertInstanceOf(RedirectResponse::class, $response);
        self::assertEquals('http://failure.nl/', $response->getTargetUrl());
    }
}


text:
package ru.job4j.condition;

import org.junit.Test;

import static org.junit.Assert.assertTrue;
/**
*Test проверяет точку в системе координат.
* @author Aleksey Kostiukov (mailto:kostiukovaleskej@gmail.com)
* @version 1
* @since 24.07.2017
*/
public class PointTest {
  /**
     * Test add.
     */
   @Test
public void whenZeroAndTwoThenTrue() {
    Point p = new Point(1, 2);
    boolean result = p.is(0, 2);
    assertTrue(result);
  }
}