text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content">
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?myAttr"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?otherAttr"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="<error>?unknown</error>"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?attr/myAttr"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="<error>?attr/unknown</error>"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="<error>@attr/myAttr</error>"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="<error>@myAttr</error>"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/myDrawable"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="<error>?drawable/myDrawable</error>"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:text"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="<error>?android:unknown</error>"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?android:attr/text"/>
  <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="</error>?android:attr/unknown</error>"/>
</LinearLayout>


text:
package shinylearner.helper;

import java.util.*;

/** This class contains helper methods for dealing with Java collections and lists. Many of these implement functionality that circumvents some of the awkwardness and verbostity of dealing with lists in Java.
 * @author Stephen Piccolo
 */
public class ListUtilities
{
    /** Converts an array of String objects to a list of String objects.
     *
     * @param values Array of String objects
     * @return List of String objects
     */
    public static ArrayList<String> CreateStringList(String... values)
    {
        ArrayList<String> results = new ArrayList<String>();
        if (values.length > 0)
            Collections.addAll(results, values);
        return results;
    }

    /** Converts a generic collection of objects into a list of String objects.
     *
     * @param values Collection of objects
     * @return List of String objects
     */
    public static ArrayList<String> CreateStringList(Collection<String> values)
    {
        ArrayList<String> results = new ArrayList<String>();

        for (Object value : values)
            results.add(String.valueOf(value));

        return results;
    }

    /** Finds the intersection between two lists of String objects.
     *
     * @param list1 First list
     * @param list2 Second list
     * @return Intersection list (contains values that exist in both lists)
     */
    public static ArrayList<String> Intersect(ArrayList<String> list1, ArrayList<String> list2)
    {
        if (list1.size() == 0)
            return list2;

        Set<String> intersection = new HashSet<String>(list1);
        intersection.retainAll(new HashSet<String>(list2));
        return new ArrayList<String>(intersection);
    }

    /** This method converts a list of String objects to a single String representation and inserts a delimiter between each object.
     *
     * @param list List of String objects
     * @param delimiter Delimiter
     * @return Formatted String representation
     */
    public static String Join(ArrayList<String> list, String delimiter)
    {
        if (list.isEmpty())
            return "";

        StringBuilder sb = new StringBuilder();

        for (String x : list)
            sb.append(x + delimiter);

        sb.delete(sb.length() - delimiter.length(), sb.length());

        return sb.toString();
    }

    /** Convenience methods that makes it easier to sort a collection
     *
     * @param list Collection to sort
     * @return Sorted list
     */
    public static ArrayList<String> Sort(Collection<String> list)
    {
        ArrayList<String> newList = new ArrayList<String>(list);
        Collections.sort(newList);
        return newList;
    }

    /** Convenience methods that makes it easier to sort a String list
     *
     * @param list List to sort
     * @return Sorted list
     */
	public static ArrayList<String> SortStringList(ArrayList<String> list)
    {
    	return (ArrayList<String>)Sort(list);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.eclipse.bpel.validator.wsdl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.eclipse.bpel.validator.IBPELMarker;
import org.eclipse.bpel.validator.ModelQuery;
import org.eclipse.bpel.validator.model.ARule;
import org.eclipse.bpel.validator.model.IModelQuery;
import org.eclipse.bpel.validator.model.INode;
import org.eclipse.bpel.validator.model.IProblem;
import org.eclipse.bpel.validator.model.Validator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.wst.wsdl.Definition;
import org.eclipse.wst.wsdl.Import;
import org.eclipse.wst.wsdl.internal.impl.ImportImpl;
import org.eclipse.wst.wsdl.util.WSDLParser;
import org.eclipse.xsd.XSDSchema;
import org.eclipse.xsd.XSDSchemaContent;
import org.eclipse.xsd.impl.XSDImportImpl;
import org.eclipse.xsd.impl.XSDIncludeImpl;
import org.eclipse.xsd.util.XSDParser;
import org.w3c.dom.Node;

/**
 * This thing exists here just for the benefit of the property and property
 * alias validators.
 *
 * @author Michal Chmielewski (michal.chmielewski@oracle.com)
 *
 */

public class Definitions extends Validator {

	// https://bugs.eclipse.org/bugs/show_bug.cgi?id=330813
	// https://jira.jboss.org/browse/JBIDE-7116
	// Added <import> location checking: missing XSD imports are not reported by WSDL validator!

	@ARule(
			sa = -1,
			desc = "Check WSDL definition",
			author = "michal.chmielewski@oracle.com",
			date = "02/15/2007",
			errors="BPELC_IMPORT__UNRESOVED"
		)
	protected void start() {
		super.start();

		Definition definition = (Definition)mModelQuery.adapt(mNode,EObject.class,ModelQuery.ADAPT_HINT_NONE);
		List<EObject> unresolved = findUnresolvedImports(definition);

		for (EObject obj : unresolved) {
			String location = "unkonwn";
			// https://bugs.eclipse.org/bugs/show_bug.cgi?id=330813
			// https://jira.jboss.org/browse/JBIDE-7107
			// line/column gathering was moved to ModelQuery class
			if (obj instanceof Import) {
				location = ((Import)obj).getLocationURI();
			}
			else if ( obj instanceof XSDImportImpl ) {
				location = ((XSDImportImpl)obj).getSchemaLocation();
			}
			else if ( obj instanceof XSDIncludeImpl ) {
				location = ((XSDIncludeImpl)obj).getSchemaLocation();
			}

			IProblem problem = createWarning( (INode)mModelQuery.adapt(obj,INode.class,IModelQuery.ADAPT_HINT_NONE) );

			problem.fill("BPELC_IMPORT__UNRESOVED",  //$NON-NLS-1$
					toString(mNode.nodeName()),
					location, // location of the unresolved document being imported
					definition.getLocation()); // location of document doing the importing
		}
	}

    @SuppressWarnings({ "restriction", "unchecked", "rawtypes" })
	protected List<EObject> findUnresolvedImports(Definition definition) {
    	if (definition == null) {
        	return Collections.emptyList();
        }

    	IAdapterManager adapterManager = Platform.getAdapterManager();
    	IFile file = (IFile)adapterManager.getAdapter(definition, IResource.class);
		if (file!=null && file.exists())
			try {
				file.deleteMarkers(IBPELMarker.ID, false, IResource.DEPTH_INFINITE);
//				System.out.println("deleted markers from "+file);
			} catch (CoreException e) {
				e.printStackTrace();
			}

        ArrayList<EObject> imports = new ArrayList<EObject>();
        if (definition.getImports() != null) {
        	Iterator defImp = definition.getImports().values().iterator();
        	while (defImp.hasNext()) {
        		List impList = (List) defImp.next();
        		for (int i=0; i<impList.size(); i++) {
					ImportImpl wsdlImport = (ImportImpl) impList.get(i);
        			wsdlImport.importDefinitionOrSchema();
        			XSDSchema schema = wsdlImport.getESchema();
        			Definition wsdlDefinition = wsdlImport.getEDefinition();
        			if (schema==null && wsdlDefinition==null)
        				imports.add(wsdlImport);
        			// only look at top-level imports to avoid multiple reports of the same problem
					imports.addAll(findUnresolvedImports(wsdlDefinition));
        		}
        	}
        }
        if (definition.getETypes() != null) {
			List<XSDSchema> schemas = definition.getETypes().getSchemas();
        	for (XSDSchema si : schemas) {
        		for (XSDSchemaContent sc : si.getContents()) {
        			if (sc instanceof XSDIncludeImpl) {
        				XSDIncludeImpl inc = (XSDIncludeImpl)sc;
        				inc.getIncorporatedSchema();
        				if (inc.getResolvedSchema() == null)
        					imports.add(inc);
        			}
        			if (sc instanceof XSDImportImpl) {
        				XSDImportImpl imp = (XSDImportImpl)sc;
        				imp.importSchema();
        				if (imp.getResolvedSchema() == null)
        					imports.add(imp);
        			}
        		}
        	}
        }

        return imports;
    }
}


text:
import django.contrib.postgres.fields
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("councils", "0005_geom_not_geog"),
    ]

    operations = [
        migrations.RenameField(
            model_name="council",
            old_name="address",
            new_name="electoral_services_address",
        ),
        migrations.RenameField(
            model_name="council",
            old_name="email",
            new_name="electoral_services_email",
        ),
        migrations.RenameField(
            model_name="council",
            old_name="postcode",
            new_name="electoral_services_postcode",
        ),
        migrations.RenameField(
            model_name="council",
            old_name="website",
            new_name="electoral_services_website",
        ),
        migrations.RemoveField(
            model_name="council",
            name="phone",
        ),
        migrations.AddField(
            model_name="council",
            name="electoral_services_phone_numbers",
            field=django.contrib.postgres.fields.ArrayField(
                base_field=models.CharField(max_length=100), default=list, size=None
            ),
        ),
        migrations.AddField(
            model_name="council",
            name="identifiers",
            field=django.contrib.postgres.fields.ArrayField(
                base_field=models.CharField(max_length=100), default=list, size=None
            ),
        ),
        migrations.AddField(
            model_name="council",
            name="registration_address",
            field=models.TextField(blank=True, null=True),
        ),
        migrations.AddField(
            model_name="council",
            name="registration_email",
            field=models.EmailField(blank=True, max_length=254),
        ),
        migrations.AddField(
            model_name="council",
            name="registration_phone_numbers",
            field=django.contrib.postgres.fields.ArrayField(
                base_field=models.CharField(blank=True, max_length=100),
                default=list,
                size=None,
            ),
        ),
        migrations.AddField(
            model_name="council",
            name="registration_postcode",
            field=models.CharField(blank=True, max_length=100, null=True),
        ),
        migrations.AddField(
            model_name="council",
            name="registration_website",
            field=models.URLField(blank=True),
        ),
    ]


text:
@font-face {
  font-family: 'Roboto';
  font-weight: 400;
  font-style: normal;
  src: url('../fonts/Roboto-regular/Roboto-regular.eot');
  src: url('../fonts/Roboto-regular/Roboto-regular.eot?#iefix') format('embedded-opentype'),
       local('Roboto'),
       local('Roboto-regular'),
       url('../fonts/Roboto-regular/Roboto-regular.woff2') format('woff2'),
       url('../fonts/Roboto-regular/Roboto-regular.woff') format('woff'),
       url('../fonts/Roboto-regular/Roboto-regular.ttf') format('truetype'),
       url('../fonts/Roboto-regular/Roboto-regular.svg#Roboto') format('svg');
}


text:
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.Text;

namespace OpenLiveWriter.CoreServices
{
	public class ExifMetadata
	{
		class ExifTags
		{
			//Useful reference for more tags:
			//http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
			internal const int ImageDescription = 0x010e;
			internal const int Orientation = 0x112;
		}

		private Image _image;
		private ExifMetadata(Image image)
		{
			_image = image;
		}

		public string ImageDescription
		{
			get { return GetStringProperty(ExifTags.ImageDescription, null); }
		}

		public ExifOrientation Orientation
		{
			get
			{
				ExifOrientation o = ExifOrientation.Unknown;
				PropertyItem pi = GetProperty(ExifTags.Orientation);
				if(pi != null)
					o = (ExifOrientation) pi.Value[0];
				return o;
			}
            set
            {
                if (value == ExifOrientation.Unknown)
                {
                    _image.RemovePropertyItem(ExifTags.Orientation);
                }
                PropertyItem orientation = GetProperty(ExifTags.Orientation);
                orientation.Value[0] = (byte) value;
                _image.SetPropertyItem(orientation);
            }
		}

		public static ExifMetadata FromImage(Image image)
		{
			return new ExifMetadata(image);
		}

		private PropertyItem GetProperty(int exifTag)
		{
			try
			{
				return _image.GetPropertyItem(exifTag);
			}
			catch(Exception)
			{
				return null;
			}
		}

		private string GetStringProperty(int exifTag, string defaultValue)
		{
			PropertyItem pi = GetProperty(exifTag);
			if(pi != null)
				return Encoding.UTF8.GetString(pi.Value);
			else
				return defaultValue;
		}

		private void DumpAllExifProperties()
		{
			foreach(PropertyItem pi in _image.PropertyItems)
			{
                Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "0x{0}: {1}: {2}", pi.Id.ToString("X", CultureInfo.InvariantCulture), pi.Type, pi.Type == 2 ? Encoding.UTF8.GetString(pi.Value) : ""));
			}
		}
	}

	public enum ExifOrientation
	{
		Normal = 1,
		Rotate90CW = 6,
		Rotate270CW = 8,
		Unknown = -1
	}
}


text:
package org.springframework.cloud.config.s3;

import org.springframework.context.annotation.Bean;

public class CloudConfigS3Configuration {
    class Marker {}

    @Bean
    public Marker enableMarker() {
        return new Marker();
    }
}


text:
package com.jcwhatever.nucleus.managed.commands.mixins;

import com.jcwhatever.nucleus.managed.commands.ICommand;
import com.jcwhatever.nucleus.managed.commands.arguments.ICommandArguments;
import com.jcwhatever.nucleus.managed.commands.exceptions.CommandException;

import org.bukkit.command.CommandSender;

/**
 * A command mixin interface for a command that that can be executed.
 *
 *
If a command implements this mixin, the {@link #execute} method
 * is invoked when a command sender attempts to execute the command.

 *
 *
Commands that are not executable are generally parents of
 * sub commands and are used for categorization/namespacing only.

 */
public interface IExecutableCommand extends ICommand {

    /**
     * Invoked to execute the command.
     */
    void execute(CommandSender sender, ICommandArguments args)
            throws CommandException;
}


text:
package com.sportmonks.data.entity;

import com.fasterxml.jackson.annotation.*;
import com.sportmonks.data.structure.Seasons;

import java.util.HashMap;
import java.util.Map;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"id", "legacy_id", "name", "is_cup", "current_season_id", "current_round_id", "current_stage_id", "country_id", "seasons", "season", "country"})
public class League {

    @JsonProperty("id")
    private Long id;
    @JsonProperty("legacy_id")
    private Integer legacyId;
    @JsonProperty("name")
    private String name;
    @JsonProperty("is_cup")
    private Boolean isCup;
    @JsonProperty("current_season_id")
    private Long currentSeasonId;
    @JsonProperty("current_round_id")
    private Long currentRoundId;
    @JsonProperty("current_stage_id")
    private Long currentStageId;
    @JsonProperty("country_id")
    private Long countryId;
    @JsonProperty("seasons")
    private Seasons seasons;
    @JsonProperty("season")
    private Season season;
    @JsonProperty("country")
    private Country country;

    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("id")
    public Long getId() {
        return id;
    }

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

    @JsonProperty("legacy_id")
    public Integer getLegacyId() {
        return legacyId;
    }

    @JsonProperty("legacy_id")
    public void setLegacyId(Integer legacyId) {
        this.legacyId = legacyId;
    }

    @JsonProperty("name")
    public String getName() {
        return name;
    }

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

    @JsonProperty("is_cup")
    public Boolean getIsCup() {
        return isCup;
    }

    @JsonProperty("is_cup")
    public void setIsCup(Boolean isCup) {
        this.isCup = isCup;
    }

    @JsonProperty("current_season_id")
    public Long getCurrentSeasonId() {
        return currentSeasonId;
    }

    @JsonProperty("current_season_id")
    public void setCurrentSeasonId(Long currentSeasonId) {
        this.currentSeasonId = currentSeasonId;
    }

    @JsonProperty("current_round_id")
    public Long getCurrentRoundId() {
        return currentRoundId;
    }

    @JsonProperty("current_round_id")
    public void setCurrentRoundId(Long currentRoundId) {
        this.currentRoundId = currentRoundId;
    }

    @JsonProperty("current_stage_id")
    public Long getCurrentStageId() {
        return currentStageId;
    }

    @JsonProperty("current_stage_id")
    public void setCurrentStageId(Long currentStageId) {
        this.currentStageId = currentStageId;
    }

    @JsonProperty("country_id")
    public Long getCountryId() {
        return countryId;
    }

    @JsonProperty("country_id")
    public void setCountryId(Long countryId) {
        this.countryId = countryId;
    }

    @JsonProperty("seasons")
    public Seasons getSeasons() {
        return seasons;
    }

    @JsonProperty("seasons")
    public void setSeasons(Seasons seasons) {
        this.seasons = seasons;
    }

    @JsonProperty("season")
    public Season getSeason() {
        return season;
    }

    @JsonProperty("season")
    public void setSeason(Season season) {
        this.season = season;
    }

    @JsonProperty("country")
    public Country getCountry() {
        return country;
    }

    @JsonProperty("country")
    public void setCountry(Country country) {
        this.country = country;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    public void setAdditionalProperties(Map<String, Object> additionalProperties) {
        this.additionalProperties = additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}


text:
<?php

namespace CsvMigrations\FieldHandlers;

use Cake\Validation\Validator;
use CsvMigrations\FieldHandlers\Config\ConfigInterface;

/**
 * FieldHandlerInterface
 *
 * FieldHandlerInterface defines the contract that all
 * field handler classes have to implement.
 */
interface FieldHandlerInterface
{
    /**
     * Constructor
     *
     * @param \CsvMigrations\FieldHandlers\Config\ConfigInterface $config Instance of field handler config
     */
    public function __construct(ConfigInterface $config);

    /**
     * Config instance getter
     *
     * @return \CsvMigrations\FieldHandlers\Config\ConfigInterface
     */
    public function getConfig(): ConfigInterface;

    /**
     * Config instance setter
     *
     * @param \CsvMigrations\FieldHandlers\Config\ConfigInterface $config Instance of field handler config
     * @return void
     */
    public function setConfig(ConfigInterface $config): void;

    /**
     * Render field input
     *
     * This method prepares the form input for the given field,
     * including the input itself, label, pre-populated value,
     * and so on.  The result can be controlled via the variety
     * of options.
     *
     * @param mixed $data Field data
     * @param mixed[] $options Field options
     * @return string Field input HTML
     */
    public function renderInput($data = '', array $options = []): string;

    /**
     * Get options for field search
     *
     * This method prepares an array of search options, which includes
     * label, form input, supported search operators, etc.  The result
     * can be controlled with a variety of options.
     *
     * @param mixed[] $options Field options
     * @return mixed[] Array of field input HTML, pre and post CSS, JS, etc
     */
    public function getSearchOptions(array $options = []): array;

    /**
     * Render field value
     *
     * This method prepares the output of the value for the given
     * field.  The result can be controlled via the variety of
     * options.
     *
     * @param mixed $data Field data
     * @param mixed[] $options Field options
     * @return string Field value
     */
    public function renderValue($data, array $options = []): string;

    /**
     * Render field name
     *
     * @return string
     */
    public function renderName(): string;

    /**
     * Convert CsvField to one or more DbField instances
     *
     * Simple fields from migrations CSV map one-to-one to
     * the database fields.  More complex fields can combine
     * multiple database fields for a single CSV entry.
     *
     * @param \CsvMigrations\FieldHandlers\CsvField $csvField CsvField instance
     * @return \CsvMigrations\FieldHandlers\CsvField[]
     */
    public static function fieldToDb(CsvField $csvField): array;

    /**
     * Validation rules setter.
     *
     * Sets Table validation rules based on the provided field-type.
     *
     * @param \Cake\Validation\Validator $validator Validator instance
     * @param mixed[] $options Field options
     * @return \Cake\Validation\Validator
     */
    public function setValidationRules(Validator $validator, array $options = []): Validator;

    /**
     * Get Default Value of the Field Handler
     *
     * @return mixed
     */
    public function getDefaultValue();
}


text:
define(['pex/fx/FXStage', 'lib/text!pex/fx/Threshold.glsl'], function(FXStage, ThresholdGLSL) {
  FXStage.prototype.threshold = function(options) {
    options = options || {};
    threshold = (options.threshold !== undefined) ? options.threshold : 0.5;

    var outputSize = this.getOutputSize(options.width, options.height);
    var rt = this.getRenderTarget(outputSize.width, outputSize.height, options.depth, options.bpp);
    rt.bind();

    this.getSourceTexture().bind();
    var program = this.getShader(ThresholdGLSL);
    program.use();
    program.uniforms.threshold( threshold );
    this.drawFullScreenQuad(outputSize.width, outputSize.height, null, program);
    rt.unbind();

    return this.asFXStage(rt, 'threshold');
  }
})


text:
<?php

namespace Eljam\GuzzleJwt\Tests\Manager;

use Eljam\GuzzleJwt\JwtToken;
use Eljam\GuzzleJwt\Manager\JwtManager;
use Eljam\GuzzleJwt\Strategy\Auth\QueryAuthStrategy;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\RequestInterface;

/**
 * @author Guillaume Cavavana <guillaume.cavana@gmail.com>
 */
class JwtManagerTest extends \PHPUnit\Framework\TestCase
{

    /**
     * testGetTokenExpiredKeyException
     */
    public function testGetTokenExpiredKeyException()
    {
        $mockHandler = new MockHandler([
            function (RequestInterface $request) {

                $this->assertTrue($request->hasHeader('timeout'));
                $this->assertEquals(
                    3,
                    $request->getHeaderLine('timeout')
                );

                $jsonPayload = <<<EOF
            {
                "status": "success",
                "message": "Login successful",
                "payload": {
                    "token": "1453720507"
                },
                "expires_in": 3600
            }
EOF;

                return new Response(
                    200,
                    ['Content-Type' => 'application/json'],
                    $jsonPayload
                );
            },
        ]);

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            [
                'token_url' => '/api/token',
                'timeout' => 3,
                'token_key' => 'token',
                'expire_key' => 'expires_in'
            ]
        );

        $this->expectException('Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException');

        $token = $jwtManager->getJwtToken();
    }

    /**
     * testGetTokenWithSublevelResponse
     */
    public function testGetTokenWithSublevelResponse()
    {
        $mockHandler = new MockHandler([
            function (RequestInterface $request) {

                $this->assertTrue($request->hasHeader('timeout'));
                $this->assertEquals(
                    3,
                    $request->getHeaderLine('timeout')
                );

                $jsonPayload = <<<EOF
            {
                "status": "success",
                "message": "Login successful",
                "payload": {
                    "token": "1453720507"
                },
                "expires_in": 3600
            }
EOF;

                return new Response(
                    200,
                    ['Content-Type' => 'application/json'],
                    $jsonPayload
                );
            },
        ]);

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            [
                'token_url' => '/api/token',
                'timeout' => 3,
                'token_key' => 'payload.token',
                'expire_key' => 'expires_in'
            ]
        );
        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('1453720507', $token->getToken());
    }

    /**
     * testGetToken.
     */
    public function testGetToken()
    {
        $mockHandler = new MockHandler([
            function (RequestInterface $request) {

                $this->assertTrue($request->hasHeader('timeout'));
                $this->assertEquals(
                    3,
                    $request->getHeaderLine('timeout')
                );

                return new Response(
                    200,
                    ['Content-Type' => 'application/json'],
                    json_encode(['token' => '1453720507', 'expires_in' => 3600])
                );
            },
        ]);

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            ['token_url' => '/api/token', 'timeout' => 3]
        );
        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('1453720507', $token->getToken());
    }

    public function testGetTokenWithTokenKeyOption()
    {
        $mockHandler = new MockHandler([
            function (RequestInterface $request) {

                $this->assertTrue($request->hasHeader('timeout'));
                $this->assertEquals(
                    3,
                    $request->getHeaderLine('timeout')
                );

                return new Response(
                    200,
                    ['Content-Type' => 'application/json'],
                    json_encode(['tokenkey' => '1453720507'])
                );
            },
        ]);

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            ['token_url' => '/api/token', 'timeout' => 3, 'token_key' => 'tokenkey']
        );
        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('1453720507', $token->getToken());
    }

    public function testGetTokenShouldGetNewTokenIfCachedTokenIsNotValid()
    {
        $mockHandler = new MockHandler(
            [
                function (RequestInterface $request) {

                    $this->assertTrue($request->hasHeader('timeout'));
                    $this->assertEquals(
                        3,
                        $request->getHeaderLine('timeout')
                    );

                    return new Response(
                        200,
                        ['Content-Type' => 'application/json'],
                        json_encode(['token' => '1453720507'])
                    );
                },
                function (RequestInterface $request) {

                    $this->assertTrue($request->hasHeader('timeout'));
                    $this->assertEquals(
                        3,
                        $request->getHeaderLine('timeout')
                    );

                    return new Response(
                        200,
                        ['Content-Type' => 'application/json'],
                        json_encode(['token' => 'foo123'])
                    );
                },
            ]
        );

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            ['token_url' => '/api/token', 'timeout' => 3]
        );
        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('1453720507', $token->getToken());

        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('foo123', $token->getToken());
    }

    public function testGetTokenShouldUseTheCachedTokenIfItIsValid()
    {
        $mockHandler = new MockHandler(
            [
                function (RequestInterface $request) {

                    $this->assertTrue($request->hasHeader('timeout'));
                    $this->assertEquals(
                        3,
                        $request->getHeaderLine('timeout')
                    );

                    return new Response(
                        200,
                        ['Content-Type' => 'application/json'],
                        json_encode(['token' => '1453720507', 'expires_in' => 3600])
                    );
                },
                function (RequestInterface $request) {

                    $this->assertTrue($request->hasHeader('timeout'));
                    $this->assertEquals(
                        3,
                        $request->getHeaderLine('timeout')
                    );

                    return new Response(
                        200,
                        ['Content-Type' => 'application/json'],
                        json_encode(['token' => 'foo123'])
                    );
                },
            ]
        );

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            ['token_url' => '/api/token', 'timeout' => 3]
        );
        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('1453720507', $token->getToken());

        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals('1453720507', $token->getToken());
    }

    public function testGetTokenShouldUseTheCachedTokenIfItIsValidBasedOnExpField()
    {
        $jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
            . '.eyJleHAiOiIzMjUwMzY4MDAwMCJ9'
            . '.k4YJmJooaa9B4pAM_U8Pi-4ss6RdKFtj9iQqLIAndVA';

        $mockHandler = new MockHandler(
            [
                function (RequestInterface $request) use ($jwtToken) {

                    $this->assertTrue($request->hasHeader('timeout'));
                    $this->assertEquals(
                        3,
                        $request->getHeaderLine('timeout')
                    );

                    return new Response(
                        200,
                        ['Content-Type' => 'application/json'],
                        json_encode(['token' => $jwtToken])
                    );
                },
                function (RequestInterface $request) {

                    $this->assertTrue($request->hasHeader('timeout'));
                    $this->assertEquals(
                        3,
                        $request->getHeaderLine('timeout')
                    );

                    return new Response(
                        200,
                        ['Content-Type' => 'application/json'],
                        json_encode(['token' => uniqid('token', true)])
                    );
                },
            ]
        );

        $handler = HandlerStack::create($mockHandler);

        $authClient = new Client([
            'handler' => $handler,
        ]);

        $authStrategy = new QueryAuthStrategy(['username' => 'admin', 'password' => 'admin']);

        $jwtManager = new JwtManager(
            $authClient,
            $authStrategy,
            null,
            ['token_url' => '/api/token', 'timeout' => 3]
        );
        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals($jwtToken, $token->getToken());

        $token = $jwtManager->getJwtToken();

        $this->assertInstanceOf(JwtToken::class, $token);
        $this->assertEquals($jwtToken, $token->getToken());
    }
}


text:
<dom-module id="wrap-story">

</dom-module>


text:
/**
 * $Id: BrokerMaster.java 1831 2013-05-16 01:39:51Z shijia.wxr $
 */
package com.alibaba.rocketmq.research.storeha;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicLong;

import com.alibaba.rocketmq.research.store.MessageStoreTestObject;
import com.alibaba.rocketmq.store.config.MessageStoreConfig;

/**
 * HA测试
 *
 * @author shijia.wxr<vintage.wang@gmail.com>
 */
public class BrokerMaster {

    public static void main(String[] args) {
        try {
            final String brokerRole = args.length >= 1 ? args[0] : "SYNC_MASTER";
            final int ThreadSize = args.length >= 2 ? Integer.parseInt(args[1]) : 128;

            MessageStoreConfig messageStoreConfig = new MessageStoreConfig();
            messageStoreConfig.setBrokerRole(brokerRole);

            final MessageStoreTestObject storeTestObject = new MessageStoreTestObject(messageStoreConfig);

            if (!storeTestObject.load()) {
                System.out.println("load store failed");
                System.exit(-1);
            }

            storeTestObject.start();

            System.out.println("waiting 5s for slave connect....");
            Thread.sleep(1000 * 5);
            System.out.println("wait over");

            // Thread pool
            final ThreadPoolExecutor executorSend =
                    (ThreadPoolExecutor) Executors.newFixedThreadPool(ThreadSize);

            final AtomicLong maxResponseTime = new AtomicLong(0);
            final AtomicLong sendTotalCnt = new AtomicLong(0);

            for (int i = 0; i < ThreadSize; i++) {
                executorSend.execute(new Runnable() {

                    @Override
                    public void run() {
                        for (long k = 1;; k++) {
                            try {
                                long beginTime = System.currentTimeMillis();
                                boolean result = storeTestObject.sendMessage();
                                long rt = System.currentTimeMillis() - beginTime;
                                if (rt > maxResponseTime.get()) {
                                    maxResponseTime.set(rt);
                                }

                                if (!result) {
                                    System.err.println(k + "\tSend message failed, error message:");
                                    Thread.sleep(1000);
                                }
                                else {
                                    sendTotalCnt.incrementAndGet();
                                }
                            }
                            catch (Exception e) {
                                System.out.println("sendMessage exception -------------");
                                e.printStackTrace();
                                try {
                                    Thread.sleep(1000);
                                }
                                catch (InterruptedException e1) {
                                }
                            }
                        }
                    }
                });
            }

            new Thread(new Runnable() {
                @Override
                public void run() {
                    long lastTime = System.currentTimeMillis();
                    long lastTotal = 0;
                    while (true) {
                        try {
                            Thread.sleep(1000 * 3);
                        }
                        catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        long now = System.currentTimeMillis();
                        long currentTotal = sendTotalCnt.get();

                        Double tps = (currentTotal - lastTotal) / ((now - lastTime) * 1.0);
                        tps *= 1000;

                        lastTime = now;
                        lastTotal = currentTotal;
                        double avtRT = 1000 / ((tps / ThreadSize) * 1.0);
                        System.out.println("send tps = " + tps.longValue() + " maxResponseTime(ms) = "
                                + maxResponseTime + " avgRT(ms) = " + avtRT);
                    }
                }
            }).start();

            System.out.println("start OK, " + messageStoreConfig.getBrokerRole());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta name="generator" content=
"HTML Tidy for Mac OS X (vers 12 April 2005), see www.w3.org">
<meta http-equiv="Content-Type" content=
"text/html; charset=us-ascii">
<title>Function betweenness_centrality_clustering</title>

Function
betweenness_centrality_clustering

boost::betweenness_centrality_clustering — Graph
clustering based on edge betweenness centrality.

Synopsis

template<typename MutableGraph, typename Done, typename EdgeCentralityMap,
         typename VertexIndexMap>
  void betweenness_centrality_clustering(MutableGraph & g, Done done,
                                         EdgeCentralityMap edge_centrality,
                                         VertexIndexMap vertex_index);
template<typename MutableGraph, typename Done, typename EdgeCentralityMap>
  void betweenness_centrality_clustering(MutableGraph & g, Done done,
                                         EdgeCentralityMap edge_centrality);
template<typename MutableGraph, typename Done>
  void betweenness_centrality_clustering(MutableGraph & g, Done done);

Description

This algorithm implements graph clustering based on edge
betweenness centrality. It is an iterative algorithm, where in each
step it computes the edge betweenness centrality (via brandes_betweenness_centrality) and
removes the edge with the maximum betweenness centrality. The
<tt class="computeroutput">done</tt> function object determines
when the algorithm terminates (the edge found when the algorithm
terminates will not be removed).

Parameters

IN: <tt>const Graph& g</tt>

  The graph object on which the algorithm will be applied.  The type
  <tt>Graph</tt> must be a model of Vertex List Graph and Incidence Graph. When an edge
  centrality map is supplied, it must also model Edge List Graph and MutableGraph.

Python: The parameter is named <tt>graph</tt>.

IN: <tt>Done done</tt>

The function object that indicates termination of the algorithm.
It must be a ternary function object thats accepts the maximum
centrality, the descriptor of the edge that will be removed, and
the graph <tt class="computeroutput">g</tt>.

Python: Any callable Python object will suffice.

OUT/UTIL: <tt>EdgeCentralityMap edge_centrality_map</tt>

  This property map is used to accumulate the betweenness centrality
  of each edge, and is a secondary form of output for the
  algorithm. The type <tt>EdgeCentralityMap</tt> must be a model of Read/Write
  Property Map, with the graph's edge descriptor type as its key
  type. The value type of this property map should be the same as the
  value type of the <tt>CentralityMap</tt> property map.

  Default: a <tt>dummy_property_map</tt>, which requires no
  work to compute and returns no answer.

  Python: The color map must be a <tt>edge_double_map</tt> for
  the graph.

  Python default: <tt>graph.get_edge_double_map("centrality")</tt>

IN: <tt>VertexIndexMap vertex_index</tt>

  This maps each vertex to an integer in the range <tt>[0,
    num_vertices(g))</tt>. This is necessary for efficient updates of the
  heap data structure when an edge is relaxed.  The type
  <tt>VertexIndexMap</tt> must be a model of
  Readable Property Map. The value type of the map must be an
  integer type. The vertex descriptor type of the graph needs to be
  usable as the key type of the map.

  Default: <tt>get(vertex_index, g)</tt>.
    Note: if you use this default, make sure your graph has
    an internal <tt>vertex_index</tt> property. For example,
    <tt>adjacenty_list</tt> with <tt>VertexList=listS</tt> does
    not have an internal <tt>vertex_index</tt> property.

  Python: Unsupported parameter.

Where Defined

<boost/graph/bc_clustering.hpp>

Copyright © 2004
Douglas Gregor,
Indiana University (dgregor@cs.indiana.edu)

Andrew Lumsdaine, Indiana
University (lums@osl.iu.edu)


text:
<?xml version="1.0"?>
  <project name="tsp_solver" default="pack" basedir="./">

  <property name="compile" value="Classes"/>
  <property name="classpath" value="lib/commons-cli-1.2.jar" />
  <property name="dest" value="dest" />

  <target name="directory">
    <mkdir dir="${compile}"/>
  	<mkdir dir="${dest}" />
  	<mkdir dir="${dest}/lib" />
  </target>

  <target name="copy" depends="directory" >
  	<copy todir="${dest}/lib" >
  	    <fileset dir="lib" includes="**"/>
  	</copy>
  	<copy file="LICENSE" toDir="${dest}" overwrite="yes" />
  	<copy file="NOTICE" toDir="${dest}" overwrite="yes" />
  	<copy file="README" toDir="${dest}" overwrite="yes" />
  	<copy file="READMEjp" toDir="${dest}" overwrite="yes" />
  	<copy file="simulated_annealing.properties" toDir="${dest}" overwrite="yes" />
  </target>

  <target name="compile" depends="directory">
    <javac
     srcdir="src"
     destdir="${compile}"
     classpath="${classpath}"
     excludes="build.xml"
   	 includeantruntime="false"
    />
  </target>

  <target name="jar" depends="compile">
  	<jar basedir="${compile}" destfile="${dest}/tsp.jar">
  		<manifest>
  			<attribute name="Main-Class" value="main.Main" />
  			<attribute name="Class-Path" value="${classpath}" />
  		</manifest>
  	</jar>
  </target>

  <target name="pack" depends="copy, jar" />

</project>


text:
<!--
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../polymer/polymer.html">

<link rel="import" href="more-route-context-aware.html">
<link rel="import" href="more-route-selection.html">

<!--
TODO(nevir): Document.

TODO(nevir): Support child addition/removal/reorder.
-->
<dom-module id="more-route-selector">
  <template>
    <more-route-selection
        id="selection"
        routes="[[routes]]"
        on-more-route-change="_onMoreRouteChange">
    </more-route-selection>
    <content></content>
  </template>
</dom-module>
<script>
Polymer({

  is: 'more-route-selector',

  behaviors: [
    MoreRouting.ContextAware,
  ],

  properties: {

    /**
     * The attribute to read route expressions from (on children).
     */
    routeAttribute: {
      type: String,
      value: 'route',
    },

    /**
     * The routes managed by this element (inferred from the items that are
     * defined by the selector it targets).
     */
    routes: {
      type:     Array,
      readOnly: true,
      notify:   true,
    },

    /**
     * The selected `MoreRouting.Route` object, or `null`.
     *
     * @type {MoreRouting.Route}
     */
    selectedRoute: {
      type:     Object,
      value:    null,
      readOnly: true,
      notify:   true,
    },

    /**
     * The index of the selected route (relative to `routes`). -1 when there
     * is no active route.
     */
    selectedIndex: {
      type:     Number,
      value:    -1,
      readOnly: true,
      notify:   true,
    },

    /**
     * The _full_ path expression of the selected route, or `null`.
     */
    selectedPath: {
      type:     String,
      readOnly: true,
      notify:   true,
    },

    /**
     * The params of the selected route, or an empty object if no route.
     */
    selectedParams: {
      type:     Object,
      readOnly: true,
      notify:   true,
    },

  },

  /**
   * @event more-route-selected fires when a new route is selected.
   * @param {{
   *   newRoute:  MoreRouting.Route, oldRoute: MoreRouting.Route,
   *   newIndex:  number,  oldIndex:  number,
   *   newPath:   ?string, oldPath:   ?string,
   *   newParams: Object,  oldParams: Object,
   * }}
   */

  attached: function() {
    this._managedSelector = this._findTargetSelector();
    if (!this._managedSelector) {
      console.warn(this, 'was built without a selector to manage. It will do nothing.');
      return;
    }

    this._managedSelector.addEventListener(
        'selected-item-changed', this._onSelectedItemChanged.bind(this));
    this._updateRoutes();
  },

  /**
   * Handle a change in selected item, driven by the targeted selector.
   *
   * Note that this will fail if a route is chosen that requires params not
   * defined by the current URL.
   */
  _onSelectedItemChanged: function(event) {
    var route = this._routeForItem(event.detail.value);
    if (!route) return;
    route.navigateTo();
  },

  _updateRoutes: function() {
    var routes = [];
    if (this._managedSelector) {
      routes = this._managedSelector.items.map(this._routeForItem.bind(this));
    }
    this._setRoutes(routes);
  },

  _onMoreRouteChange: function(event) {
    if (!this._managedSelector) return;
    var route = event.detail.newRoute;
    this._managedSelector.select(this.routes.indexOf(route));
  },

  _findTargetSelector: function() {
    var children = Polymer.dom(this).children;
    if (children.length !== 1) {
      console.error(this, 'expects only a single selector child');
      return null;
    }

    var child = children[0];
    if ('selected' in child && 'items' in child) {
      return child;
    } else {
      console.error(this, 'can only manage children that are selectors');
      return null;
    }
  },

  _routeForItem: function(item) {
    if (!item) return null;
    if (item.moreRouteContext && item.moreRouteContext instanceof MoreRouting.Route) {
      return item.moreRouteContext;
    }

    if (!item.hasAttribute(this.routeAttribute)) {
      console.warn(item, 'is missing a context route or "' + this.routeAttribute + '" attribute');
      return null;
    }
    var expression = item.getAttribute(this.routeAttribute);
    var route      = MoreRouting.getRoute(expression, this.parentRoute);
    // Associate the route w/ its element while we're here.
    item.moreRouteContext = route;

    return route;
  },

});
</script>


text:
package org.finra.herd.service.helper;

import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import org.finra.herd.model.api.xml.NamespaceKey;

/**
 * A helper class for Namespace related code.
 */
@Component
public class NamespaceHelper
{
    /**
     * Validates a namespace key. This method also trims the key parameters.
     *
     * @param namespaceKey the namespace key
     *
     * @throws IllegalArgumentException if any validation errors were found
     */
    public void validateNamespaceKey(NamespaceKey namespaceKey) throws IllegalArgumentException
    {
        // Validate.
        Assert.notNull(namespaceKey, "A namespace key must be specified.");
        Assert.hasText(namespaceKey.getNamespaceCode(), "A namespace must be specified.");

        // Remove leading and trailing spaces.
        namespaceKey.setNamespaceCode(namespaceKey.getNamespaceCode().trim());
    }
}


text:
package software.amazon.awssdk.benchmark.enhanced.dynamodb;

import org.openjdk.jmh.infra.Blackhole;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.paginators.ScanIterable;

public final class V2TestDynamoDbScanClient extends V2TestDynamoDbBaseClient {
    private final ScanResponse scanResponse;

    public V2TestDynamoDbScanClient(Blackhole bh, ScanResponse scanResponse) {
        super(bh);
        this.scanResponse = scanResponse;
    }

    @Override
    public ScanResponse scan(ScanRequest scanRequest) {
        bh.consume(scanRequest);
        return this.scanResponse;
    }

    @Override
    public ScanIterable scanPaginator(ScanRequest scanRequest) {
        return new ScanIterable(this, scanRequest);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace AssistiveTweet.Behaviour
{

    /// <summary>

    /// ドラッグムーブを実現する添付ビヘイビア
    /// </summary>
    public static class DragMoveBehaviour
    {
        public static bool GetCanDragMove(UIElement elem)
        {
            return (bool)elem.GetValue(CanDragMoveProperty);
        }

        public static void SetCanDragMove(UIElement elem, bool val)
        {
            elem.SetValue(CanDragMoveProperty, val);
        }

        public static readonly DependencyProperty CanDragMoveProperty =
                DependencyProperty.RegisterAttached(
                        "CanDragMove",
                        typeof(bool),
                        typeof(DragMoveBehaviour),
                        new PropertyMetadata(OnPropertyChanged));

        private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            //Propertyが変更されたときにMouseDownのイベントハンドラを登録しておく

            var target = sender as UIElement;
            if (target == null) return;
            if ((bool)e.NewValue == true)
            {
                target.MouseDown += OnMouseDown;
            }
            else
            {
                //do nothing
            }
        }

        private static void OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            //押されたオブジェクトが所属するWindowを探してDragMove()する

            var obj = sender as DependencyObject;
            if (obj == null) return;
            if (e.ChangedButton == MouseButton.Left && e.LeftButton == MouseButtonState.Pressed)
            {
                getParentWindow(obj).DragMove();
            }
        }

        private static Window getParentWindow(DependencyObject current)
        {
            //引数currentを内部に持っているwinを探して返す
            foreach (Window win in App.Current.Windows)
            {
                if (win.IsAncestorOf(current))
                {
                    return win;
                }
            }
            throw new InvalidOperationException("Couldn't find window");
        }
    }
}


text:
This playbook will allow Vagrant to create an Ubuntu 14.04 LTS 64 instance with everything necessary to run Ruby on Rails.

This Ansible playbook was generated using [railsbox](https://railsbox.io/) and modified as needed.

##### Before You Run Vagrant/Ansible

Before you run Vagrant and/or Ansible, you'll need to edit the following files and change all variables that have **CHANGE_ME**:
* config.yml
* ansible/group_vars/all/config.yml


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title> NetFUNNEL2 index Test </title>
	<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
	<script type="text/javascript" src="js/netfunnel.js" charset="UTF-8"></script>
	<script>
		function goIndex(){
			NetFunnel_Action({action_id:"load"},"index_1.html");
		}
	</script>
</head>
<body onload="goIndex()">
</body>

</html>


text:
title: 100 doors
id: 594810f028c0303b75339acb
challengeType: 5
isHidden: false
forumTopicId: 302217
---

## Description

There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and 'toggle' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (i.e., door #2, #4, #6, ...) and toggle it. The third time, visit every 3rd door (i.e., door #3, #6, #9, ...), etc., until you only visit the 100th door.

## Instructions

Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.

## Tests

```yml
tests:
  - text: <code>getFinalOpenedDoors</code> should be a function.
    testString: assert(typeof getFinalOpenedDoors === 'function');
  - text: <code>getFinalOpenedDoors</code> should return an array.
    testString: assert(Array.isArray(getFinalOpenedDoors(100)));
  - text: <code>getFinalOpenedDoors</code> should produce the correct result.
    testString: assert.deepEqual(getFinalOpenedDoors(100), solution);

```

## Challenge Seed

```js
function getFinalOpenedDoors(numDoors) {
  // Good luck!
}
```

### After Test

```js
const solution = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100];
```

## Solution

```js
function getFinalOpenedDoors(numDoors) {
  // this is the final pattern (always squares).
  // thus, the most efficient solution simply returns an array of squares up to numDoors).
  const finalState = [];
  let i = 1;
  while (Math.pow(i, 2) <= numDoors) {
    finalState.push(Math.pow(i, 2));
    i++;
  }
  return finalState;
}

```


text:
module BootstrapForm
  class Configuration
    def default_form_attributes=(attributes)
      case attributes
      when nil
        @default_form_attributes = {}
      when Hash
        @default_form_attributes = attributes
      else
        raise ArgumentError, "Unsupported default_form_attributes #{attributes.inspect}"
      end
    end

    def default_form_attributes
      return @default_form_attributes if defined? @default_form_attributes

      # TODO: Return blank hash ({}) in 5.0.0. Role "form" for form tags is redundant and makes W3C to raise a warning.
      { role: "form" }
    end
  end
end


text:
function MyController($scope) {
    $scope.clock = {
        now: new Date()
    };
    var updateClock = function() {
        $scope.clock.now = new Date();
    };
    setInterval(function() {
        $scope.$apply(updateClock);
    }, 1000);
    updateClock();
};


text:
<?php

defined('_HZEXEC_') or die();

$isNew = $this->item->isNew();
$canDo = Components\Menus\Helpers\Menus::getActions();

Toolbar::title(Lang::txt($isNew ? 'COM_MENUS_VIEW_NEW_MENU_TITLE' : 'COM_MENUS_VIEW_EDIT_MENU_TITLE'), 'menu');

// If a new item, can save the item.  Allow users with edit permissions to apply changes to prevent returning to grid.
if ($isNew && $canDo->get('core.create'))
{
	if ($canDo->get('core.edit'))
	{
		Toolbar::apply();
	}
	Toolbar::save();
}

// If user can edit, can save the item.
if (!$isNew && $canDo->get('core.edit'))
{
	Toolbar::apply();
	Toolbar::save();
}

// If the user can create new items, allow them to see Save & New
if ($canDo->get('core.create'))
{
	Toolbar::save2new();
}
if ($isNew)
{
	Toolbar::cancel();
}
else
{
	Toolbar::cancel('cancel', 'JTOOLBAR_CLOSE');
}
Toolbar::divider();
Toolbar::help('menu');

// Include the component HTML helpers.
Html::addIncludePath(Component::path($this->option) . '/helpers/html');

// Load the tooltip behavior.
Html::behavior('tooltip');
Html::behavior('formvalidation');

$this->js();
?>

<form action="<?php echo Route::url('index.php?option=' . $this->option . '&controller=' . $this->controller . '&task=edit&cid=' . (int) $this->item->get('id')); ?>" method="post" name="adminForm" id="item-form" class="editform form-validate" data-invalid-msg="<?php echo $this->escape(Lang::txt('JGLOBAL_VALIDATION_FORM_FAILED'));?>">
	<fieldset class="adminform">
		<legend><?php echo Lang::txt('COM_MENUS_MENU_DETAILS');?></legend>

			<?php echo $this->form->getLabel('title'); ?>
			<?php echo $this->form->getInput('title'); ?>

			<?php echo $this->form->getLabel('menutype'); ?>
			<?php echo $this->form->getInput('menutype'); ?>

			<?php echo $this->form->getLabel('description'); ?>
			<?php echo $this->form->getInput('description'); ?>

	</fieldset>

	<input type="hidden" name="cid" value="<?php echo (int) $this->item->get('id'); ?>" />

	<input type="hidden" name="option" value="<?php echo $this->option; ?>" />
	<input type="hidden" name="controller" value="<?php echo $this->controller; ?>" />
	<input type="hidden" name="task" value="" />
	<?php echo Html::input('token'); ?>
</form>


text:
package toller

import (
    "errors"
    "config"
    "time"
    "net"
    "strings"
    "fmt"
)

const (
    STARVE int32 = 0
    EMPTY int32 = 1
    FULL int32 = 2
)

type Dialer func() (net.Conn, error)

type BackConnPool struct {
    dialer Dialer
    host *Host
    user string
    passwd string
    pool chan *BackConn
    waitq chan *FrontConn
    water_count chan bool
    status int32
    max uint16
    min uint16
    watermark uint16
    stop bool
}

func default_dialer(proto, laddr, raddr string, timeout time.Duration) (net.Conn, error) {
	if proto == "" {
		if strings.IndexRune(raddr, ':') != -1 {
			proto = "tcp"
		} else {
		    proto = "unix"
        }
	}

	// Make a connection
	d := &net.Dialer{Timeout: timeout}
	if laddr != "" {
		var err error
		switch proto {
		case "tcp", "tcp4", "tcp6":
			d.LocalAddr, err = net.ResolveTCPAddr(proto, laddr)
		case "unix":
			d.LocalAddr, err = net.ResolveTCPAddr(proto, laddr)
		default:
			err = net.UnknownNetworkError(proto)
		}
		if err != nil {
			return nil, err
		}
	}
	return d.Dial(proto, raddr)
}

func newBackConnPool(host *Host, poolconfig *config.UserPoolConfig) (bp *BackConnPool) {
    bp = new(BackConnPool)
    bp.host = host
    bp.user = poolconfig.User
    bp.max = poolconfig.Max
    bp.min = poolconfig.Min
    bp.passwd = poolconfig.Passwd
    bp.watermark = 0
    bp.pool = make(chan *BackConn, bp.max)
    bp.waitq = make(chan *FrontConn, int(bp.max) * MAXCONN_PER_BACKEND * 2)
    bp.water_count = make(chan bool, 32)
    bp.stop = false
    // set the dialer
    bp.dialer = func () (net.Conn, error) {
        return default_dialer(bp.host.proto, "", bp.host.addr, 2 * time.Minute)
    }

    // start Scheduling
    go bp.Schedule()
    return
}

func (bp *BackConnPool) Stop() {
    bp.stop = true
}

func (bp *BackConnPool) EnQueue(fc *FrontConn) (ok bool, err error) {
    ok = false
    if !bp.stop {
        // if stop, can not EnQueue
        select {
        case bp.waitq <- fc:
            ok = true
        default:
            err = errors.New("chanfull")
        }
    } else {
        err = errors.New("Stopped")
    }
    return
}

func (bp *BackConnPool) NotifyClosing() {
    bp.water_count <- false // if water_count is full, just blocking here
}

func (bp *BackConnPool) NotifyAdding() {
    bp.water_count <- true // if water_count if full, just blocking
}

/*
 * if a BackConn's q get full, it means load high, so set the status to EMPTY.
 * if continous conns more than min number, STARVE
 * if can not get BackConn at all, means the transactions are too much.
*/
func (bp *BackConnPool) Schedule() {
    for {
        select {
        case fc := <-bp.waitq:
            // dispatch FrontConn to BackConn's waitq
            full_count := 0
            //for {
                select {
                case bc := <-bp.pool:
                    ok, err := bc.EnQueue(fc)
                    if ok {
                        bp.pool <- bc
                        break
                    } else if err == errors.New("chanfull") {
                        bp.pool <- bc
                        if full_count > 1 {
                            if bc, err = bp.AddConn(); err == nil {
                                bc.EnQueue(fc) // the conn is new, so never failed
                                bp.pool <- bc
                            } else {
                                ErrorLog.Printf("can not Add BackConn to %s pool\n", bp.user)
                            }
                            break
                        }
                        full_count++
                    } else if err == errors.New("Transaction") {
                        bc.OutPool() // temparary leave the BackConn out of the pool
                    }
                default:
                    // no BackConn in the pool
                    if bc, err := bp.AddConn(); err == nil {
                        bc.EnQueue(fc) // the conn is new, so never failed
                        bp.pool <- bc
                    } else {
                        ErrorLog.Printf("can not Add BackConn to %s pool\n", bp.user)
                    }
                    break
                }
            //}
        case add_or_delete := <-bp.water_count:
            // decrease watermark according to closed message
            if add_or_delete {
                bp.watermark++
            } else {
                bp.watermark--
            }
        default:
            if bp.stop { break } // stop and waitq is empty, can stop
            if bp.status > EMPTY && bp.watermark > bp.min {
                // start check idle BackConn for stopping
                for i := uint16(0); i < bp.watermark; i++ {
                    bc := <-bp.pool
                    if bc.IsEmpty() {
                        bc.Stop()
                        break // just stop a conn once
                    } else {
                        bp.pool <- bc
                    }
                }
            }
        }
    }
    bp.Cleanup()
    bp.WaitForCleanup()
    return
}

func (bp *BackConnPool) PutbackConn(bc *BackConn) {
    select {
    case bp.pool <- bc:
    default:
        // pool full and just close the conn
        bc.Stop()
    }
}

func (bp *BackConnPool) SetStatus(new_status int32) {
    bp.status = new_status
}

func (bp *BackConnPool) FetchInfo() (info *serverFullInfo, err error) {
    fmt.Println("Fetchinfo start")
    if bp.stop {
        err = errors.New("Stop")
    } else {
        info, err = testBackConn(bp)
    }
    return
}

func (bp *BackConnPool) AddConn() (bc *BackConn, err error){
    if bp.stop {
        err = errors.New("Stop")
    } else {
        if bc, err = newBackConn(bp); err == nil {
            select {
            case bp.pool <- bc:
                bp.NotifyAdding()
            default:
                err = errors.New("poolfull")
                // pool full, just close your connection.
                bc.Close()
                bc = nil
            }
        }
    }
    return
}

func (bp *BackConnPool) Cleanup() {
    for bc := range bp.pool {
        bc.Stop()
    }
    return
}

func (bp *BackConnPool) WaitForCleanup() {
    for {
        add_or_delete := <-bp.water_count
        if add_or_delete {
            bp.watermark++
        } else {
            bp.watermark--
        }
        if bp.watermark == 0 {
            break
        }
    }
    bp.host.NotifyClosed()
    return
}


text:
/*
 * This file is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 2,
 * as published by the Free Software Foundation.
 *
 * In addition to the permissions in the GNU General Public License,
 * the authors give you unlimited permission to link the compiled
 * version of this file into combinations with other programs,
 * and to distribute those combinations without any restriction
 * coming from the use of this file.  (The General Public License
 * restrictions do apply in other respects; for example, they cover
 * modification of the file, and distribution when not linked into
 * a combined executable.)
 *
 * This file is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#ifndef INCLUDE_git_object_h__
#define INCLUDE_git_object_h__

#include "common.h"
#include "types.h"
#include "oid.h"

/**
 * @file git2/object.h
 * @brief Git revision object management routines
 * @defgroup git_object Git revision object management routines
 * @ingroup Git
 * @{
 */
GIT_BEGIN_DECL

/**
 * Lookup a reference to one of the objects in a repostory.
 *
 * The generated reference is owned by the repository and
 * should be closed with the `git_object_close` method
 * instead of free'd manually.
 *
 * The 'type' parameter must match the type of the object
 * in the odb; the method will fail otherwise.
 * The special value 'GIT_OBJ_ANY' may be passed to let
 * the method guess the object's type.
 *
 * @param object pointer to the looked-up object
 * @param repo the repository to look up the object
 * @param id the unique identifier for the object
 * @param type the type of the object
 * @return a reference to the object
 */
GIT_EXTERN(int) git_object_lookup(git_object **object, git_repository *repo, const git_oid *id, git_otype type);

/**
 * Get the id (SHA1) of a repository object
 *
 * @param obj the repository object
 * @return the SHA1 id
 */
GIT_EXTERN(const git_oid *) git_object_id(const git_object *obj);

/**
 * Get the object type of an object
 *
 * @param obj the repository object
 * @return the object's type
 */
GIT_EXTERN(git_otype) git_object_type(const git_object *obj);

/**
 * Get the repository that owns this object
 *
 * @param obj the object
 * @return the repository who owns this object
 */
GIT_EXTERN(git_repository *) git_object_owner(const git_object *obj);

/**
 * Close an open object
 *
 * This method instructs the library to close an existing
 * object; note that git_objects are owned and cached by the repository
 * so the object may or may not be freed after this library call,
 * depending on how agressive is the caching mechanism used
 * by the repository.
 *
 * IMPORTANT:
 * It *is* necessary to call this method when you stop using
 * an object. Failure to do so will cause a memory leak.
 *
 * @param object the object to close
 */
GIT_EXTERN(void) git_object_close(git_object *object);

/**
 * Convert an object type to it's string representation.
 *
 * The result is a pointer to a string in static memory and
 * should not be free()'ed.
 *
 * @param type object type to convert.
 * @return the corresponding string representation.
 */
GIT_EXTERN(const char *) git_object_type2string(git_otype type);

/**
 * Convert a string object type representation to it's git_otype.
 *
 * @param str the string to convert.
 * @return the corresponding git_otype.
 */
GIT_EXTERN(git_otype) git_object_string2type(const char *str);

/**
 * Determine if the given git_otype is a valid loose object type.
 *
 * @param type object type to test.
 * @return true if the type represents a valid loose object type,
 * false otherwise.
 */
GIT_EXTERN(int) git_object_typeisloose(git_otype type);

/**
 * Get the size in bytes for the structure which
 * acts as an in-memory representation of any given
 * object type.
 *
 * For all the core types, this would the equivalent
 * of calling `sizeof(git_commit)` if the core types
 * were not opaque on the external API.
 *
 * @param type object type to get its size
 * @return size in bytes of the object
 */
GIT_EXTERN(size_t) git_object__size(git_otype type);

/** @} */
GIT_END_DECL

#endif


text:
"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""

from django.conf.urls import url, include
from django.contrib import admin
admin.autodiscover()

from oauth2_provider.ext.rest_framework import TokenHasReadWriteScope, TokenHasScope

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
    url(r'^', include('cinemizer.urls')),
]


text:
import test from 'tape-promise/tape';
import GL from '@luma.gl/constants';
import {VertexArrayObject} from '@luma.gl/gltools';

import {fixture} from 'test/setup';

test('WebGL#VertexArrayObject (default)#enable', (t) => {
  const {gl} = fixture;

  const vertexAttributes = VertexArrayObject.getDefaultArray(gl);

  const MAX_ATTRIBUTES = VertexArrayObject.getMaxAttributes(gl);
  t.ok(MAX_ATTRIBUTES >= 8, 'vertexAttributes.getMaxAttributes() >= 8');

  for (let i = 1; i < MAX_ATTRIBUTES; i++) {
    t.equal(
      vertexAttributes.getParameter(GL.VERTEX_ATTRIB_ARRAY_ENABLED, {location: i}),
      false,
      `vertex attribute ${i} should initially be disabled`
    );
  }

  for (let i = 0; i < MAX_ATTRIBUTES; i++) {
    vertexAttributes.enable(i);
  }

  for (let i = 0; i < MAX_ATTRIBUTES; i++) {
    t.equal(
      vertexAttributes.getParameter(GL.VERTEX_ATTRIB_ARRAY_ENABLED, {location: i}),
      true,
      `vertex attribute ${i} should now be enabled`
    );
  }

  for (let i = 1; i < MAX_ATTRIBUTES; i++) {
    vertexAttributes.enable(i, false);
  }

  // t.equal(vertexAttributes.getParameter(GL.VERTEX_ATTRIB_ARRAY_ENABLED, {location: 0}), true,
  //   'vertex attribute 0 should **NOT** be disabled');

  for (let i = 1; i < MAX_ATTRIBUTES; i++) {
    t.equal(
      vertexAttributes.getParameter(GL.VERTEX_ATTRIB_ARRAY_ENABLED, {location: i}),
      false,
      `vertex attribute ${i} should now be disabled`
    );
  }

  t.end();
});

test('WebGL#VertexArrayObject construct/delete', (t) => {
  const {gl} = fixture;

  if (!VertexArrayObject.isSupported(gl)) {
    t.comment('VertexArrayObjects not supported, skipping tests');
    t.end();
    return;
  }

  // @ts-expect-error
  t.throws(() => new VertexArrayObject(), 'VertexArrayObject throws on missing gl context');

  const vao = new VertexArrayObject(gl);
  t.ok(vao instanceof VertexArrayObject, 'VertexArrayObject construction successful');

  vao.delete();
  t.ok(vao instanceof VertexArrayObject, 'VertexArrayObject delete successful');

  vao.delete();
  t.ok(vao instanceof VertexArrayObject, 'VertexArrayObject repeated delete successful');

  t.end();
});

test('WebGL#vertexArrayObject#WebGL2 support', (t) => {
  const {gl2: gl} = fixture;

  if (!gl) {
    t.comment('VertexArrayObjects not supported, skipping tests');
    t.end();
    return;
  }

  t.ok(VertexArrayObject.isSupported(gl), 'VertexArrayObject is supported');

  const vertexAttributes = VertexArrayObject.getDefaultArray(gl);

  const MAX_ATTRIBUTES = VertexArrayObject.getMaxAttributes(gl);

  for (let i = 0; i < MAX_ATTRIBUTES; i++) {
    t.equal(
      vertexAttributes.getParameter(GL.VERTEX_ATTRIB_ARRAY_DIVISOR, {location: i}),
      0,
      `vertex attribute ${i} should have 0 divisor`
    );
  }

  t.end();
});

test('WebGL#VertexArrayObject#getConstantBuffer', (t) => {
  const {gl} = fixture;

  const vertexAttributes = VertexArrayObject.getDefaultArray(gl);

  let buffer = vertexAttributes.getConstantBuffer(100, new Float32Array([5, 4, 3]));

  t.equal(buffer.byteLength, 1200, 'byteLength should match');
  t.equal(buffer.bytesUsed, 1200, 'bytesUsed should match');

  buffer = vertexAttributes.getConstantBuffer(5, new Float32Array([5, 3, 2]));
  t.equal(buffer.byteLength, 1200, 'byteLength should be unchanged');
  t.equal(buffer.bytesUsed, 60, 'bytesUsed should have changed');

  const {gl2} = fixture;

  if (gl2) {
    const vertexAttributes2 = VertexArrayObject.getDefaultArray(gl2);
    buffer = vertexAttributes2.getConstantBuffer(5, new Float32Array([5, 3, 2]));
    t.equal(buffer.byteLength, 60, 'byteLength should be unchanged');
    t.equal(buffer.bytesUsed, 60, 'bytesUsed should have changed');
    const data = buffer.getData();
    t.deepEqual(
      data,
      new Float32Array([5, 3, 2, 5, 3, 2, 5, 3, 2, 5, 3, 2, 5, 3, 2]),
      'Constant buffer was correctly set'
    );
    t.comment(JSON.stringify(data));
  }

  t.end();
});


text:
{% extends "blog/base_blog.html" %}
{% load comments blog_tags markup_tags %}

{% block title %}{{ block.super }}: {{ post.title }}{% endblock %}

{% block content_title %}
	{% get_comment_count for post as comment_count %}

{{ post.title }}

			Published by {{ post.author.get_full_name }}
			{{ post.published|timesince }} ago{% if post.categories.all %} in {% for category in post.categories.all %}{{ category }}{% if not forloop.last %}, {% endif %}{% ifequal forloop.revcounter0 1 %} and {% endifequal %}{% endfor %}{% endif %}.
			{{ comment_count }} Comment{{ comment_count|pluralize }}

		{% if post.tags %}

			Tags
			{% for tag in post.tags.all %}{{ tag }}{% if not forloop.last %}, {% endif %}{% ifequal forloop.revcounter0 1 %} and {% endifequal %}{% endfor %}

{% endif %}

{% endblock %}

{% block content %}
	{% get_comment_count for post as comment_count %}
	{% get_comment_list for post as comment_list %}

{{ post.body|apply_markup:post.markup }}

	{% if post.related_objects.all or post.related_links.all %}

Related Links

		{% for object in post.related_objects.all %}

{{ object }}

		{% endfor %}
		{% for object in post.related_links.all %}

{{ object }}

		{% endfor %}

	{% endif %}

		{% if comment_count %}

Comments ({{ comment_count }})

				{% for comment in comment_list %}

							#
							{% if comment.url %}{{ comment.name }}{% else %}{{ comment.name }}{% endif %} said

						{{ comment.comment|striptags|urlizetrunc:"20"|linebreaks }}

{{ comment.submit_date|date:"P" }} on {{ comment.submit_date|date:"F j, Y" }}

				{% endfor %}

		{% endif %}
		{% if post.allow_comments %}
			{% render_comment_form for post %}
		{% else %}

Comments are closed.

Comments have been close for this post.

		{% endif %}

{% endblock %}


text:
package api

import akka.actor.Actor
import spray.http.StatusCodes._
import spray.http._
import spray.routing._
import spray.util.{LoggingContext, SprayActorLogging}

import scala.util.control.NonFatal

/**
 * Holds potential error response with the HTTP status and optional body
 *
 * @param responseStatus the status code
 * @param response the optional body
 */
case class ErrorResponseException(responseStatus: StatusCode, response: Option[HttpEntity]) extends Exception

/**
 * Provides a hook to catch exceptions and rejections from routes, allowing custom
 * responses to be provided, logs to be captured, and potentially remedial actions.
 *
 * Note that this is not marshalled, but it is possible to do so allowing for a fully
 * JSON API (e.g. see how Foursquare do it).
 */
trait FailureHandling {
  this: HttpService =>

  // For Spray > 1.1-M7 use routeRouteResponse
  // see https://groups.google.com/d/topic/spray-user/zA_KR4OBs1I/discussion
  def rejectionHandler: RejectionHandler = RejectionHandler.Default

  def exceptionHandler(implicit log: LoggingContext) = ExceptionHandler {

    case e: IllegalArgumentException => ctx =>
      loggedFailureResponse(ctx, e,
        message = "The server was asked a question that didn't make sense: " + e.getMessage,
        error = NotAcceptable)

    case e: NoSuchElementException => ctx =>
      loggedFailureResponse(ctx, e,
        message = "The server is missing some information. Try again in a few moments.",
        error = NotFound)

    case t: Throwable => ctx =>
      // note that toString here may expose information and cause a security leak, so don't do it.
      loggedFailureResponse(ctx, t)
  }

  private def loggedFailureResponse(ctx: RequestContext,
                                    thrown: Throwable,
                                    message: String = "The server is having problems.",
                                    error: StatusCode = InternalServerError)
                                   (implicit log: LoggingContext): Unit = {
    log.error(thrown, ctx.request.toString)
    ctx.complete(error, message)
  }

}

/**
 * Allows you to construct Spray ``HttpService`` from a concatenation of routes; and wires in the error handler.
 * It also logs all internal server errors using ``SprayActorLogging``.
 *
 * @param route the (concatenated) route
 */
class RoutedHttpService(route: Route) extends Actor with HttpService with SprayActorLogging {

  implicit def actorRefFactory = context

  implicit val handler = ExceptionHandler {
    case NonFatal(ErrorResponseException(statusCode, entity)) => ctx =>
      ctx.complete(statusCode, entity)

    case NonFatal(e) => ctx => {
      log.error(e, InternalServerError.defaultMessage)
      ctx.complete(InternalServerError)
    }
  }

  def receive: Receive =
    runRoute(route)(handler, RejectionHandler.Default, context, RoutingSettings.default, LoggingContext.fromActorRefFactory)

}


text:
import { Injectable } from '@angular/core';

import { Instructor } from './instructor.model';
import { instructors } from './instructors.mock';

@Injectable()
export class InstructorService {
    private instructors: Instructor[];

    constructor() {
        this.init();
    }

    public getInstructors(): Instructor[] {
        return this.instructors;
    }

    public getInstructor(id: number): Instructor {
        return this.instructors.find(instructor => instructor.id === +id);
    }

    private init(): void {
        this.instructors = instructors.sort(
            (instructorA, instructorB) => (instructorA.firstName + ' ' + instructorA.lastName).
                             localeCompare(instructorB.firstName + ' ' + instructorB.lastName));
    }
}


text:
import * as path from 'path';
import * as child_process from 'child_process';

const pathToExecPy = path.resolve(__dirname, 'exec.py');

async function exec(method, args = []) {
  const object = { method, args };
  const input = JSON.stringify(object);
  const result = child_process.execFileSync('python', [pathToExecPy], { input, encoding: 'utf8' });
  return JSON.parse(result);
}

export async function analyzeFile(path: string) {
  return exec('analyze_file', [path]);
}

export async function analyzeSourceCode(name: string, code: string) {
  return exec('analyze_file.analyze_source_code', [name, code]);
}


text:
package com.gmail.woodyc40.common.protocol;

import com.google.common.base.Charsets;
import net.tridentsdk.meta.MessageBuilder;
import net.tridentsdk.server.player.TridentPlayer;

/**
 * Tests the protocol class(es)
 *
 * @author Pierre C
 */
public class ProtocolTest {
    public static void main(String[] args) {
        /*
        ProtocolManagement management = ProtocolManagement.manager();
        management.intercept(event -> System.out.println(event.getClass() + " has happened"));

        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            management.transmit(new ProtocolEvent() {
            }, pipe -> {
                System.out.println("This is the " + finalI + "th round");
                return ProtocolAction.NO_PLAYERS;
            });
        }
        */

        /* // I haven't tested this LOL
        ProtocolManagement management = ProtocolManagement.manager();
        management.intercept(new ProtocolListener<PacketReceivedEvent>() {
            @Override
            public void intercept(PacketReceivedEvent event) {
                Packet packet = event.packet();
                if (packet.id() == 0x01) {
                    // Packet 0x01 received is player chat

                    // Read the first field
                    String string = (String) packet.read();

                    // Prevent it from being processed if you're
                    // a skythekidrs fanboy
                    if (string.contains("budder")) {
                        event.setIgnored(true);
                    } else {
                        String skythekidrs = "skythekidrs";
                        if (string.contains(skythekidrs)) {
                            // Strings are immutable
                            String newString = string.replace(skythekidrs, "");

                            // Write the first field
                            packet.write(newString);
                        }
                    }
                }
            }
        }); */

        // Not tested
        ProtocolManagement management = ProtocolManagement.manager();
        Packet packet = management.createPacket(0x02, true);

        // WRITING
        ByteAppender appender = ByteAppender.empty();
        appender.append(new MessageBuilder("Hello World").build().asJson().getBytes(Charsets.UTF_8));
        appender.append((byte) 0);
        packet.decode(appender.wrapped().peek());
        // or
        packet.write(new MessageBuilder("Hello World").build().asJson());
        packet.write((byte) 0);

        // SENDING
        management.send(appender, TridentPlayer.players());
        // or
        management.send(pipe -> {
            packet.encode(pipe);
            return TridentPlayer.players();
        });
    }
}


text:
#include <string>
#include <vector>

#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "internal.h"

bool ParseKeyValueArguments(std::map<std::string, std::string> *out_args,
                            const std::vector<std::string> &args,
                            const struct argument *templates) {
  out_args->clear();

  for (size_t i = 0; i < args.size(); i++) {
    const std::string &arg = args[i];
    const struct argument *templ = nullptr;
    for (size_t j = 0; templates[j].name[0] != 0; j++) {
      if (strcmp(arg.c_str(), templates[j].name) == 0) {
        templ = &templates[j];
        break;
      }
    }

    if (templ == nullptr) {
      fprintf(stderr, "Unknown argument: %s\n", arg.c_str());
      return false;
    }

    if (out_args->find(arg) != out_args->end()) {
      fprintf(stderr, "Duplicate argument: %s\n", arg.c_str());
      return false;
    }

    if (templ->type == kBooleanArgument) {
      (*out_args)[arg] = "";
    } else {
      if (i + 1 >= args.size()) {
        fprintf(stderr, "Missing argument for option: %s\n", arg.c_str());
        return false;
      }
      (*out_args)[arg] = args[++i];
    }
  }

  for (size_t j = 0; templates[j].name[0] != 0; j++) {
    const struct argument *templ = &templates[j];
    if (templ->type == kRequiredArgument &&
        out_args->find(templ->name) == out_args->end()) {
      fprintf(stderr, "Missing value for required argument: %s\n", templ->name);
      return false;
    }
  }

  return true;
}

void PrintUsage(const struct argument *templates) {
  for (size_t i = 0; templates[i].name[0] != 0; i++) {
    const struct argument *templ = &templates[i];
    fprintf(stderr, "%s\t%s\n", templ->name, templ->description);
  }
}

bool GetUnsigned(unsigned *out, const std::string &arg_name,
                 unsigned default_value,
                 const std::map<std::string, std::string> &args) {
  const auto &it = args.find(arg_name);
  if (it == args.end()) {
    *out = default_value;
    return true;
  }

  const std::string &value = it->second;
  if (value.empty()) {
    return false;
  }

  errno = 0;
  char *endptr;
  unsigned long int num = strtoul(value.c_str(), &endptr, 10);
  if (num == ULONG_MAX && errno == ERANGE) {
    return false;
  }
  if (*endptr != 0 || num > UINT_MAX) {
    return false;
  }
  *out = static_cast<unsigned>(num);

  return true;
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Status (twitter4j-core 4.0.4 API)</title>
<meta name="date" content="2015-06-23">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

twitter4j

Interface Status

All Superinterfaces:

Comparable<Status>, EntitySupport, Serializable, TwitterResponse

public interface Status
extends Comparable<Status>, TwitterResponse, EntitySupport, Serializable

A data interface representing one single status of a user.

Author:

Yusuke Yamamoto - yusuke at mac.com

Field Summary

Fields inherited from interface twitter4j.TwitterResponse

NONE, READ, READ_WRITE, READ_WRITE_DIRECTMESSAGES

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

long[]
getContributors()

Returns an array of contributors, or null if no contributor is associated with this status.

Date
getCreatedAt()

Return the created_at

long
getCurrentUserRetweetId()

Returns the authenticating user's retweet's id of this tweet, or -1L when the tweet was created
 before this feature was enabled.

int
getFavoriteCount()

Indicates approximately how many times this Tweet has been "favorited" by Twitter users.

GeoLocation
getGeoLocation()

Returns The location that this tweet refers to if available.

long
getId()

Returns the id of the status

String
getInReplyToScreenName()

Returns the in_reply_to_screen_name

long
getInReplyToStatusId()

Returns the in_reply_tostatus_id

long
getInReplyToUserId()

Returns the in_reply_user_id

String
getLang()

Returns the lang of the status text if available.

Place
getPlace()

Returns the place attached to this status

Status
getQuotedStatus()

Returns the Tweet object of the original Tweet that was quoted.

long
getQuotedStatusId()

Returns the Tweet ID of the quoted Tweet

int
getRetweetCount()

Returns the number of times this tweet has been retweeted, or -1 when the tweet was
 created before this feature was enabled.

Status
getRetweetedStatus()

Scopes
getScopes()

Returns the targeting scopes applied to a status.

String
getSource()

Returns the source

String
getText()

Returns the text of the status

User
getUser()

Return the user associated with the status.

 This can be null if the instance is from User.getStatus().

String[]
getWithheldInCountries()

Returns the list of country codes where the tweet is withheld

boolean
isFavorited()

Test if the status is favorited

boolean
isPossiblySensitive()

Returns true if the status contains a link that is identified as sensitive.

boolean
isRetweet()

boolean
isRetweeted()

Test if the status is retweeted

boolean
isRetweetedByMe()

Returns true if the authenticating user has retweeted this tweet, or false when the tweet was
 created before this feature was enabled.

boolean
isTruncated()

Test if the status is truncated

Methods inherited from interface java.lang.Comparable

compareTo

Methods inherited from interface twitter4j.TwitterResponse

getAccessLevel, getRateLimitStatus

Methods inherited from interface twitter4j.EntitySupport

getExtendedMediaEntities, getHashtagEntities, getMediaEntities, getSymbolEntities, getURLEntities, getUserMentionEntities

Method Detail

getCreatedAt

Date getCreatedAt()

Return the created_at

Returns:

created_at

Since:

Twitter4J 1.1.0

getId

long getId()

Returns the id of the status

Returns:

the id

getText

String getText()

Returns the text of the status

Returns:

the text

getSource

String getSource()

Returns the source

Returns:

the source

Since:

Twitter4J 1.0.4

isTruncated

boolean isTruncated()

Test if the status is truncated

Returns:

true if truncated

Since:

Twitter4J 1.0.4

getInReplyToStatusId

long getInReplyToStatusId()

Returns the in_reply_tostatus_id

Returns:

the in_reply_tostatus_id

Since:

Twitter4J 1.0.4

getInReplyToUserId

long getInReplyToUserId()

Returns the in_reply_user_id

Returns:

the in_reply_tostatus_id

Since:

Twitter4J 1.0.4

getInReplyToScreenName

String getInReplyToScreenName()

Returns the in_reply_to_screen_name

Returns:

the in_in_reply_to_screen_name

Since:

Twitter4J 2.0.4

getGeoLocation

GeoLocation getGeoLocation()

Returns The location that this tweet refers to if available.

Returns:

returns The location that this tweet refers to if available (can be null)

Since:

Twitter4J 2.1.0

getPlace

Place getPlace()

Returns the place attached to this status

Returns:

The place attached to this status

Since:

Twitter4J 2.1.1

isFavorited

boolean isFavorited()

Test if the status is favorited

Returns:

true if favorited

Since:

Twitter4J 1.0.4

isRetweeted

boolean isRetweeted()

Test if the status is retweeted

Returns:

true if retweeted

Since:

Twitter4J 3.0.4

getFavoriteCount

int getFavoriteCount()

Indicates approximately how many times this Tweet has been "favorited" by Twitter users.

Returns:

the favorite count

Since:

Twitter4J 3.0.4

getUser

User getUser()

Return the user associated with the status.

 This can be null if the instance is from User.getStatus().

Returns:

the user

isRetweet

boolean isRetweet()

Returns:

if the status is retweet or not

Since:

Twitter4J 2.0.10

getRetweetedStatus

Status getRetweetedStatus()

Returns:

retweeted status

Since:

Twitter4J 2.1.0

getContributors

long[] getContributors()

Returns an array of contributors, or null if no contributor is associated with this status.

Returns:

contributors

Since:

Twitter4J 2.2.3

getRetweetCount

int getRetweetCount()

Returns the number of times this tweet has been retweeted, or -1 when the tweet was
 created before this feature was enabled.

Returns:

the retweet count.

isRetweetedByMe

boolean isRetweetedByMe()

Returns true if the authenticating user has retweeted this tweet, or false when the tweet was
 created before this feature was enabled.

Returns:

whether the authenticating user has retweeted this tweet.

Since:

Twitter4J 2.1.4

getCurrentUserRetweetId

long getCurrentUserRetweetId()

Returns the authenticating user's retweet's id of this tweet, or -1L when the tweet was created
 before this feature was enabled.

Returns:

the authenticating user's retweet's id of this tweet

Since:

Twitter4J 3.0.1

isPossiblySensitive

boolean isPossiblySensitive()

Returns true if the status contains a link that is identified as sensitive.

Returns:

whether the status contains sensitive links

Since:

Twitter4J 3.0.0

getLang

String getLang()

Returns the lang of the status text if available.

Returns:

two-letter iso language code

Since:

Twitter4J 3.0.6

getScopes

Scopes getScopes()

Returns the targeting scopes applied to a status.

Returns:

the targeting scopes applied to a status.

Since:

Twitter4J 3.0.6

getWithheldInCountries

String[] getWithheldInCountries()

Returns the list of country codes where the tweet is withheld

Returns:

list of country codes where the tweet is withheld - null if not withheld

Since:

Twitter4j 4.0.3

getQuotedStatusId

long getQuotedStatusId()

Returns the Tweet ID of the quoted Tweet

Returns:

the Tweet ID of the quoted Tweet

Since:

Twitter4J 4.0.4

getQuotedStatus

Status getQuotedStatus()

Returns the Tweet object of the original Tweet that was quoted.

Returns:

the quoted Tweet object

Since:

Twitter4J 4.0.4

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015. All rights reserved.


text:
package org.jkiss.dbeaver.registry;

import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.DBPDataSourceContainer;
import org.jkiss.dbeaver.model.access.DBAAuthProfile;
import org.jkiss.dbeaver.model.net.DBWHandlerConfiguration;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

class SecureCredentials {

    @Nullable
    private String userName;
    @Nullable
    private String userPassword;
    @Nullable
    private Map<String, String> properties;

    public SecureCredentials() {
    }

    public SecureCredentials(@NotNull DBPDataSourceContainer dataSource) {
        this.userName = dataSource.getConnectionConfiguration().getUserName();
        this.userPassword = dataSource.isSavePassword() ? dataSource.getConnectionConfiguration().getUserPassword() : null;
    }

    public SecureCredentials(@NotNull DBAAuthProfile profile) {
        this.userName = profile.getUserName();
        this.userPassword = profile.getUserPassword();
        this.properties = profile.getProperties();
    }

    public SecureCredentials(@NotNull DBWHandlerConfiguration handlerConfiguration) {
        this.userName = handlerConfiguration.getUserName();
        this.userPassword = handlerConfiguration.isSavePassword() ? handlerConfiguration.getPassword() : null;
    }

    @Nullable
    public String getUserName() {
        return userName;
    }

    public void setUserName(@Nullable String userName) {
        this.userName = userName;
    }

    @Nullable
    public String getUserPassword() {
        return userPassword;
    }

    public void setUserPassword(@Nullable String userPassword) {
        this.userPassword = userPassword;
    }

    @Nullable
    public Map<String, String> getProperties() {
        return properties;
    }

    public void setProperties(@NotNull Map<String, String> properties) {
        if (this.properties != null) {
            this.properties.clear();
            this.properties.putAll(properties);
        } else {
            this.properties = new HashMap<>(properties);
        }
    }

    public void setSecureProp(String key, String value) {
        if (this.properties == null) {
            this.properties = new LinkedHashMap<>();
        }
        this.properties.put(key, value);
    }
}


text:
package com.beanframework.user.domain;

import java.util.UUID;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface RoleRepository extends JpaRepository<Role, UUID>, JpaSpecificationExecutor<Role> {

	@Query("select count(r) > 0 from Role r where r.uuid = :uuid")
	public boolean isRoleExists(@Param("uuid") UUID uuid);

	@Query("select count(r) > 0 from Role r where r.name = :name")
	public boolean isNameExists(@Param("name") String name);

	@Query(value = "select r from Role r where r.name = ?1")
	Role findByName(String name);

	@Modifying
	@Query("delete from Role r where r.name = :name")
	void deleteByName(@Param("name") String name);
}