text:
import React from "react";
import PropTypes from "prop-types";
import invariant from "tiny-invariant";
import warning from "tiny-warning";

import RouterContext from "./RouterContext.js";
import matchPath from "./matchPath.js";

/**
 * The public API for rendering the first <Route> that matches.
 */
class Switch extends React.Component {
  render() {
    return (
      <RouterContext.Consumer>
        {context => {
          invariant(context, "You should not use <Switch> outside a <Router>");

          const location = this.props.location || context.location;

          let element, match;

          // We use React.Children.forEach instead of React.Children.toArray().find()
          // here because toArray adds keys to all child elements and we do not want
          // to trigger an unmount/remount for two <Route>s that render the same
          // component at different URLs.
          React.Children.forEach(this.props.children, child => {
            if (match == null && React.isValidElement(child)) {
              element = child;

              const path = child.props.path || child.props.from;

              match = path
                ? matchPath(location.pathname, { ...child.props, path })
                : context.match;
            }
          });

          return match
            ? React.cloneElement(element, { location, computedMatch: match })
            : null;
        }}
      </RouterContext.Consumer>
    );
  }
}

if (__DEV__) {
  Switch.propTypes = {
    children: PropTypes.node,
    location: PropTypes.object
  };

  Switch.prototype.componentDidUpdate = function(prevProps) {
    warning(
      !(this.props.location && !prevProps.location),
      '<Switch> elements should not change from uncontrolled to controlled (or vice versa). You initially used no "location" prop and then provided one on a subsequent render.'
    );

    warning(
      !(!this.props.location && prevProps.location),
      '<Switch> elements should not change from controlled to uncontrolled (or vice versa). You provided a "location" prop initially but omitted it on a subsequent render.'
    );
  };
}

export default Switch;


text:
package org.elasticsearch.xpack.searchablesnapshots.hdfs;

import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.xpack.searchablesnapshots.AbstractSearchableSnapshotsRestTestCase;

import static org.hamcrest.Matchers.blankOrNullString;
import static org.hamcrest.Matchers.not;

public class HdfsSearchableSnapshotsIT extends AbstractSearchableSnapshotsRestTestCase {
    @Override
    protected String repositoryType() {
        return "hdfs";
    }

    @Override
    protected Settings repositorySettings() {
        final String uri = System.getProperty("test.hdfs.uri");
        assertThat(uri, not(blankOrNullString()));

        final String path = System.getProperty("test.hdfs.path");
        assertThat(path, not(blankOrNullString()));

        // Optional based on type of test
        final String principal = System.getProperty("test.krb5.principal.es");

        Settings.Builder repositorySettings = Settings.builder().put("client", "searchable_snapshots").put("uri", uri).put("path", path);
        if (principal != null) {
            repositorySettings.put("security.principal", principal);
        }
        return repositorySettings.build();
    }
}

redpajama_set_name: RedPajamaGithub


text:
#include "fork2019.h"

#include <stdbool.h>

#include "../../../common/commons.h"

#include "../../../common/cmd/commonCommand.h"

#include "../../../common/error/error.h"

#include "../../../common/delay/cenDelay.h"

#include "../../../common/io/inputStream.h"
#include "../../../common/io/outputStream.h"
#include "../../../common/io/printWriter.h"
#include "../../../common/io/reader.h"

#include "../../../common/pwm/servo/servoPwm.h"
#include "../../../common/pwm/servo/servoList.h"

#include "../../../common/log/logger.h"
#include "../../../common/log/logLevel.h"

#include "../../../common/timer/delayTimer.h"

#include "../../../drivers/tof/tofList.h"

#include "forkScan2019.h"
#include "../elevator/elevator2019.h"
#include "../arm/arm2019.h"
#include "../../robot.h"

/**
 * @param servoList the list of servo
 * @param leftRight
 * @param leftServoIndex
 * @param rightServoIndex
 * @param leftSpeed
 * @param rightSpeed
 * @param leftPosition
 * @param rightPosition
 */
void fork2019MoveServo(ServoList* servoList,
        unsigned int leftRight,
        unsigned int leftServoIndex,
        unsigned int rightServoIndex,
        unsigned int leftSpeed,
        unsigned int rightSpeed,
        unsigned int leftPosition,
        unsigned rightPosition,
        bool wait) {
    if (leftRight == FORK_2019_LEFT_INDEX) {
        Servo* servo = getServo(servoList, leftServoIndex);
        pwmServo(servo, leftSpeed, leftPosition, wait);
    } else if (leftRight == FORK_2019_RIGHT_INDEX) {
        Servo* servo = getServo(servoList, rightServoIndex);
        pwmServo(servo, rightSpeed, rightPosition, wait);
    } else if (leftRight == FORK_2019_LEFT_AND_RIGHT_INDEX) {
        Servo* leftServo = getServo(servoList, leftServoIndex);
        // We don't wait both time for left & right (the delay is blocking), so we don't put "wait", but false on delay parameter
        pwmServo(leftServo, leftSpeed, leftPosition, false);
        Servo* rightServo = getServo(servoList, rightServoIndex);
        pwmServo(rightServo, rightSpeed, rightPosition, wait);
    }
}

void moveForkBack(ServoList* servoList, unsigned int leftRight, bool wait) {
    fork2019MoveServo(servoList, leftRight,
            FORK_2019_LEFT_SERVO_FORK_INDEX, FORK_2019_RIGHT_SERVO_FORK_INDEX,
            FORK_2019_SERVO_LEFT_SPEED_FACTOR, FORK_2019_SERVO_RIGHT_SPEED_FACTOR,
            FORK_2019_SERVO_LEFT_RETRACTED_SERVO_VALUE, FORK_2019_SERVO_RIGHT_RETRACTED_SERVO_VALUE,
            wait);
}

void moveForkBackAllWithoutWait(ServoList* servoList) {
    moveForkBack(servoList, FORK_2019_LEFT_AND_RIGHT_INDEX, false);
}

void moveForkSimplePuck(ServoList* servoList, unsigned int leftRight, bool wait) {
    fork2019MoveServo(servoList, leftRight,
            FORK_2019_LEFT_SERVO_FORK_INDEX, FORK_2019_RIGHT_SERVO_FORK_INDEX,
            FORK_2019_SERVO_LEFT_SPEED_FACTOR, FORK_2019_SERVO_RIGHT_SPEED_FACTOR,
            FORK_2019_SERVO_LEFT_SIMPLE_PUCK_SERVO_VALUE, FORK_2019_SERVO_RIGHT_SIMPLE_PUCK_SERVO_VALUE,
            wait);
}

void moveForkDoublePuck(ServoList* servoList, unsigned int leftRight, bool wait) {
    fork2019MoveServo(servoList, leftRight,
            FORK_2019_LEFT_SERVO_FORK_INDEX, FORK_2019_RIGHT_SERVO_FORK_INDEX,
            FORK_2019_SERVO_LEFT_SPEED_FACTOR, FORK_2019_SERVO_RIGHT_SPEED_FACTOR,
            FORK_2019_SERVO_LEFT_DOUBLE_PUCK_SERVO_VALUE, FORK_2019_SERVO_RIGHT_DOUBLE_PUCK_SERVO_VALUE,
            wait);
}

void moveForkPushOff(ServoList* servoList, unsigned int leftRight, bool wait) {
    fork2019MoveServo(servoList, leftRight,
            FORK_2019_LEFT_SERVO_PUSH_INDEX, FORK_2019_RIGHT_SERVO_PUSH_INDEX,
            FORK_2019_SERVO_PUSH_LEFT_SPEED_FACTOR, FORK_2019_SERVO_PUSH_LEFT_SPEED_FACTOR,
            FORK_2019_SERVO_PUSH_LEFT_OFF_SERVO_VALUE, FORK_2019_SERVO_PUSH_RIGHT_OFF_SERVO_VALUE,
            wait);
}

void moveForkPushOn(ServoList* servoList, unsigned int leftRight, bool wait) {
    enum RobotType robotType = getRobotType();
    if (robotType == ROBOT_TYPE_BIG) {
        fork2019MoveServo(servoList, leftRight,
                FORK_2019_LEFT_SERVO_PUSH_INDEX, FORK_2019_RIGHT_SERVO_PUSH_INDEX,
                FORK_2019_SERVO_PUSH_LEFT_SPEED_FACTOR, FORK_2019_SERVO_PUSH_LEFT_SPEED_FACTOR,
                FORK_2019_BIG_ROBOT_SERVO_PUSH_LEFT_ON_SERVO_VALUE, FORK_2019_BIG_ROBOT_SERVO_PUSH_RIGHT_ON_SERVO_VALUE,
                wait);
    } else if (robotType == ROBOT_TYPE_SMALL) {
        fork2019MoveServo(servoList, leftRight,
                FORK_2019_LEFT_SERVO_PUSH_INDEX, FORK_2019_RIGHT_SERVO_PUSH_INDEX,
                FORK_2019_SERVO_PUSH_LEFT_SPEED_FACTOR, FORK_2019_SERVO_PUSH_LEFT_SPEED_FACTOR,
                FORK_2019_SMALL_ROBOT_SERVO_PUSH_LEFT_ON_SERVO_VALUE, FORK_2019_SMALL_ROBOT_SERVO_PUSH_RIGHT_ON_SERVO_VALUE,
                wait);
    }
}

void moveForkPushOffAllWithoutWait(ServoList* servoList) {
    moveForkPushOff(servoList, FORK_2019_LEFT_AND_RIGHT_INDEX, false);
}

// COMPLEXE OPERATIONS

void fork2019Init(ServoList* servoList) {
    // We do not wait because the robot is initializing
    bool wait = false;

    // Go to the bottom
    moveElevatorBottom(servoList, wait);

    // Center the Elevator
    moveElevatorMiddle(servoList, wait);

    // Fork Push Off
    moveForkPushOff(servoList, FORK_2019_LEFT_AND_RIGHT_INDEX, wait);

    // Fork Retracted
    moveForkBack(servoList, FORK_2019_LEFT_AND_RIGHT_INDEX, wait);
}

void updateServoProperties2019(ServoList* servoList) {
    if (servoList == NULL) {
        writeError(SERVO_LIST_NULL);
    }

    // Arm (For small Robot only))
    getServo(servoList, FORK_2019_LEFT_ARM_SERVO_INDEX)->name = "ARM LEFT";
    getServo(servoList, FORK_2019_RIGHT_ARM_SERVO_INDEX)->name = "ARM RIGHT";

    // Elevator
    // -> Up/Down
    getServo(servoList, FORK_2019_ELEVATOR_SERVO_INDEX)->name = "ELEV. UP/DOWN";
    getServo(servoList, FORK_2019_ELEVATOR_SERVO_INDEX)->maxSpeedUnderLoad = FORK_2019_ELEVATOR_MAX_SPEED_UNDER_LOAD;

    // Left / Right (Scan)
    getServo(servoList, FORK_2019_SCAN_SERVO_INDEX)->name = "ELEV SCAN";
    getServo(servoList, FORK_2019_SCAN_SERVO_INDEX)->maxSpeedUnderLoad = FORK_2019_ELEVATOR_SCAN_MAX_SPEED_UNDER_LOAD;

    // Fork
    getServo(servoList, FORK_2019_LEFT_SERVO_FORK_INDEX)->name = "FORK LEFT";
    getServo(servoList, FORK_2019_LEFT_SERVO_FORK_INDEX)->maxSpeedUnderLoad = FORK_2019_ELEVATOR_FORK_MAX_SPEED_UNDER_LOAD;
    getServo(servoList, FORK_2019_RIGHT_SERVO_FORK_INDEX)->name = "FORK RIGHT";
    getServo(servoList, FORK_2019_RIGHT_SERVO_FORK_INDEX)->maxSpeedUnderLoad = FORK_2019_ELEVATOR_FORK_MAX_SPEED_UNDER_LOAD;

    // Fork Push
    getServo(servoList, FORK_2019_LEFT_SERVO_PUSH_INDEX)->name = "PUSH LEFT";
    getServo(servoList, FORK_2019_LEFT_SERVO_PUSH_INDEX)->maxSpeedUnderLoad = FORK_2019_ELEVATOR_FORK_PUSH_MAX_SPEED_UNDER_LOAD;
    getServo(servoList, FORK_2019_RIGHT_SERVO_PUSH_INDEX)->name = "PUSH RIGHT";
    getServo(servoList, FORK_2019_RIGHT_SERVO_PUSH_INDEX)->maxSpeedUnderLoad = FORK_2019_ELEVATOR_FORK_PUSH_MAX_SPEED_UNDER_LOAD;
}


text:
import { ResourceIndex } from "../../../resources/interfaces";
import { DropDownItem } from "../../../ui";
import { ResourceUpdate, TaggedSequence } from "farmbot";

/** Function that converts resources into dropdown selections based on
 * use-case specific rules */
export type ListBuilder = (i: ResourceIndex) => DropDownItem[];

/** Shape of step.args when step.kind = "resource_update" */
export type ResourceUpdateArgs = Partial<ResourceUpdate["args"]>;

/** Input data for calls to commitStepChanges() */
export interface MarkAsEditProps {
  nextAction: DropDownItem;
  nextResource: DropDownItem | undefined;
  step: ResourceUpdate;
  index: number;
  sequence: TaggedSequence
}

export interface StepWithResourceIndex {
  step: ResourceUpdate;
  resourceIndex: ResourceIndex;
}

/** A pair of DropDownItems used to render the currently selected items in the
 * "Mark As.." block. */
export interface DropDownPair {
  /** Left side drop down */
  leftSide: DropDownItem;
  /** Right side drop down */
  rightSide: DropDownItem;
}


text:
using Google.Cloud.Spanner.Data;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

public class QueryWithBytesAsyncSample
{
    public class Venue
    {
        public int VenueId { get; set; }
        public string VenueName { get; set; }
    }

    public async Task<List<Venue>> QueryWithBytesAsync(string projectId, string instanceId, string databaseId)
    {
        string connectionString = $"Data Source=projects/{projectId}/instances/{instanceId}/databases/{databaseId}";
        // Initialize a Bytes array to use for querying.
        string sampleText = "Hello World 1";
        byte[] exampleBytes = Encoding.UTF8.GetBytes(sampleText);

        using var connection = new SpannerConnection(connectionString);
        var cmd = connection.CreateSelectCommand("SELECT VenueId, VenueName FROM Venues WHERE VenueInfo = @ExampleBytes");
        cmd.Parameters.Add("ExampleBytes", SpannerDbType.Bytes, exampleBytes);

        var venues = new List<Venue>();
        using var reader = await cmd.ExecuteReaderAsync();
        while (await reader.ReadAsync())
        {
            venues.Add(new Venue
            {
                VenueId = reader.GetFieldValue<int>("VenueId"),
                VenueName = reader.GetFieldValue<string>("VenueName")
            });
        }
        return venues;
    }
}
// [END spanner_query_with_bytes_parameter]


text:
<!DOCTYPE html>

    <title>p43-1打印预览</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet"/>
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/>
    <link href="data/styles.css" type="text/css" rel="stylesheet"/>
    <link href="files/p43-1打印预览/styles.css" type="text/css" rel="stylesheet"/>

欢迎您,Yicold  管理员

注销

结算数据

/

Copyright © 2009-2015 WEIBO 北京微梦创科网络技术有限公司京网文[2014]2046-296号京ICP备12002058号增值电信业务经营许可证B2-20140447

打印

打印预览

NO.格式:业务+年月日+序号

示例:A201511120001

业务代码:

专线A;拼车B;包车C

序号格式:0001-9999


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Security.Cryptography;

namespace Microsoft.Composition.Metadata
{
    public static class ExtensionMethods
    {
        public static string GetFullTypeName(this MetadataReader metadataReader, Handle handle)
        {
            if (handle.HandleType == HandleType.Type)
            {
                return GetFullTypeName(metadataReader, (TypeHandle)handle);
            }
            else if (handle.HandleType == HandleType.TypeReference)
            {
                return GetFullTypeName(metadataReader, (TypeReferenceHandle)handle);
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        public static string GetFullTypeName(this MetadataReader metadataReader, TypeReferenceHandle typeReferenceHandle)
        {
            var typeReference = metadataReader.GetTypeReference(typeReferenceHandle);
            return GetFullTypeName(metadataReader, typeReference);
        }

        public static string GetFullTypeName(this MetadataReader metadataReader, TypeHandle typeHandle)
        {
            var typeDefinition = metadataReader.GetTypeDefinition(typeHandle);
            return metadataReader.GetFullTypeName(typeDefinition);
        }

        public static string GetFullTypeName(this MetadataReader metadataReader, TypeDefinition typeDefinition)
        {
            var name = metadataReader.GetString(typeDefinition.Namespace) ?? "";
            if (name != "")
            {
                name = name + ".";
            }

            name = name + metadataReader.GetString(typeDefinition.Name);
            return name;
        }

        public static string GetFullTypeName(this MetadataReader metadataReader, TypeReference typeReference)
        {
            var name = metadataReader.GetString(typeReference.Namespace) ?? "";
            if (name != "")
            {
                name = name + ".";
            }

            name = name + metadataReader.GetString(typeReference.Name);
            return name;
        }

        public static string GetFullAssemblyName(this MetadataReader metadataReader)
        {
            return GetFullAssemblyName(metadataReader, metadataReader.GetAssemblyDefinition());
        }

        public static string GetFullAssemblyName(this MetadataReader metadataReader, AssemblyDefinition assemblyDefinition)
        {
            var assemblyName = metadataReader.GetString(assemblyDefinition.Name);
            var culture = metadataReader.GetString(assemblyDefinition.Culture);
            if (string.IsNullOrEmpty(culture))
            {
                culture = "neutral";
            }

            var version = assemblyDefinition.Version;
            var publicKeyBytes = metadataReader.GetBytes(assemblyDefinition.PublicKey);
            byte[] publicKeyTokenBytes = publicKeyBytes;
            string publicKeyToken = "null";
            if (publicKeyBytes.Length > 0)
            {
                publicKeyTokenBytes = CalculatePublicKeyToken(publicKeyBytes);
                publicKeyToken = Conversion.ByteArrayToHexString(publicKeyTokenBytes);
            }

            var fullAssemblyName = string.Format(
                "{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
                assemblyName,
                version.ToString(),
                culture,
                publicKeyToken);
            return fullAssemblyName;
        }

        public static string GetFullAssemblyName(this MetadataReader metadataReader, AssemblyReference assemblyReference)
        {
            var assemblyName = metadataReader.GetString(assemblyReference.Name);
            var culture = metadataReader.GetString(assemblyReference.Culture);
            if (string.IsNullOrEmpty(culture))
            {
                culture = "neutral";
            }

            var version = assemblyReference.Version;
            var publicKeyTokenBytes = metadataReader.GetBytes(assemblyReference.PublicKeyOrToken);
            var publicKeyToken = Conversion.ByteArrayToHexString(publicKeyTokenBytes);
            publicKeyToken = string.IsNullOrEmpty(publicKeyToken) ? "null" : publicKeyToken;

            var fullAssemblyName = string.Format(
                "{0}, Version={1}, Culture={2}, PublicKeyToken={3}",
                assemblyName,
                version.ToString(),
                culture,
                publicKeyToken);
            return fullAssemblyName;
        }

        public static IEnumerable<string> GetReferenceAssemblyPartialNames(this MetadataReader metadataReader)
        {
            foreach (var assemblyReferenceHandle in metadataReader.AssemblyReferences)
            {
                var assemblyReference = metadataReader.GetAssemblyReference(assemblyReferenceHandle);
                var partialName = metadataReader.GetString(assemblyReference.Name);
                yield return partialName;
            }
        }

        public static bool ReferencesAssembly(this MetadataReader metadataReader, string partialAssemblyName)
        {
            var references = metadataReader.GetReferenceAssemblyPartialNames();
            return references.Any(r => string.Equals(r, partialAssemblyName, StringComparison.OrdinalIgnoreCase));
        }

        public static IEnumerable<string> GetReferenceAssemblyFullNames(this MetadataReader metadataReader)
        {
            foreach (var assemblyReferenceHandle in metadataReader.AssemblyReferences)
            {
                var assemblyReference = metadataReader.GetAssemblyReference(assemblyReferenceHandle);
                var fullAssemblyName = metadataReader.GetFullAssemblyName(assemblyReference);
                yield return fullAssemblyName;
            }
        }

        private static byte[] CalculatePublicKeyToken(byte[] publicKeyBytes)
        {
            using (var sha1 = new SHA1Cng())
            {
                publicKeyBytes = sha1.ComputeHash(publicKeyBytes);
            }

            byte[] result = new byte[8];
            int length = publicKeyBytes.Length - 1;
            for (int i = 0; i < 8; i++)
            {
                result[i] = publicKeyBytes[length - i];
            }

            return result;
        }

        public static Handle GetAttributeTypeHandle(this MetadataReader metadataReader, CustomAttribute customAttribute)
        {
            Handle attributeTypeHandle;
            var ctor = customAttribute.Constructor;
            if (ctor.HandleType == HandleType.MemberReference)
            {
                var memberReferenceHandle = (MemberReferenceHandle)ctor;
                var memberReference = metadataReader.GetMemberReference(memberReferenceHandle);
                attributeTypeHandle = memberReference.Parent;
            }
            else
            {
                MethodHandle methodHandle = (MethodHandle)ctor;
                var method = metadataReader.GetMethod(methodHandle);
                attributeTypeHandle = metadataReader.GetDeclaringType(methodHandle);
            }

            return attributeTypeHandle;
        }
    }
}


text:
#region Copyright & License

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

#endregion

using System;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using Be.Stateless.BizTalk.ContextProperties;
using Be.Stateless.BizTalk.Runtime.Caching;
using Be.Stateless.BizTalk.Transform;
using Be.Stateless.BizTalk.Transforms.ToSql.Procedures.Batch;
using Be.Stateless.BizTalk.Unit.Resources;
using Be.Stateless.BizTalk.Unit.Transform;
using Be.Stateless.BizTalk.Xml;
using Be.Stateless.IO;
using Microsoft.BizTalk.Message.Interop;
using Moq;
using NUnit.Framework;

namespace Be.Stateless.BizTalk.Streaming.Extensions
{
	[TestFixture]
	public class TransformerFixture
	{
		[Test]
		public void ApplyTransformsWithImportedAndIncludedStylesheets()
		{
			using (var stream = ResourceManager.Load("Be.Stateless.BizTalk.Streaming.Data.BatchContent.xml").Transform().Apply(typeof(CompositeEmbeddedTransform)))
			using (var reader = XmlReader.Create(stream))
			{
				reader.MoveToContent();
				Assert.That(
					reader.ReadOuterXml(),
					Contains.Substring("\n  <ns:Parts>\n    dropped by Included.xsl\n    dropped by Imported.xsl\n    dropped by EmbeddedTransform.xsl\n  </ns:Parts>"));
			}
		}

		[Test]
		public void BuildArgumentListYieldsFreshCopyWhenRequired()
		{
			var arguments = new XsltArgumentList();
			var contextMock = new Mock<IBaseMessageContext>();

			var sut = new Transformer(new Stream[] { new MemoryStream() });
			sut.ExtendWith(contextMock.Object);

			var descriptor = XsltCache.Instance[typeof(IdentityTransform)];

			// no specific arguments, no message ctxt requirement, same XsltArgumentList instance can be shared
			Assert.That(sut.BuildArgumentList(descriptor, null), Is.SameAs(descriptor.Arguments));

			// specific arguments, no message ctxt requirement, new XsltArgumentList instance is required
			Assert.That(sut.BuildArgumentList(descriptor, arguments), Is.Not.SameAs(descriptor.Arguments).And.Not.SameAs(arguments));

			descriptor = XsltCache.Instance[typeof(AnyToAddPart)];

			// no specific arguments but message ctxt requirement, new XsltArgumentList instance is required
			Assert.That(sut.BuildArgumentList(descriptor, null), Is.Not.SameAs(descriptor.Arguments).And.Not.SameAs(arguments));

			// specific arguments and message ctxt requirement, new XsltArgumentList instance is required
			Assert.That(sut.BuildArgumentList(descriptor, arguments), Is.Not.SameAs(descriptor.Arguments).And.Not.SameAs(arguments));
		}

		[Test]
		public void HonorsMessageContextExtensionRequirements()
		{
			var stream = new StringStream("<?xml version=\"1.0\" encoding=\"utf-16\" ?><root></root>");
			var contextMock = new Mock<IBaseMessageContext>();
			var transform = typeof(AnyToAddPart);
			var arguments = XsltCache.Instance[transform].Arguments;

			Assert.That(arguments.GetExtensionObject(BaseMessageContextFunctions.TARGET_NAMESPACE), Is.Null);

			var sut = new Transformer(new Stream[] { stream });
			sut.ExtendWith(contextMock.Object).Apply(transform);

			Assert.That(arguments.GetExtensionObject(BaseMessageContextFunctions.TARGET_NAMESPACE), Is.Null);

			contextMock.Verify(c => c.Read(BizTalkFactoryProperties.EnvelopeSpecName.Name, BizTalkFactoryProperties.EnvelopeSpecName.Namespace), Times.Once());
			contextMock.Verify(c => c.Read(TrackingProperties.MessagingStepActivityId.Name, TrackingProperties.MessagingStepActivityId.Namespace), Times.Once());
		}

		[Test]
		public void NoMessageContextExtensionRequirements()
		{
			var stream = new StringStream("<?xml version=\"1.0\" encoding=\"utf-16\" ?><root></root>");
			var transform = typeof(IdentityTransform);
			var arguments = XsltCache.Instance[transform].Arguments;
			Assert.That(arguments.GetExtensionObject(BaseMessageContextFunctions.TARGET_NAMESPACE), Is.Null);

			var sut = new Transformer(new Stream[] { stream });
			sut.Apply(transform);

			Assert.That(arguments.GetExtensionObject(BaseMessageContextFunctions.TARGET_NAMESPACE), Is.Null);
		}

		[Test]
		public void ThrowIfCannotHonorMessageContextExtensionRequirements()
		{
			var stream = new StringStream("<?xml version=\"1.0\" encoding=\"utf-16\" ?><root></root>");
			var transform = typeof(AnyToAddPart);

			var sut = new Transformer(new Stream[] { stream });
			Assert.That(
				() => sut.Apply(transform),
				Throws.TypeOf<ArgumentNullException>().With.Message.EqualTo("Value cannot be null.\r\nParameter name: context"));
		}
	}
}


text:
<?php

namespace EZ\Pagination\ClassesConcrete;

use EZ\Pagination\Interfaces\PaginationFactoryInterface;

/**
 * @package EZ\Pagination\ClassesConcrete
 */
class UlFactory implements PaginationFactoryInterface
{
    /**
     * @return UlWrapper
     */
    public function createWrapper()
    {
        return new UlWrapper();
    }

    /**
     * @return LiPage
     */
    public function createPage()
    {
        return new LiPage();
    }

    /**
     * @return LiButton
     */
    public function createButton()
    {
        return new LiButton();
    }

    /**
     * @return LiExtendableSign
     */
    public function createExtendableSign()
    {
        return new LiExtendableSign();
    }

    /**
     * @return LiCurrentPage
     */
    public function createCurrentPage()
    {
        return new LiCurrentPage();
    }
}


text:
<?php

namespace User\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;

class UserFileRepository extends EntityRepository {

    public function findPhotosByLocation($limit = 6, $latitude = null, $longitude = null, $distance = 20) {

        $query = $this->createQueryBuilder('uf')
                ->leftJoin('uf.user', 'u')
                ->leftJoin('u.userTypes', 'ut')
                ->leftJoin('u.addresses', 'a')
                ->setMaxResults($limit)
                ->orderBy('uf.id', 'DESC')
        ;

        /* Geocode */
        $query->andWhere("(3958*3.1415926*sqrt((a.latitude - :latitude)*(a.latitude - :latitude)
                + cos(a.latitude/57.29578)*cos(:latitude/57.29578)*(a.longitude - :longitude)*(a.longitude-:longitude))/180)
                <= :distance")
                ->setParameter('latitude', $latitude)
                ->setParameter('longitude', $longitude)
                ->setParameter('distance', $distance);
        /* Geocode */

        $result = $query->getQuery()->getResult();
        shuffle($result);
        return $result;
    }

    public function countByUser(\User\UserBundle\Entity\User $User) {
        $query = $this->createQueryBuilder('uf')
                ->select('COUNT(uf.id)')
                ->leftJoin('uf.user', 'u')
                ->where('u.id = :id')
                ->setParameter('id', $User->getId());
        return $query->getQuery()->getSingleScalarResult();
    }

    public function findByUser(\User\UserBundle\Entity\User $User, $order = 'uf.id', $sort = 'DESC') {
        $query = $this->createQueryBuilder('uf')
                ->leftJoin('uf.user', 'u')
                ->where('u.id = :id')
                ->orderBy($order, $sort)
                ->setParameter('id', $User->getId());
        return $query->getQuery();
    }

    public function findForAdmin($locale = 'en') {
        $query = $this->createQueryBuilder('uf');

        return $query->getQuery();
    }

    public function filterAdmin($data, $locale = 'en') {
        $query = $this->createQueryBuilder('uf')
                ->leftJoin('uf.user', 'u')
                ->leftJoin('u.translations', 'ut', 'WITH', 'ut.locale = :locale')
                ->setParameter('locale', $locale)
                ->where("1 = 1");

        if (isset($data["search"])) {
            $orQuery = $query->expr()->orx();
            $orQuery->add($query->expr()->like("u.id", ":search"));
            $orQuery->add($query->expr()->like("u.username", ":search"));
            $orQuery->add($query->expr()->like("u.email", ":search"));
            $orQuery->add($query->expr()->like("u.facebook_id", ":search"));
            $orQuery->add($query->expr()->like("u.google_id", ":search"));
            $orQuery->add($query->expr()->like("u.email", ":search"));
            $orQuery->add($query->expr()->like("ut.description", ":search"));
            $orQuery->add($query->expr()->like("ut.baseline", ":search"));
            $query->andWhere($orQuery);
            $query->setParameter('search', '%' . $data["search"] . '%');
        }

        return $query->getQuery();
    }

    public function count() {
        $query = $this->createQueryBuilder('uf')
                ->select('COUNT(uf.id)');
        return $query->getQuery()->getSingleScalarResult();
    }

}


text:
<html>
<head>
<title>%s@fidonet :: WEB Admin tools</title>
<script src="/js/jnode.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="/css/jnode.css" />
</head>
<body>


text:
import numpy as np
import cv2,sys
import cv2.cv as cv
cap = cv2.VideoCapture(sys.argv[1])

if True:
    print("Depth generator output mode:")
    print("FRAME_WIDTH      " + str(cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)))
    print("FRAME_HEIGHT     " + str(cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)))
    print("FRAME_MAX_DEPTH  " + str(cap.get(cv.CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH)) + "mm")
    print("FPS              " + str(cap.get(cv.CV_CAP_PROP_FPS)))
    print("REGISTRATION     " + str(cap.get(cv.CV_CAP_PROP_OPENNI_REGISTRATION)) + "\n")

while(True):
    # Capture frame-by-frame
    cap.grab();

    if True:
        frame = cap.retrieve( cv.CV_CAP_OPENNI_BGR_IMAGE )[1]
        depthMap = cap.retrieve( cv.CV_CAP_OPENNI_DEPTH_MAP );
    else:
        frame = cap.retrieve()[1]
    print frame
    # Our operations on the frame come here
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


text:
The dataset has turned out to not be amenable to analysis by simple MST
using a Hamming metric. Several improvements are thinkable, some of
which are based on the little information which the approach used here
revealed. However, implementing such improvements is beyond the scope of
this thesis.


text:
This repo is part of a challenge that consists of developing two simple single page applications, one using just AngularJS and one using AngularJS and RequireJS in order to tell the differences between:
* page loading time
* network traffic.

---

##Running:

* `make setup` to install all dependencies.
* `make server` to start project.
* `make build` to create a dist.
* `make test` to run karma testing.


text:
package shared.elements;

import shared.Element;

import java.util.List;

/**
 * Object/Work - Core element (1) in getty crosswalk
 */
public abstract class ObjectWork extends Element {

    // - OBJECT/WORK (core) - //

    public abstract List<String> getCatalogLevel();

    public abstract List<String> getObjectWorkType();

    public abstract List<String> getComponenntsParts();

    public abstract List<String> getObjectRemarks();

}


text:
const path = require("path");

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: path.resolve('.'),

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      "tests/spec/*.ts"
    ],

    mime: {
      'text/javascript': ['ts','tsx']
    },

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor

    preprocessors: {
      "tests/spec/*.ts": ["webpack"]
    },

    webpack: {
      output: {
        filename: "file.js"
      },
      module: {
        rules: [
          {
            test: /\.tsx?$/, use: "ts-loader",
            exclude: /node_modules/
          }
        ]
      },
      resolve: {
        extensions: [".ts", ".tsx", ".js"]
      }
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_DEBUG,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
};


text:
package io.smalldata.ohmageomh.surveys.domain.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.util.Map;

/**
 *

 * Serializes the values of some map into a list.
 *

 *
 * @author John Jenkins
 */
public class MapValuesJsonSerializer extends JsonSerializer<Map<?, ?>> {
	/*
	 * (non-Javadoc)
	 * @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
	 */
	@Override
	public void serialize(
		final Map<?, ?> value,
		final JsonGenerator generator,
		final SerializerProvider provider)
		throws IOException, JsonProcessingException {

		provider.defaultSerializeValue(value.values(), generator);
	}
}


text:
.page-header { margin: 15px 0 10px 0; padding: 0; border: none; }
.page-header h1 { display: block; color: #23527c; margin: 0 15px 0 0; padding: 0; width: auto;
line-height: 36px; font-size: 26px; }
.page-header h1 small { font-size: 15px; }

.filter-form .form-control { padding-left: 8px; padding-right: 8px; width: auto; }
.page-alert { padding-top: 8px; padding-bottom: 8px; margin: 15px 0; }

.datalist-table { margin-top: 15px; }
.datalist-table .good-cover { display: block; width: 100px; border: 1px solid #dedede; }
.datalist-table .good-cover img { width: 100%; height: auto; }
.datalist-table h4 { margin: 0; padding: 0; font-size: 13px; font-weight: 600; }
.datalist-table td p { margin: 0; font-size: 12px !important; line-height: 22px; }
.datalist-table td .label { font-size: 11px !important; filter: alpha(opacity=70); opacity: 0.7; }
.datalist-table tbody tr td { padding-top: 10px; padding-bottom: 10px; }
.datalist-table .btn-group { }
.datalist-table .btn-group .btn { font-size: 18px; white-space: normal; line-height: normal; padding: 0 12px;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.4); color: #999; }
.datalist-table .btn-group .btn small { display: block; margin: 0 -5px 0 -5px; font-size: 13px; }
.datalist-table .btn-group .btn small label { margin: 0 5px; }
.datalist-table .btn-group .btn:hover,.datalist-table .btn-group .btn:active,
.datalist-table .btn-group .btn:focus { color: #337ab7; }

.btn-export-download { margin: 5px 0; }


text:
package com.google.code.microlog4android.format.command.util;

/**
 * A String utility class.
 *
 * @author Johan Karlsson
 *
 */
public enum StringUtil {
	;

	/**
	 * Extract a partial name of a class name, starting from the end.
	 *
	 * @param string
	 *            the name of the class
	 * @param parts
	 *            the number of parts of the class name that you want to be
	 *            returned.
	 *
	 * @return the partial class name.
	 */
	public static String extractPartialClassName(String className, int parts) {
		String partialCategoryName = className;

		int nofDots = 0;
		int dotIndex = className.lastIndexOf('.');
		if (dotIndex != -1) {
			nofDots++;
		}

		while (nofDots < parts && dotIndex > -1) {
			dotIndex = className.lastIndexOf('.', dotIndex - 1);

			if (dotIndex != -1) {
				nofDots++;
			}
		}

		if (dotIndex > -1 && nofDots <= parts) {
			partialCategoryName = className.substring(dotIndex + 1);
		}

		return partialCategoryName;
	}

}


text:
package com.example.users.model;

import java.util.List;

import org.apache.http.HttpException;
import org.json.JSONException;

import com.example.users.utils.HttpUtils;
import com.example.users.utils.JSONUtils;
import com.example.users.vo.ResponseData;
import com.example.users.vo.User;

public class UserModel {

	/**
	 * Ìí¼ÓÓû§ÐÅÏ¢
	 * @param user
	 * @throws JSONException
	 * @throws HttpException
	 */
	public ResponseData addUser(User user) throws HttpException, JSONException {
		ResponseData rd = (ResponseData) HttpUtils.postJSON("users.save",
				JSONUtils.object2JSON(user),
				ResponseData.class);

		return rd;
	}

	/**
	 * ²éѯÓû§ÐÅÏ¢Áбí
	 * @param r
	 * @throws HttpException
	 */
	public List listUser() throws HttpException {
		return HttpUtils.getList("users.list", null, User.class);
	}
}


text:
class DestinyUnlockFlagDefinition < ActiveRecord::Base
  self.table_name = "DestinyUnlockFlagDefinition"
end


text:
/*eslint no-unused-vars: 0*/

'use strict';

/**
 * Create an element an append it to the sandbox. This element will be created before every test,
 * and cleaned up after every test.
 *
 * @param {string} tag
 * @param {object} [attributes]
 * @param {boolean} [mount]
 * @returns {HTMLElement}
 */
function createElement(tag, attributes, mount) {
    var element = document.createElement(tag),
        sandbox = document.getElementById('sandbox');

    // Add attributes
    Object.keys(attributes || {}).forEach(function(key) {
        var value = attributes[key];

        if (typeof value === 'function') {
            value = value.call(null, element, key);
        }

        switch (key) {
            case 'className':
            case 'id':
                element[key] = value;
            break;
            case 'html':
                element.innerHTML = value;
            break;
            case 'css':
                Object.keys(value).forEach(function(prop) {
                    var style = value[prop];

                    if (style.indexOf('important') >= 0) {
                        element.style.setProperty(prop, style.replace('!important', '').trim(), 'important');
                    } else {
                        element.style[prop] = style;
                    }
                });
            break;
            default:
                element.setAttribute(key, value);
            break;
        }
    });

    // Add a cleanup function
    element.cleanup = function() {
        if (element.parentNode) {
            element.parentNode.removeChild(element);
        }
    };

    // Add to the sandbox
    if (mount !== false) {
        sandbox.appendChild(element);
    }

    return element;
}

/**
 * Process a callback in a separate thread so that mutations trigger instantly,
 * instead of waiting for the render loop.
 *
 * @param {function} func
 */
function processInThread(func) {
    setTimeout(func, 0);
}


text:
+++
date = "2016-08-15T16:11:58+05:30"
title = "Releasing the legacy driver"
[menu.main]
  weight = 105
  parent="contributing"
+++

If you're reading this, chances are you're about to issue a release for a
new version of the legacy C++ driver.  Congratulations!

## Before Getting Started

To perform the release process, you will need the following:

* `git`, `python`, `doxygen` installed on your local machine.
* Push access to the `mongodb/mongo-cxx-driver` repository on GitHub.
* Push access to the `10gen/apidocs` repository on GitHub.
* Administrative access on the [C++ Driver JIRA project](https://jira.mongodb.org/browse/CXX).

This guide assumes that you have a local clone of the `mongo-cxx-driver`
and `apidocs` repositories, and that your GitHub remote is configured with
remote name `origin`.

In addition, this guide assumes that you are about to issue a production
release named `legacy-x.y.z`.  The process for issuing a release candidate
is nearly identical, with two exceptions:

- The new version string will be in format `legacy-x.y.z-rcw`, instead of
  `legacy-x.y.z`.  In this guide, replace all instances of the latter with
  the former.
- The copy for the release notes and announcement will need to indicate
  that the release is not for production use.

Lastly, this guide also assumes that the following release is is named
`legacy-x.y.(z+1)`.  The name of the following release may differ from
this.

## Confirm All Outstanding Issues Resolved in JIRA

- On the [project roadmap
  panel](https://jira.mongodb.org/browse/CXX/?selectedTab=com.atlassian.jira.jira-projects-plugin:roadmap-panel)
  in JIRA, ensure that all tickets marked for `legacy-x.y.z` are resolved.
  Assuming there are 10 issues in the release, you should see the text "10
  of 10 issues have been resolved" on this page.

## Create and Push the BUMP Commit

* Change directories to your local clone of `mongo-cxx-driver`, and use
  `git status` to confirm a clean working tree, and that you have the
  `legacy` branch checked out.
* Make edits to the following files.  You will be changing the development
  version string (`legacy-x.y.z-rcw-pre`) in these files to the release
  version string (`legacy-x.y.z`):
        * `SConstruct`: update value of `mongoclientVersion`.
        * `etc/doxygen/config`: update value of `PROJECT_NUMBER`.
* Commit and push the bump commit, as follows:

	```
	git add SConstruct etc/doxygen/config
	git commit -m "BUMP legacy-x.y.z"
	git push origin legacy
	```

Pushing the BUMP commit to the origin will kick off builds in Evergreen
and Travis CI. Wait for both builds to finish and pass.

## Tag the Release

* From the same directory, create and push a tag for the commit that will serve as the release.

	```
	git tag legacy-x.y.z
	git push origin legacy-x.y.z
	```

## Generate and Publish Documentation

> Warning: this section is obsolete

* In your local clone of the `apidocs` repo, build and publish the release
  documentation as follows.  The `build.py` script will modify existing
  files, and also create files in a new directory named `cxx/legacy-x.y.z`.

	```
	python build.py cxx
	git add cxx/
	git add -u
	git commit -m "Documentation for C++ driver release legacy-x.y.z"
	git push origin master
	```

Within an hour, a regularly scheduled task will automatically deploy the
new documentation at the [legacy C++ driver API documentation
page](http://api.mongodb.com/cxx/).

## Bulk Transition All Tickets Targeted for Release to "Closed"

- Re-visit the [project roadmap
  panel](https://jira.mongodb.org/browse/CXX/?selectedTab=com.atlassian.jira.jira-projects-plugin:roadmap-panel)
  in JIRA.
- Under the legacy-x.y.z version, click the link "X issues" on the left-hand side.  This will bring you to the search page that displays all tickets targeted for the version about to be released.
- Select "Tools => Bulk Change" from the upper-right hand corner of the search page.
- In the "Choose Issues" dialog, select all issues.
- In the "Choose Operation" dialog, select "Transition Issues".
- In the "Edit Fields" dialog, click "Next" without modifying any fields.
- Confirm the change.

## Release the Version in JIRA

* Visit the [versions administrative
  panel](https://jira.mongodb.org/plugins/servlet/project-config/CXX/versions)
  in JIRA.
* Hover over the version to be released.  A cog icon will appear on the right-hand side of the page.
* Click the cog icon, and select "Release" from the drop-down.  A pop-up will appear, and it should contain no warnings about unresolved issues.
* Set "Release date" to the current date.
* Confirm the release.

## Create the Next Version in JIRA

* From the [versions administrative
  panel](https://jira.mongodb.org/plugins/servlet/project-config/CXX/versions),
  determine whether or not the version corresponding to the next release
  already exists.
* If the version already exists, continue to the next step.
* If the version does not exist, enter the new version's Name and Description at the prompt towards the top of the page.  Select the current date as the next version's start date, and pick a release date.  Typically, the legacy C++ driver is released only a small handful of times each year, so the release date for the new version should likely be at least a couple of months out (barring extraordinary circumstances).

## Draft & Publish GitHub Release Notes

* Visit the [GitHub releases
  page](https://github.com/mongodb/mongo-cxx-driver/releases).
* Click "Draft a New Release".
* Select `legacy-x.y.z` as the tag.  The page should indicate that this tag is recognized.
* Enter "MongoDB Legacy C++ Driver x.y.z" as the release title.
* Draft the release notes.  Typically, release notes have two sections:
	* In the first section, describe in a few sentences what this release is all about.  Mention whether this is a major release or a minor patch release, and call out any notable tickets resolved and anything else that users may want to know about.
	* In the second section, paste in a formatted list of tickets that were resolved in this release.  You can copy-paste this formatted list straight from JIRA's automatically-generated release notes, which you can find by clicking on the "Release Notes" link under the release version at the [project roadmap panel](https://jira.mongodb.org/browse/CXX/?selectedTab=com.atlassian.jira.jira-projects-plugin:roadmap-panel).
* Select "Publish release".

## Send Announcement Email

* Draft an email to mongodb-announce@googlegroups.com announcing the
  release, with subject "Legacy C++ driver legacy-x.y.z released."
* Use the below text as a template, and feel free to include any extra information that seems appropriate for an announcement email:

> The C++ Driver Team is excited to announce the availability of the [legacy-x.y.z](https://github.com/mongodb/mongo-cxx-driver/releases/tag/legacy-x.y.z) release of the Legacy C++ Driver.
>
> This is a stable release.  Please review the [release notes](https://github.com/mongodb/mongo-cxx-driver/releases/tag/legacy-x.y.z) for details on what has changed in this release. The legacy-x.y.z release is a recommended upgrade for all users of the LAST_RELEASE and older drivers.
>
> You can obtain the driver source from GitHub, either under the [legacy-x.y.z](https://github.com/mongodb/mongo-cxx-driver/tree/legacy-x.y.z) tag or from the [releases page](https://github.com/mongodb/mongo-cxx-driver/releases). The legacy C++ driver is a source level distribution and does not offer a stable ABI across releases.
>
> Please feel free to post any questions to the [mongodb-user](https://groups.google.com/forum/#!forum/mongodb-user) mailing list. Bug reports should be filed against the [CXX](https://jira.mongodb.org/browse/CXX) project in the MongoDB JIRA.
>
> Thank you,
>
> The C++ Driver Team

## Create and Push the Next Version Commit

* Change directories back to your clone of `mongo-cxx-driver`.  Edit the following files:
	* `SConstruct`: change value of `mongoclientVersion` from `legacy-x.y.z` to `legacy-x.y.(z+1)-rc0-pre`.
	* `etc/doxygen/config`: change value of `PROJECT_NUMBER` from `legacy-x.y.z` to `legacy-x.y.(z+1)-rc0-pre`.
	* `README.md`: change both the link text and link address to refer to `legacy-x.y.z`.
* Commit and push the next version commit, as follows:

	```
	git add SConstruct etc/doxygen/config README.md
	git commit -m "post legacy-x.y.z"
	git push origin legacy
	```

## Relax

You're done!


text:
package com.amazon.speech.speechlet.interfaces.system.request;

import java.util.Date;
import java.util.Locale;

import com.amazon.speech.speechlet.SpeechletRequest;

/**
 * A superclass for System requests.
 */
public class SystemRequest extends SpeechletRequest {
    protected SystemRequest(SpeechletRequestBuilder builder) {
        super(builder);
    }

    protected SystemRequest(final String requestId, final Date timestamp, final Locale locale) {
        super(requestId, timestamp, locale);
    }
}


text:
layout: default
title: CAS - Password Management
---

# Password Management - REST

Tasks such as locating user's email and security questions as well as management
and updating of the password are delegated to user-defined rest endpoints.

REST support is enabled by including the following dependencies in the WAR overlay:

```xml
<dependency>
    <groupId>org.apereo.cas</groupId>
    <artifactId>cas-server-support-pm-rest</artifactId>
    <version>${cas.version}</version>
</dependency>
```

To see the relevant list of CAS properties, please [review this guide](Configuration-Properties.html#rest-password-management).

| Endpoint                  | Method    | Headers             | Expected Response
|---------------------------|-----------|------------------------------------------------------------------------
| Get Email Address         | `GET`     | `username`          | `200`. Email address in the body.
| Get Security Questions    | `GET`     | `username`          | `200`. Security questions map in the body.
| Update Password           | `POST`    | `username`, `password`, `oldPassword` | `200`. `true/false` in the body.


text:
Table of Contents
=================

  * [Building the code base](#building-the-code-base)
  * [Is this production ready?](#is-this-production-ready)
  * [Using your own docker image with elastic agents](#using-your-own-docker-image-with-elastic-agents)
     * [Using the GoCD agent, installed via .deb/.rpm](#using-the-gocd-agent-installed-via-debrpm)
     * [Use a custom bootstrapper](#use-a-custom-bootstrapper)
  * [Usage instructions](#usage-instructions)
  * [Troubleshooting](#troubleshooting)
  * [Credits](#credits)
  * [License](#license)

## Building the code base

To build the jar, run `./gradlew clean test assemble`

## Is this production ready?

It depends.

The plugin, as it is currently implemented is meant to be a very simple plugin to demonstrate how to get started with GoCD [elastic agent](https://plugin-api.go.cd/current/elastic-agents) feature. This plugin terminates docker containers very aggressively (within a minute or two of the agent being idle). Depending on your usage, this may not be desirable. If this behavior is undesirable to you, you may need to fork this plugin and [tweak it a bit](https://github.com/gocd-contrib/docker-elastic-agents/blob/master/src/main/java/cd/go/contrib/elasticagents/docker/executors/ServerPingRequestExecutor.java) so the docker containers are not terminated as aggressively.

## Using your own docker image with elastic agents

The plugin executes the equivalent of the following docker command to start the agent —

```
docker run -e GO_EA_SERVER_URL=...
           -e GO_EA_AUTO_REGISTER_KEY=...
           -e GO_EA_AUTO_REGISTER_ENVIRONMENT=...
           -e GO_EA_AUTO_REGISTER_ELASTIC_AGENT_ID=...
           -e GO_EA_AUTO_REGISTER_ELASTIC_PLUGIN_ID=...
           ...
           IMAGE_ID
```

Your docker image is expected to contain a bootstrap program (to be executed via docker's `CMD`) that will create an [`autoregister.properties`](https://docs.gocd.io/current/advanced_usage/agent_auto_register.html) file using these variables. The `GO_EA_SERVER_URL` will point to the server url that the agent must communicate with.

Here is an example shell script to do this —

```bash
# write out autoregister.properties
(
cat <<EOF
agent.auto.register.key=${GO_EA_AUTO_REGISTER_KEY}
agent.auto.register.environments=${GO_EA_AUTO_REGISTER_ENVIRONMENT}
agent.auto.register.elasticAgent.agentId=${GO_EA_AUTO_REGISTER_ELASTIC_AGENT_ID}
agent.auto.register.elasticAgent.pluginId=${GO_EA_AUTO_REGISTER_ELASTIC_PLUGIN_ID}
EOF
) > /var/lib/go-agent/config/autoregister.properties
```

### Using the GoCD agent, installed via `.deb/.rpm`

See the bootstrap script and docker file here under [`contrib/scripts/bootstrap-via-installer`](contrib/scripts/bootstrap-via-installer).

### Use a custom bootstrapper

This method uses lesser memory and boots up the agent process and starts off a build quickly:

See the bootstrap script and docker file here under [`contrib/scripts/bootstrap-without-installed-agent`](contrib/scripts/bootstrap-without-installed-agent).

## Usage instructions

* Download and install Docker for your favorite OS from https://docs.docker.com/engine/installation/

If you already have it running it on a mac, make sure to restart it (see https://github.com/docker/for-mac/issues/17#mobyaccess). Time drift is known to cause the plugin to not work, because the timestamps returned by the docker API has drifted from the host.

A good way to know if there's a time drift is to run `docker ps` —

    ```
    CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
    e0754c9f4cdb        alpine:latest       "/bin/sh"           32 minutes ago      Up 17 seconds                           test
    809f310ba1e4        ubuntu:trusty       "/bin/bash"         33 minutes ago      Up About a minute                       reverent_raman
    ```

Notice how the `CREATED` and `STATUS` are several minutes apart for a recently created container.

* Download the latest GoCD installer from https://go.cd/download

    ```shell
    $ unzip go-server-VERSION.zip
    $ mkdir -p go-server-VERSION/plugins/external
    ```
* Download the docker plugin (https://github.com/gocd-contrib/docker-elastic-agents/releases)
* Copy the docker plugin to the go server directory

    ```
    $ cp docker-elastic-agents-0.1-SNAPSHOT.jar /path/to/go-server-VERSION/plugins/external
    ```

* Start the server and configure the plugin (turn on debug logging to get more logs, they're not that noisy)

  On linux/mac

    ```shell
    $ GO_SERVER_SYSTEM_PROPERTIES='-Dplugin.cd.go.contrib.elastic-agent.docker.log.level=debug' ./server.sh
    ```

  On windows

    ```
    C:> set GO_SERVER_SYSTEM_PROPERTIES='-Dplugin.cd.go.contrib.elastic-agent.docker.log.level=debug'
    C:> server.cmd
    ```

To configure the plugin, navigate to the plugin settings page on your GoCD server http://localhost:8153/go/admin/plugins and setup the following settings for the docker plugin.

```
Go Server Host — https://YOUR_IP_ADDRESS:8154/go — do not use "localhost"
Docker URI (for mac and linux) — unix:///var/run/docker.sock
Auto register timeout - between 1-3 minutes
```

Now setup the config.xml —

* add `agentAutoRegisterKey="some-secret-key"` to the `<server/>` tag.
* setup a job —

```xml
<server agentAutoRegisterKey="...">
  <elastic>
    <profiles>
      <profile id="docker.unit-tests" pluginId="cd.go.contrib.elastic-agent.docker">
        <!-- The following properties are currently supported -->
        <property>
          <!-- Allows you to select the docker image that the build should run with -->
          <key>Image</key>
          <value>gocdcontrib/ubuntu-docker-elastic-agent</value>
        </property>
        <property>
          <!-- Allows you to set the environment variables when starting the docker container -->
          <key>Environment</key>
          <value>
            JAVA_HOME=/opt/java
            MAKE_OPTS=-j8
          </value>
        </property>
        <property>
          <!-- Allows you to set the command that should be run on the container, separate executable and each args by a newline -->
          <key>Command</key>
          <value>
            ls
            -al
            /usr/bin
          </value>
        </property>
      </profile>
    </profiles>
  </elastic>
</server>
...
<pipelines group="defaultGroup">
  <pipeline name="Foo">
    <materials>
      <git url="YOUR GIT URL" />
    </materials>
    <stage name="defaultStage">
      <jobs>
        <job name="defaultJob" elasticProfileId="docker.unit-tests">
          <tasks>
            <exec command="ls" />
          </tasks>
        </job>
      </jobs>
    </stage>
  </pipeline>
</pipelines>
```

## Troubleshooting

Enabling debug level logging can help you troubleshoot an issue with the elastic agent plugin. To enable debug level logs, edit the `/etc/default/go-server` (for Linux) to add:

```bash
export GO_SERVER_SYSTEM_PROPERTIES="$GO_SERVER_SYSTEM_PROPERTIES -Dplugin.cd.go.contrib.elastic-agent.docker.log.level=debug"
```

If you're running the server via `./server.sh` script —

```
$ GO_SERVER_SYSTEM_PROPERTIES="-Dplugin.cd.go.contrib.elastic-agent.docker.log.level=debug" ./server.sh
```

## Credits

Thanks to @konpa for the [docker icon](https://raw.githubusercontent.com/konpa/devicon/b80c6d9acb7b58b80904769015f9e0dd36fe46d2/icons/docker/docker-plain.svg) used by the plugin.

## License

```plain
Copyright 2016, ThoughtWorks, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```


text:
package org.apache.druid.query.aggregation.datasketches.kll;

import org.apache.datasketches.kll.KllDoublesSketch;
import org.apache.druid.segment.ColumnValueSelector;

import java.nio.ByteBuffer;

public class KllDoublesSketchBuildBufferAggregator
    extends KllSketchBuildBufferAggregator<KllDoublesSketch, Double>
{
  public KllDoublesSketchBuildBufferAggregator(
      final ColumnValueSelector<Double> valueSelector,
      final int size,
      final int maxIntermediateSize
  )
  {
    super(valueSelector, new KllDoublesSketchBuildBufferAggregatorHelper(size, maxIntermediateSize));
  }

  @Override
  public void aggregate(final ByteBuffer buffer, final int position)
  {
    if (selector.isNull()) {
      return;
    }

    final KllDoublesSketch sketch = helper.getSketchAtPosition(buffer, position);
    sketch.update(selector.getDouble());
  }

}


text:
package com.github.frank.fastAOP.visitor;

import com.github.frank.fastAOP.config.TransformConfig;
import org.objectweb.asm.*;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by frank on 17-7-16.
 */
public class HookClassAdapter extends ClassVisitor {

    private static Logger logger = Logger.getLogger(HookClassAdapter.class.getName());

    public HookClassAdapter(int api, ClassVisitor cv) {
        super(api, cv);
    }

    @Override
    public void visitAttribute(Attribute attr) {
        logger.log(Level.INFO," type: "+attr.type);
        super.visitAttribute(attr);
    }

    @Override
    public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
        logger.log(Level.INFO," name: "+name+" desc: "+desc+" value: "+value);
        return super.visitField(access, name, desc, signature, value);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        logger.log(Level.INFO,"MethodName: "+name);
        if(TransformConfig.getInstance().isEnableExceptionHook()) {
            return new ExceptionHookMethodAdapter(Opcodes.ASM5, super.visitMethod(access, name, desc, signature, exceptions), access, name, desc);
        }else {
            logger.log(Level.INFO,"未开启异常捕获");
            return super.visitMethod(access,name,desc,signature,exceptions);
        }

    }
}


text:
Change Password

        <error-list [error]="error"></error-list>
        <form (ngSubmit)="passChange()" [formGroup]="passwordChangeForm">
            <fieldset [disabled]="isSubmitting">
                <fieldset class="form-group">

                        Old Password
                        <input type="password"  class="form-control" id="OldPassword"
                                formControlName="oldPassword" placeholder="Old Password">

                        New Password

                        <input type="password" class="form-control"
                               id="NewPassword" placeholder="New Password" formControlName="newPassword"
                               pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{6,}">

*Minimum 6 chracters(Alphabets,Numeric
                            digits,Special
                            Symbols)

                         Confirm Password

                        <input type="password" class="form-control"
                               id="ConfirmPassword" placeholder="Confirm Password" formControlName="confirmPassword">

Passwords don't match

                    <button type="submit" class="btn btn-primary" [disabled]="!passwordChangeForm.valid">Change Password</button>
                </fieldset>
            </fieldset>
        </form>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Nova Hedwigia 69: 61 (1981)

#### Original name
Panus convivalis Corner

### Remarks
null


text:
package org.heigit.ors.fastisochrones.partitioning;

/**
 * Based on https://stackoverflow.com/questions/4958330/java-executorservice-awaittermination-of-all-recursively-created-tasks/4958416#4958416
 */
public class InverseSemaphore {
    private int value = 0;
    private Object lock = new Object();

    public void beforeSubmit() {
        synchronized (lock) {
            value++;
        }
    }

    public void taskCompleted() {
        synchronized (lock) {
            value--;
            if (value == 0) lock.notifyAll();
        }
    }

    public void awaitCompletion() throws InterruptedException {
        synchronized (lock) {
            while (value > 0) lock.wait();
        }
    }
}


text:
typedef struct chip8 chip8_t;
typedef struct io io_t;

typedef void (* io_setup_t)(io_t *);
typedef void (* io_render_t)(io_t *, chip8_t *);
typedef void (* io_beep_t)(io_t *, chip8_t *);
typedef void (* io_delay_t)(io_t *, chip8_t *);
typedef int  (* io_listen_t)(io_t *, chip8_t *);
typedef void (* io_teardown_t)(io_t *);
typedef void * io_custom_t;

typedef struct io {
  char        * name;
  io_setup_t    setup;
  io_render_t   render;
  io_beep_t     beep;
  io_delay_t    delay;
  io_listen_t   listen;
  io_teardown_t teardown;
  io_custom_t   custom;
} io_t;

inline void io_setup(io_t *);
inline void io_render(io_t *, chip8_t *);
inline void io_beep(io_t *, chip8_t *);
inline void io_delay(io_t *, chip8_t *);
inline int  io_listen(io_t *, chip8_t *);
inline void io_teardown(io_t *);
inline void io_free(io_t *);

#endif


text:
class Connection;

class Processer{
public:
  int protocol;
  HTTP_processer http;
  WebSock_processer websock;

  Connection *conn;

  Processer();
  ~Processer();
  void Process(int sock, unsigned char *buff, int index, int data_start, ProcessResult &ret);

};

#endif


text:
#include "../../SDL_internal.h"
#include "SDL_error.h"
#include "SDL_filesystem.h"

#ifdef SDL_FILESYSTEM_NACL

char *
SDL_GetBasePath(void)
{
    SDL_Unsupported();
    return NULL;
}

char *
SDL_GetPrefPath(const char *org, const char *app)
{
    SDL_Unsupported();
    return NULL;
}

#endif /* SDL_FILESYSTEM_NACL */

/* vi: set ts=4 sw=4 expandtab: */


text:
<?php

namespace edu\wisc\services\caos;

class GetUniqueClassInstructionModesInTermResponse
{

    /**
     * @var string $instructionMode
     */
    protected $instructionMode = null;

    /**
     * @param string $instructionMode
     */
    public function __construct($instructionMode)
    {
      $this->instructionMode = $instructionMode;
    }

    /**
     * @return string
     */
    public function getInstructionMode()
    {
      return $this->instructionMode;
    }

    /**
     * @param string $instructionMode
     * @return \edu\wisc\services\caos\GetUniqueClassInstructionModesInTermResponse
     */
    public function setInstructionMode($instructionMode)
    {
      $this->instructionMode = $instructionMode;
      return $this;
    }

}


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var Rule = /** @class */ (function (_super) {
    tslib_1.__extends(Rule, _super);
    function Rule() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Rule.FAILURE_STRING_REDUNDANT_TAG = function (tagName) {
        return "JSDoc tag '@" + tagName + "' is redundant in TypeScript code.";
    };
    Rule.FAILURE_STRING_NO_COMMENT = function (tagName) {
        return "'@" + tagName + "' is redundant in TypeScript code if it has no description.";
    };
    Rule.prototype.apply = function (sourceFile) {
        return this.applyWithFunction(sourceFile, walk);
    };
    /* tslint:disable:object-literal-sort-keys */
    Rule.metadata = {
        ruleName: "no-redundant-jsdoc",
        description: "Forbids JSDoc which duplicates TypeScript functionality.",
        optionsDescription: "Not configurable.",
        options: null,
        optionExamples: [true],
        type: "style",
        typescriptOnly: true,
    };
    /* tslint:enable:object-literal-sort-keys */
    Rule.FAILURE_STRING_REDUNDANT_TYPE = "Type annotation in JSDoc is redundant in TypeScript code.";
    return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
function walk(ctx) {
    var sourceFile = ctx.sourceFile;
    // Intentionally exclude EndOfFileToken: it can have JSDoc, but it is only relevant in JavaScript files
    return sourceFile.statements.forEach(function cb(node) {
        if (tsutils_1.canHaveJsDoc(node)) {
            for (var _i = 0, _a = tsutils_1.getJsDoc(node, sourceFile); _i < _a.length; _i++) {
                var tags = _a[_i].tags;
                if (tags !== undefined) {
                    for (var _b = 0, tags_1 = tags; _b < tags_1.length; _b++) {
                        var tag = tags_1[_b];
                        checkTag(tag);
                    }
                }
            }
        }
        return ts.forEachChild(node, cb);
    });
    function checkTag(tag) {
        switch (tag.kind) {
            case ts.SyntaxKind.JSDocTag:
                if (redundantTags.has(tag.tagName.text)) {
                    ctx.addFailureAtNode(tag.tagName, Rule.FAILURE_STRING_REDUNDANT_TAG(tag.tagName.text));
                }
                break;
            case ts.SyntaxKind.JSDocAugmentsTag:
                // OK
                break;
            case ts.SyntaxKind.JSDocClassTag:
            case ts.SyntaxKind.JSDocTypeTag:
            case ts.SyntaxKind.JSDocTypedefTag:
            case ts.SyntaxKind.JSDocPropertyTag:
                // Always redundant
                ctx.addFailureAtNode(tag.tagName, Rule.FAILURE_STRING_REDUNDANT_TAG(tag.tagName.text));
                break;
            case ts.SyntaxKind.JSDocTemplateTag:
                if (tag.comment === undefined || tag.comment === "") {
                    ctx.addFailureAtNode(tag.tagName, Rule.FAILURE_STRING_NO_COMMENT(tag.tagName.text));
                }
                break;
            case ts.SyntaxKind.JSDocReturnTag:
            case ts.SyntaxKind.JSDocParameterTag: {
                var _a = tag, typeExpression = _a.typeExpression, comment = _a.comment;
                if (typeExpression !== undefined) {
                    ctx.addFailureAtNode(typeExpression, Rule.FAILURE_STRING_REDUNDANT_TYPE);
                }
                if (comment === "") {
                    // Redundant if no documentation
                    ctx.addFailureAtNode(tag.tagName, Rule.FAILURE_STRING_NO_COMMENT(tag.tagName.text));
                }
                break;
            }
            default:
                throw new Error("Unexpected tag kind: " + ts.SyntaxKind[tag.kind]);
        }
    }
}
var redundantTags = new Set([
    "abstract",
    "access",
    "class",
    "constant",
    "constructs",
    "default",
    "enum",
    "exports",
    "function",
    "global",
    "implements",
    "interface",
    "instance",
    "member",
    "memberof",
    "mixes",
    "mixin",
    "module",
    "name",
    "namespace",
    "override",
    "private",
    "property",
    "protected",
    "public",
    "readonly",
    "requires",
    "static",
    "this",
]);


text:
from rest_framework import serializers
from rest_framework_gis import serializers as gis_serializers
from api.models import (
        Collection,
        Document,
        Page,
        Sentence,
        Location,)

class CollectionSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Collection
        fields = ('url', 'text', 'documents',)

class ListDocumentSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Document
        fields = ('url', 'title', 'pubdate', 'author', 'external_url',
                  'collection',)

class RetrieveDocumentSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Document
        fields = ('url', 'title', 'pubdate', 'author', 'external_url',
                  'collection', 'pages',)

class PageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Page
        fields = ('url', 'document', 'sentences',)

class SentenceSerializer(serializers.HyperlinkedModelSerializer):
    document = serializers.HyperlinkedRelatedField(read_only=True,
                        view_name='document-detail', source='page.document')

    class Meta:
        model = Sentence
        fields = ('url', 'text', 'i_score', 'document',)

class LocationSerializer(gis_serializers.GeoModelSerializer):

    class Meta:
        model = Location
        fields = ('url', 'text', 'point', 'polygon', 'polygon_type', )


text:
<?php

namespace Emri99\Gitlab;

use Emri99\Gitlab\Exception\GitlabApiClientException;
use Emri99\Gitlab\Exception\NotFoundException;
use Unirest\Method;
use Unirest\Request;
use Unirest\Response;

class GitlabApiClient
{
    /**
     * Authenticate mode : HTTP Header
     * Use an personal/impersonate access token.
     */
    const AUTH_HTTP_TOKEN = 'HTTP';

    /**
     * Authenticate mode : OAUTH token
     * Use the key supplied by Gitlab's OAuth provider.
     */
    const AUTH_OAUTH_TOKEN = 'OAUTH';

    /**
     * Dynamic part of url.
     *
     * @var string
     */
    protected $path;

    /**
     * Default headers (supplied).
     *
     * @var array
     */
    protected $headers = array();

    /**
     * Authentication headers (computed internally).
     *
     * @var array
     */
    protected $authenticationHeaders = array();

    /**
     * @var array|null
     */
    protected $auth = null;

    /**
     * @var array
     */
    private $options = array();

    private $baseUrl;

    public function __construct($baseUrl, array $options = array())
    {
        if ('/' === substr($baseUrl, -1, 1)) {
            $baseUrl = substr($baseUrl, 0, -1);
        }
        $this->baseUrl = $baseUrl;
        $this->options = array_merge(array(
            'user_agent' => 'php-gitlab-generic-api-client',
            'timeout' => 60,
            'json_decode_to_array' => false,
            'json_decode_options' => JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES & JSON_UNESCAPED_UNICODE,
            'verify_peer' => true,
            'verify_host' => true,
        ), $options);
    }

    /**
     * Add url segment to endpoint url.
     *
     * @param string $method
     *
     * @return $this
     */
    public function __call($method, array $args)
    {
        $this->path .= '/'.$method;

        if (0 === count($args)) {
            return $this;
        }

        foreach ($args as $param) {
            if (null === $param) {
                continue;
            }

            if (!is_scalar($param)) {
                throw new \InvalidArgumentException(sprintf('Method "%s" : Invalid argument type. scalar expected.', $method));
            }
            $this->__call($this->encodePath($param), array());
        }

        return $this;
    }

    /**
     * @return $this
     */
    public function setHeaders(array $headers)
    {
        $this->headers = $headers;

        return $this;
    }

    /**
     * @param string $name
     *
     * @throws \InvalidArgumentException
     *
     * @return mixed
     */
    public function getOption($name)
    {
        if (!array_key_exists($name, $this->options)) {
            throw new \InvalidArgumentException(sprintf('Undefined option called: "%s"', $name));
        }

        return $this->options[$name];
    }

    /**
     * Authenticate a user for all next requests.
     *
     * @param string $token      Gitlab private token
     * @param string $authMethod One of the AUTH_* class constants
     * @param string $sudo
     *
     * @return $this
     */
    public function authenticate($token, $authMethod = self::AUTH_HTTP_TOKEN, $sudo = null)
    {
        $this->authenticationHeaders = array();

        if (!in_array($authMethod, array(self::AUTH_HTTP_TOKEN, self::AUTH_OAUTH_TOKEN))) {
            return $this;
        }

        if (self::AUTH_HTTP_TOKEN === $authMethod) {
            $this->authenticationHeaders['PRIVATE-TOKEN'] = $token;
        }

        if (self::AUTH_OAUTH_TOKEN === $authMethod) {
            $this->authenticationHeaders['Authorization'] = sprintf('Bearer %s', $token);
        }

        if (!is_null($sudo)) {
            $this->authenticationHeaders['SUDO'] = $sudo;
        }

        return $this;
    }

    /**
     * @param array $headers
     *
     * @throws GitlabApiClientException
     * @throws NotFoundException
     *
     * @return mixed
     */
    public function get(array $parameters = array(), $headers = array())
    {
        $response = $this->request(Method::GET, $this->flushPath($parameters), $headers);

        return $this->returnOrThrow($response);
    }

    /**
     * @param array $headers
     *
     * @throws GitlabApiClientException
     * @throws NotFoundException
     *
     * @return mixed
     */
    public function post(array $parameters = array(), $headers = array(), array $files = array())
    {
        $body = null;
        if (!empty($parameters) && empty($files)) {
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
            $body = Request\Body::Form($parameters);
        } elseif (!empty($files)) {
            $headers['Content-Type'] = 'multipart/form-data';
            $body = Request\Body::Multipart($parameters, $files);
        }

        $response = $this->request(Method::POST, $this->flushPath(), $headers, $body);

        return $this->returnOrThrow($response);
    }

    /**
     * @param array $headers
     *
     * @throws GitlabApiClientException
     * @throws NotFoundException
     *
     * @return mixed
     */
    public function put(array $parameters = array(), $headers = array(), array $files = array())
    {
        $body = null;
        if (!empty($parameters) && empty($files)) {
            $headers['Content-Type'] = 'application/x-www-form-urlencoded';
            $body = Request\Body::Form($parameters);
        } elseif (!empty($files)) {
            $headers['Content-Type'] = 'multipart/form-data';
            $body = Request\Body::Multipart($parameters, $files);
        }

        $response = $this->request(Method::PUT, $this->flushPath(), $headers, $body);

        return $this->returnOrThrow($response);
    }

    /**
     * @param array $headers
     *
     * @throws GitlabApiClientException
     * @throws NotFoundException
     *
     * @return mixed
     */
    public function delete(array $parameters = array(), $headers = array())
    {
        $response = $this->request('DELETE', $this->flushPath($parameters), $headers);

        return $this->returnOrThrow($response);
    }

    /**
     * @param Response $response
     *
     * @throws NotFoundException
     * @throws GitlabApiClientException
     *
     * @return array|\stdClass depending on option 'json_decode_to_array'
     */
    protected function returnOrThrow($response)
    {
        if (!$response) {
            throw new GitlabApiClientException('No response');
        }

        if (null === $response->raw_body || '' === $response->raw_body) {
            return null;
        }

        if (is_string($response->body)
            && isset($response->headers['Content-Type'])
            && 'application/json' === $response->headers['Content-Type']) {
            throw new GitlabApiClientException('Unable to decode json response');
        }

        $error = !empty($response->body->error) ? $response->body->error : null;
        if ($error && !is_string($error)) {
            $error = trim(json_encode($error), '"');
        }

        if ($response->code >= 400) {
            $error = $error ?: '';
            if (404 === $response->code && $this->lastpath) {
                $exception = NotFoundException::create($this->lastpath, $error);
                $this->lastpath = null;
                throw $exception;
            }
        }

        if (null !== $error) {
            throw new GitlabApiClientException(sprintf('%s - %s', $response->code, $error), $response->code);
        }

        if (!$this->options['json_decode_to_array']) {
            return $response->body;
        }

        return json_decode(json_encode($response->body), true);
    }

    protected function request($httpMethod = 'GET', $path, array $headers = array(), $body = null)
    {
        $httpMethod = strtoupper($httpMethod);
        $path = trim($this->baseUrl.$path, '/');

        $httpOptions = array(
            'verifyPeer' => array($this->options['verify_peer']),
            'verifyHost' => array($this->options['verify_host']),
            'timeout' => array($this->options['timeout']),
            'jsonOpts' => array(false, 512, $this->options['json_decode_options']),
        );

        $allHeaders = array_merge($this->headers, $this->authenticationHeaders, $headers);

        return $this->performRequest(
            $httpMethod,
            $path,
            $body,
            $allHeaders,
            $httpOptions
        );
    }

    /**
     * @codeCoverageIgnore
     *
     * @param string $httpMethod
     * @param string $path
     * @param string $body
     * @param array  $allHeaders
     * @param array  $httpOptions
     *
     * @throws \Unirest\Exception
     *
     * @return \Unirest\Response
     */
    protected function performRequest($httpMethod, $path, $body, $allHeaders, $httpOptions)
    {
        foreach ($httpOptions as $method => $args) {
            call_user_func_array(array('Unirest\Request', $method), $args);
        }

        return Request::send($httpMethod, $path, $body, $allHeaders);
    }

    /**
     * @param string $path
     *
     * @return string
     */
    protected function encodePath($path)
    {
        $path = rawurlencode($path);

        return str_replace('.', '%2E', $path);
    }

    /**
     * Retrieve current url fragment & flush it from next requests.
     *
     * @param mixed|null $parameters
     *
     * @return string
     */
    protected function flushPath($parameters = null)
    {
        $path = $this->path;

        if ($parameters) {
            $separator = false === strpos($path, '?') ? '?' : '&';
            $path .= $separator.http_build_query($parameters);
        }

        // remember full url to display path in 404 message
        $this->lastpath = $this->baseUrl.$path;
        $this->path = '';

        return $path;
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeActions;

namespace Microsoft.CodeAnalysis.CodeRefactorings
{
    internal static class CodeRefactoringContextExtensions
    {
        /// <summary>
        /// Use this helper to register multiple refactorings (<paramref name="actions"/>).
        /// </summary>
        internal static void RegisterRefactorings<TCodeAction>(
            this CodeRefactoringContext context, ImmutableArray<TCodeAction> actions)
            where TCodeAction : CodeAction
        {
            if (!actions.IsDefault)
            {
                foreach (var action in actions)
                {
                    context.RegisterRefactoring(action);
                }
            }
        }
    }
}


text:
'use strict';

angular.module('dictionaryApp')
    .config(function ($stateProvider) {
        $stateProvider
            .state('translation', {
                parent: 'entity',
                url: '/translations',
                data: {
                    authorities: ['ROLE_USER'],
                    pageTitle: 'Translations'
                },
                views: {
                    'content@': {
                        templateUrl: 'scripts/app/entities/translation/translations.html',
                        controller: 'TranslationController'
                    }
                },
                resolve: {
                }
            })
            .state('translation.detail', {
                parent: 'entity',
                url: '/translation/{id}',
                data: {
                    authorities: ['ROLE_USER'],
                    pageTitle: 'Translation'
                },
                views: {
                    'content@': {
                        templateUrl: 'scripts/app/entities/translation/translation-detail.html',
                        controller: 'TranslationDetailController'
                    }
                },
                resolve: {
                    entity: ['$stateParams', 'Translation', function($stateParams, Translation) {
                        return Translation.get({id : $stateParams.id});
                    }]
                }
            })
            .state('translation.new', {
                parent: 'translation',
                url: '/new',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$modal', function($stateParams, $state, $modal) {
                    $modal.open({
                        templateUrl: 'scripts/app/entities/translation/translation-dialog.html',
                        controller: 'TranslationDialogController',
                        size: 'lg',
                        resolve: {
                            entity: function () {
                                return {
                                    usage: null,
                                    priority: null,
                                    id: null
                                };
                            }
                        }
                    }).result.then(function(result) {
                        $state.go('translation', null, { reload: true });
                    }, function() {
                        $state.go('translation');
                    })
                }]
            })
            .state('translation.edit', {
                parent: 'translation',
                url: '/{id}/edit',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$modal', function($stateParams, $state, $modal) {
                    $modal.open({
                        templateUrl: 'scripts/app/entities/translation/translation-dialog.html',
                        controller: 'TranslationDialogController',
                        size: 'lg',
                        resolve: {
                            entity: ['Translation', function(Translation) {
                                return Translation.get({id : $stateParams.id});
                            }]
                        }
                    }).result.then(function(result) {
                        $state.go('translation', null, { reload: true });
                    }, function() {
                        $state.go('^');
                    })
                }]
            })
            .state('translation.delete', {
                parent: 'translation',
                url: '/{id}/delete',
                data: {
                    authorities: ['ROLE_USER'],
                },
                onEnter: ['$stateParams', '$state', '$modal', function($stateParams, $state, $modal) {
                    $modal.open({
                        templateUrl: 'scripts/app/entities/translation/translation-delete-dialog.html',
                        controller: 'TranslationDeleteController',
                        size: 'md',
                        resolve: {
                            entity: ['Translation', function(Translation) {
                                return Translation.get({id : $stateParams.id});
                            }]
                        }
                    }).result.then(function(result) {
                        $state.go('translation', null, { reload: true });
                    }, function() {
                        $state.go('^');
                    })
                }]
            });
    });


text:
<?php

namespace core\object;
use core\object\Comparable as Comparable;

/**
 * This class implements comparison methods for objects
 * @author Marc Bredt
 */
class ComparableObject implements Comparable {

  public function __construct() {}

  private function has_attribute() {}

  /**
   * Compare (specific) attributes of objects.
   * @return true on success, otherwise false
   */
  public function compare($o = null, $attrs = array()) {}

  /**
   * Compare serialized versions of objects.
   * @return true on success, otherwise false
   */
  public function scompare($o = null) {}

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Fullscreen Login</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link rel='stylesheet' href='http://fonts.googleapis.com/css?family=PT+Sans:400,700'>
        <link rel="stylesheet" href="assets/css/reset.css">
        <link rel="stylesheet" href="assets/css/supersized.css">
        <link rel="stylesheet" href="assets/css/style.css">

Login

            <form action="" method="post">
                <input type="text" name="username" class="username" placeholder="Username">
                <input type="password" name="password" class="password" placeholder="Password">
                <button type="submit">Sign me in</button>

+

            </form>

Or connect with:

Collect from 模板之家


text:
"""Test time stamping in pkg_tar"""

import datetime
import tarfile
import time
import unittest
import zipfile

from bazel_tools.tools.python.runfiles import runfiles

# keep in sync with archive.py
PORTABLE_MTIME = 946684800  # 2000-01-01 00:00:00.000 UTC

class StampTest(unittest.TestCase):
  """Test for non-epoch time stamps in packages."""

  target_mtime = int(time.time())
  zip_epoch_dt = datetime.datetime(1980, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)
  ZIP_EPOCH = int(zip_epoch_dt.timestamp())
  # We allow the stamp on the build file to be within this delta back in
  # time from now. That allows for the test data to be built early in a clean
  # CI run and have the test run a few seconds later. Ideally, this would
  # be no greater than the expected total CI run time, but the extra margin
  # does not hurt.
  ALLOWED_DELTA_FROM_NOW = 30000  # seconds

  def check_mtime(self, mtime, file_path, file_name):
    """Checks that a time stamp is reasonable.

    This checks that a timestamp is not 0 or any of the well known EPOCH values,
    and that it is within some delta from the current time.

    Args:
      mtime: timestamp in seconds
      file_path: path to archive name
      file_name: file within archive
    """
    if mtime == 0:
       self.fail('Archive %s contains file %s with mtime == 0' % (
           file_path, file_name))
    if mtime == PORTABLE_MTIME:
       self.fail('Archive %s contains file %s with portable mtime' % (
           file_path, file_name))
    if mtime == StampTest.ZIP_EPOCH:
       self.fail('Archive %s contains file %s with ZIP epoch' % (
           file_path, file_name))
    if ((mtime < self.target_mtime - StampTest.ALLOWED_DELTA_FROM_NOW)
        or (mtime > self.target_mtime)):
       self.fail(
           'Archive %s contains file %s with mtime:%d, expected:%d +/- %d.' % (
               file_path, file_name, mtime, self.target_mtime,
               StampTest.ALLOWED_DELTA_FROM_NOW) +
           '  This may be a false positive if your build cache is more than' +
           ' %s seconds old.  If so, try bazel clean and rerun the test.' %
           StampTest.ALLOWED_DELTA_FROM_NOW)

  def assertTarFilesAreAlmostNew(self, file_name):
    """Assert that tarfile contains files with an mtime of roughly now.

    This is used to prove that the test data was a file which was presumably:
    built with 'stamp=1' or ('stamp=-1' and --stamp) contains files which
    all have a fairly recent mtime, thus indicating they are "current" time
    rather than the epoch or some other time.

    Args:
        file_name: the path to the TAR file to test.
    """
    file_path = runfiles.Create().Rlocation('rules_pkg/tests/' + file_name)
    with tarfile.open(file_path, 'r:*') as f:
      for info in f:
        self.check_mtime(info.mtime, file_path, info.name)

  def assertZipFilesAreAlmostNew(self, file_name):
    """Assert that zipfile contains files with an mtime of roughly now.

    This is used to prove that the test data was a file which was presumably:
    built with 'stamp=1' or ('stamp=-1' and --stamp) contains files which
    all have a fairly recent mtime, thus indicating they are "current" time
    rather than the epoch or some other time.

    Args:
        file_name: the path to the ZIP file to test.
    """
    file_path = runfiles.Create().Rlocation('rules_pkg/tests/' + file_name)
    target_mtime = int(time.time())
    with zipfile.ZipFile(file_path, mode='r') as f:
      for info in f.infolist():
        d = info.date_time
        dt = datetime.datetime(d[0], d[1], d[2], d[3], d[4], d[5], tzinfo=datetime.timezone.utc)
        self.check_mtime(int(dt.timestamp()), file_path, info.filename)

  def test_not_epoch_times_tar(self):
    self.assertTarFilesAreAlmostNew('stamped_tar.tar')

  def test_not_epoch_times_zip(self):
    self.assertZipFilesAreAlmostNew('stamped_zip.zip')

if __name__ == '__main__':
  unittest.main()


text:
package com.howmuchbeer.main;

import java.util.Date;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Text;

/**
 * A comment left by a visitor.
 *
 * @author nbeckman
 *
 */
@PersistenceCapable
public class Comment {
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;

	@Persistent
    private Date dateOfEntry;

	@Persistent
	private Boolean moderated;

	// Comment and author come from the user, must be scrubbed.

	@Persistent
	private String author;

	@Persistent
	private com.google.appengine.api.datastore.Text comment;

	public Key getKey() {
		return key;
	}

	public void setKey(Key key) {
		this.key = key;
	}

	public Date getDateOfEntry() {
		return dateOfEntry;
	}

	public void setDateOfEntry(Date dateOfEntry) {
		this.dateOfEntry = dateOfEntry;
	}

	public Boolean getModerated() {
		return moderated;
	}

	public void setModerated(Boolean moderated) {
		this.moderated = moderated;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public com.google.appengine.api.datastore.Text getComment() {
		return comment;
	}

	public void setComment(com.google.appengine.api.datastore.Text comment) {
		this.comment = comment;
	}

	public Comment(Date dateOfEntry, String author, Text comment) {
		super();
		this.moderated = false;
		this.dateOfEntry = dateOfEntry;
		this.author = author;
		this.comment = comment;
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>habilitar-estabelecimento-como-centro-de-atendimento-de-urgencia-aos-pacientes-com-avc</id>
    <dbId>1051</dbId>
    <nome>Habilitar estabelecimento como Centro de Atendimento de Urgência aos Pacientes com AVC</nome>
    <sigla></sigla>
    <descricao>Trata-se da ação de habilitar estabelecimentos de saúde como Centro de Atendimento de Urgência aos Pacientes com AVC Tipo I, II ou III.</descricao>
    <contato>Postal e Presencial: Coordenação-Geral de Atenção Especializada / Departamento de Atenção Especializada e Temática / SAS / MS - SAF Sul, Trecho 2, Bl "F", 2º andar, Sl. 205 - Edifício Premium, Torre II - 70.070-600 - Brasília/DF
E-mail: altacomplexidade@saude.gov.br
Telefone: (61) 3315-6176</contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="2525">
            <tipo>Estados e Municípios</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="5036">
            <titulo>Solicitar habilitação</titulo>
            <descricao></descricao>
            <documentos>
                <default>
                    <item id="3536">Alvará sanitário, titulação dos profissionais e outros</item>
                    <item id="3537">Titulação dos Profissionais</item>
                    <item id="3538">Ofício do gestor Estadual</item>
                    <item id="3539">Formulário de Vistoria do Gestor (Check-List) preenchido e assinado (Anexo III – A, PT nº 756/2005)</item>
                    <item id="3540">CIB aprovando a habilitação</item>
                    <item id="3541">Ofício do gestor Estadual informando à quem caberá custear a habilitação e o cálculo do Impacto financeiro conforme parâmetros previstos na Portaria nº 756/2005</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3738" tipo="web">
                        <descricao>http://saips.saude.gov.br/autenticacao</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="5037">
            <titulo>Fornecer informações adicionais (caso requisitado)</titulo>
            <descricao></descricao>
            <documentos>
                <default>
                    <item id="3542">documentações e informações requisitadas pelos analistas</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3739" tipo="web">
                        <descricao>http://saips.saude.gov.br/autenticacao</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
        <etapa id="5038">
            <titulo>Receber resultado</titulo>
            <descricao>A habilitação será publicada em portaria específica</descricao>
            <documentos>
                <default/>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="3740" tipo="web">
                        <descricao>http://portal2.saude.gov.br/saudelegis/LEG_NORMA_PESQ_CONSULTA.CFM</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="3741" tipo="web">
                        <descricao>http://saips.saude.gov.br/autenticacao</descricao>
                    </canal-de-prestacao>
                    <canal-de-prestacao id="3742" tipo="web">
                        <descricao>http://portal.imprensanacional.gov.br/</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/304" dbId="37534">
        <nomeOrgao>Ministério da Saúde (MS)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="2" idServicoSegmento="5061">Órgãos e entidades públicas</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Assistência Hospitalar e Ambulatorial</item>
        <item>Fiscalização do Estado</item>
        <item>Humanização na saúde</item>
        <item>Saúde</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="9431">AVC</item>
        <item id="9432">habilitação</item>
        <item id="9433">alta complexidade</item>
    </palavras-chave>
    <legislacoes>
        <item id="2211">[Portaria GM/MS nº 665, de 12/04/2012 ](http://bvsms.saude.gov.br/bvs/saudelegis/gm/2012/PRT0665_12_04_2012.html)</item>
        <item id="2212">[Portaria GM/MS nº 800, de 17/06/2015](http://bvsms.saude.gov.br/bvs/saudelegis/gm/2015/prt0800_17_06_2015.html)</item>
    </legislacoes>
</servico>