text:
using System;
using System.Diagnostics;

namespace Oragon.Architecture.IO.Path
{
	partial class PathHelpers
	{
		#region Private Classes

		private abstract class EnvVarPathBase : PathBase, IEnvVarPath
		{
			#region Private Fields

			//
			// EnvVar (env var name with percent like "%TEMP%" )
			//
			private readonly string m_EnvVarWith2PercentsChar;

			#endregion Private Fields

			#region Protected Constructors

			protected EnvVarPathBase(string pathString) :
				base(pathString)
			{
				Debug.Assert(pathString != null);
				Debug.Assert(pathString.Length > 0);

				m_EnvVarWith2PercentsChar = ComputeEnvVar();
				Debug.Assert(m_EnvVarWith2PercentsChar != null);
				Debug.Assert(m_EnvVarWith2PercentsChar.Length >= 3);
				Debug.Assert(m_EnvVarWith2PercentsChar[0] == MiscHelpers.ENVVAR_PERCENT);
				Debug.Assert(m_EnvVarWith2PercentsChar[m_EnvVarWith2PercentsChar.Length - 1] == MiscHelpers.ENVVAR_PERCENT);
			}

			#endregion Protected Constructors

			#region Public Properties

			public string EnvVar { get { return m_EnvVarWith2PercentsChar; } }

			//
			// ParentDirectoryPath
			//
			IEnvVarDirectoryPath IEnvVarPath.ParentDirectoryPath
			{
				get
				{
					string parentPath = MiscHelpers.GetParentDirectory(m_PathString);
					return parentPath.ToEnvVarDirectoryPath();
				}
			}

			public override bool IsAbsolutePath { get { return false; } }

			public override bool IsEnvVarPath { get { return true; } }

			public override bool IsRelativePath { get { return false; } }

			public override bool IsVariablePath { get { return false; } }

			public override IDirectoryPath ParentDirectoryPath
			{
				get
				{
					string parentPath = MiscHelpers.GetParentDirectory(m_PathString);
					return parentPath.ToEnvVarDirectoryPath();
				}
			}

			public override PathMode PathMode { get { return PathMode.EnvVar; } }

			#endregion Public Properties

			#region Public Methods

			// This methods are implemented in EnvVarFilePath and EnvVarDirectoryPath.
			public abstract EnvVarPathResolvingStatus TryResolve(out IAbsolutePath pathResolved);

			public abstract bool TryResolve(out IAbsolutePath pathResolved, out string failureReason);

			#endregion Public Methods

			#region Protected Methods

			protected string GetErrorEnvVarResolvedButCannotConvertToAbsolutePathFailureReason()
			{
				string envVarValue;
				var b = TryExpandMyEnvironmentVariables(out envVarValue);
				Debug.Assert(b); // If the error EnvVarResolvedButCanConvertToAbsolutePath occurs
				// it means envVar can be resolved!
				return "The environment variable " + m_EnvVarWith2PercentsChar + " is resolved into the value {" + envVarValue + "} but this value cannot be the prefix of an absolute path.";
			}

			protected string GetErrorUnresolvedEnvVarFailureReason()
			{
				return "Can't resolve the environment variable " + m_EnvVarWith2PercentsChar + ".";
			}

			//
			// EnvVar resolving!
			//
			protected bool TryResolveEnvVar(out string pathStringResolved)
			{
				string envVarValue;
				if (!TryExpandMyEnvironmentVariables(out envVarValue))
				{
					pathStringResolved = null;
					return false;
				}
				Debug.Assert(envVarValue != null);
				Debug.Assert(envVarValue.Length > 0);

				var envVarWith2PercentsLength = m_EnvVarWith2PercentsChar.Length;
				Debug.Assert(m_PathString.Length >= envVarWith2PercentsLength);

				var pathStringWithoutEnvVar = m_PathString.Substring(envVarWith2PercentsLength, m_PathString.Length - envVarWith2PercentsLength);

				pathStringResolved = envVarValue + pathStringWithoutEnvVar;
				return true;
			}

			#endregion Protected Methods

			#region Private Methods

			private string ComputeEnvVar()
			{
				Debug.Assert(MiscHelpers.IsAnEnvVarPath(m_PathString));
				Debug.Assert(m_PathString[0] == MiscHelpers.ENVVAR_PERCENT);
				var indexClose = m_PathString.IndexOf(MiscHelpers.ENVVAR_PERCENT, 1);
				Debug.Assert(indexClose > 1);
				return m_PathString.Substring(0, indexClose + 1);
			}

			private bool TryExpandMyEnvironmentVariables(out string envVarValue)
			{
				envVarValue = Environment.ExpandEnvironmentVariables(m_EnvVarWith2PercentsChar);
				return // envVarValue != null &&   <--  Resharper tells that this is always true!
					   envVarValue.Length > 0 &&
					   envVarValue != m_EnvVarWith2PercentsChar; // Replacement only occurs for environment variables that are set.
			}

			#endregion Private Methods
		}

		#endregion Private Classes
	}
}


text:
static NSMutableDictionary *namedConsoleSets = nil;

bool debugToLogFile = false;

@implementation SDLDebugTool

#pragma mark - Console Management
+ (void)addConsole:(NSObject<SDLDebugToolConsole> *)console {
    [self addConsole:console toGroup:@"default"];
}

+ (void)addConsole:(NSObject<SDLDebugToolConsole> *)console toGroup:(NSString *)groupName {
    // Make sure master dictionary exists
    if (namedConsoleSets == nil) {
        namedConsoleSets = [NSMutableDictionary new];
    }

    // Make sure the set to contain this group's elements exists
    if ([namedConsoleSets objectForKey:groupName] == nil) {
        [namedConsoleSets setValue:[NSMutableSet new] forKey:groupName];
    }

    // Add the console to the set
    [[namedConsoleSets valueForKey:groupName] addObject:console];
}

+ (void)removeConsole:(NSObject<SDLDebugToolConsole> *)console {
    [self removeConsole:console fromGroup:@"default"];
}

+ (void)removeConsole:(NSObject<SDLDebugToolConsole> *)console fromGroup:(NSString *)groupName {
    [[SDLDebugTool getConsoleListenersForGroup:groupName] removeObject:console];
}

+ (NSMutableSet *)getConsoleListenersForGroup:(NSString *)groupName {
    return [namedConsoleSets valueForKey:groupName];
}

#pragma mark - logging
+ (void)logInfo:(NSString *)info {
    [self logInfo:info withType:SDLDebugType_Debug toOutput:SDLDebugOutput_All toGroup:@"default"];
}

+ (void)logInfo:(NSString *)info withType:(SDLDebugType)type {
    [self logInfo:info withType:type toOutput:SDLDebugOutput_All toGroup:@"default"];
}

+ (void)logInfo:(NSString *)info withType:(SDLDebugType)type toOutput:(SDLDebugOutput)output {
    [SDLDebugTool logInfo:info withType:type toOutput:output toGroup:@"default"];
}

+ (void)logInfo:(NSString *)info andBinaryData:(NSData *)data withType:(SDLDebugType)type toOutput:(SDLDebugOutput)output {
    // convert binary data to string, append the two strings, then pass to usual log method.
    NSMutableString *outputString = [[NSMutableString alloc] init];
    if (info) {
        [outputString appendString:info];
    }

    if (data) {
        NSString *dataString = [SDLHexUtility getHexString:data];
        if (dataString) {
            [outputString appendString:dataString];
        }
    }

    [SDLDebugTool logInfo:outputString withType:type toOutput:output toGroup:@"default"];
}

// The designated logInfo method. All outputs should be performed here.
+ (void)logInfo:(NSString *)info withType:(SDLDebugType)type toOutput:(SDLDebugOutput)output toGroup:(NSString *)consoleGroupName {
    // Format the message, prepend the thread id
    NSMutableString *outputString = [NSMutableString stringWithFormat:@"[%li] %@", (long)[[NSThread currentThread] threadIndex], info];

    ////////////////////////////////////////////////
    //
    //  Output to the various destinations
    //
    ////////////////////////////////////////////////

    //Output To DeviceConsole
    if (output & SDLDebugOutput_DeviceConsole) {
        NSLog(@"%@", outputString);
    }

    //Output To DebugToolConsoles
    if (output & SDLDebugOutput_DebugToolConsole) {
        NSSet *consoleListeners = [self getConsoleListenersForGroup:consoleGroupName];
        for (NSObject<SDLDebugToolConsole> *console in consoleListeners) {
            [console logInfo:outputString];
        }
    }

    //Output To LogFile
    if (output & SDLDebugOutput_File) {
        [SDLDebugTool writeToLogFile:outputString];
    }

    //Output To Siphon
    [SDLSiphonServer init];
    [SDLSiphonServer _siphonNSLogData:outputString];
}

#pragma mark - file handling
+ (void)enableDebugToLogFile {
    debugToLogFile = true;

    [SDLDebugTool logInfo:@"Log File Enabled" withType:SDLDebugType_Debug];

    //Delete Log File If It Exists
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"smartdevicelink.log"];

    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        [SDLDebugTool logInfo:@"Log File Exisits, Deleteing" withType:SDLDebugType_Debug];
        [manager removeItemAtPath:filePath error:nil];
    }
}

+ (void)disableDebugToLogFile {
    debugToLogFile = false;
}

+ (void)writeToLogFile:(NSString *)info {
    // Warning: do not call any logInfo method from here. recursion of death.

    if (!debugToLogFile || info == NULL || info.length == 0) {
        return;
    }

    // Create timestamp string, add it in front of the message to be logged
    NSDate *currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/dd/YY HH:mm:ss.SSS"];
    NSString *dateString = [dateFormatter stringFromDate:currentDate];
    NSString *outputString = [dateString stringByAppendingFormat:@": %@\n", info];

    // file write takes an NSData, so convert string to data.
    NSData *dataToLog = [outputString dataUsingEncoding:NSUTF8StringEncoding];

    // If open/create file and write
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"smartdevicelink.log"];

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    if (fileHandle) {
        [fileHandle seekToEndOfFile];
        [fileHandle writeData:dataToLog];
        [fileHandle closeFile];
    } else {
        [dataToLog writeToFile:filePath atomically:NO];
    }
}

#pragma mark - Helper Methods
+ (NSString *)stringForDebugType:(SDLDebugType)debugType {
    switch (debugType) {
        case SDLDebugType_Debug:
            return @"DBG";
            break;
        case SDLDebugType_Transport_iAP:
            return @"iAP";
            break;
        case SDLDebugType_Transport_TCP:
            return @"TCP";
            break;
        case SDLDebugType_Protocol:
            return @"Pro";
            break;
        case SDLDebugType_RPC:
            return @"RPC";
            break;
        case SDLDebugType_APP:
            return @"APP";
            break;

        default:
            return @"Invalid DebugType";
            break;
    }
}

@end

redpajama_set_name: RedPajamaGithub


text:
\documentclass[12pt]{article}

\usepackage{setspace}

\usepackage[letterpaper]{geometry}
\geometry{top=1in, bottom=1in, left=1in, right=1in}

\usepackage{fancyhdr}
\pagestyle{fancy}

\lhead{}
\chead{}
\rhead{Jones \thepage}
\lfoot{}
\cfoot{}
\rfoot{}

\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}

\renewcommand{\refname}{Works Cited}
\setlength\headsep{0.333in}
\doublespacing

\makeatletter
\renewenvironment{thebibliography}[1]
     {\begin{center}{\refname}\end{center}%
      \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}%
      \list{\@biblabel{\@arabic\c@enumiv}}%
           {\settowidth\labelwidth{\@biblabel{#1}}%
            \leftmargin\labelwidth
            \advance\leftmargin\labelsep
            \@openbib@code
            \usecounter{enumiv}%
            \let\p@enumiv\@empty
            \renewcommand\theenumiv{\@arabic\c@enumiv}}%
      \sloppy
      \clubpenalty4000
      \@clubpenalty \clubpenalty
      \widowpenalty4000%
      \sfcode`\.\@m}
     {\def\@noitemerr
       {\@latex@warning{Empty `thebibliography' environment}}%
      \endlist}
\makeatother

\begin{document}

\begin{flushleft} {

Paul Jones\\
Professor   \\
Class (Reference Number) \\
\today \\
\begin{center}
Title
\end{center}

} \end{flushleft}

\setlength{\parindent}{0.5in}

% body

\clearpage

\bibliographystyle{mla-good}
\bibliography{bibliography.bib}

\end{document}


text:
package org.apache.hadoop.hive.ql.exec;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.hadoop.hive.common.classification.InterfaceAudience;
import org.apache.hadoop.hive.common.classification.InterfaceStability;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorUtils;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;

/**
 * exception class, thrown when udf argument have something wrong.
 */
@InterfaceAudience.Public
@InterfaceStability.Stable
public class UDFArgumentException extends SemanticException {

  public UDFArgumentException() {
    super();
  }

  public UDFArgumentException(String message) {
    super(message);
  }

  public UDFArgumentException(Throwable cause) {
    super(cause);
  }

  /**
   * Constructor.
   *
   * @param funcClass
   *          The UDF or UDAF class.
   * @param argTypeInfos
   *          The list of argument types that lead to an ambiguity.
   * @param methods
   *          All potential matches.
   */
  public UDFArgumentException(String message,
      Class<?> funcClass,
      List<TypeInfo> argTypeInfos,
      List<Method> methods) {
    super(getMessage(message, funcClass, argTypeInfos, methods));
    this.funcClass = funcClass;
    this.argTypeInfos = argTypeInfos;
    this.methods = methods;
  }

  private static String getMessage(String message,
      Class<?> funcClass,
      List<TypeInfo> argTypeInfos,
      List<Method> methods) {
    StringBuilder sb = new StringBuilder();
    sb.append(message);
    if (methods != null) {
      // Sort the methods before omitting them.
      sortMethods(methods);
      sb.append(". Possible choices: ");
      for (Method m: methods) {
        Type[] types = m.getGenericParameterTypes();
        sb.append("_FUNC_(");
        List<String> typeNames = new ArrayList<String>(types.length);
        for (int t = 0; t < types.length; t++) {
          if (t > 0) {
            sb.append(", ");
          }
          sb.append(ObjectInspectorUtils.getTypeNameFromJavaClass(types[t]));
        }
        sb.append(")  ");
      }
    }
    return sb.toString();
  }

  private static void sortMethods(List<Method> methods) {
    Collections.sort( methods, new Comparator<Method>(){

      @Override
      public int compare(Method m1, Method m2) {
        int result = m1.getName().compareTo(m2.getName());
        if (result != 0)
          return result;
        Type[] types1 = m1.getGenericParameterTypes();
        Type[] types2 = m2.getGenericParameterTypes();
        for (int i = 0; i < types1.length && i < types2.length; i++) {
          String type1 = ObjectInspectorUtils.getTypeNameFromJavaClass(types1[i]);
          String type2 = ObjectInspectorUtils.getTypeNameFromJavaClass(types2[i]);
          if ((result = type1.compareTo(type2)) != 0)
            return result;
        }
        return types1.length - types2.length;
      }

    });
  }

  /**
   * The UDF or UDAF class that has the ambiguity.
   */
  private Class<?> funcClass;

  /**
   * The list of parameter types.
   */
  private List<TypeInfo> argTypeInfos;

  /**
   * The list of matched methods.
   */
  private List<Method> methods;

  public Class<?> getFunctionClass() {
    return funcClass;
  }

  public List<TypeInfo> getArgTypeList() {
    return argTypeInfos;
  }

  public List<Method> getMethods() {
    return methods;
  }

}


text:
<?php

namespace Ayamel\ApiBundle\Tests;
use Ayamel\ApiBundle\ApiTestCase;

class ResourceCollectionTest extends ApiTestCase
{
    public function testCreateResourceCollection()
    {
        $data = array(
            'title' => 'yo dawg',
            'type' => 'collection'
        );
        $return = $this->getJson("POST", '/api/v1/resources?_key=45678isafgd56789asfgdhf4567', [], [], array(
            'CONTENT_TYPE' => 'application/json'
        ), json_encode($data));

        $this->assertSame(201, $return['response']['code']);

        $uploadUrl = substr($return['contentUploadUrl'], strlen('http://localhost'));

        return $uploadUrl;
    }

    /**
     * @depends testCreateResourceCollection
     */
    public function testCollectionDoesNotAllowContentUploading($uploadUrl)
    {
        $return = $this->getJson('POST', $uploadUrl.'?_key=45678isafgd56789asfgdhf4567', [], [], array(
            'CONTENT_TYPE' => 'application/json'
        ), json_encode(array(
            'uri' => 'http://www.google.com/'
        )));

        $this->assertSame(400, $return['response']['code']);
    }
}


text:
namespace BuildDataDriver.Interfaces
{
    public interface IFtpDestination
    {
        string FtpId { get; set; }
        string FTPDirectory { get; set; }
    }
}


text:
package core

import (
	"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
	"net/http"
)

// TerminateInstanceRequest wrapper for the TerminateInstance operation
//
// # See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/TerminateInstance.go.html to see an example of how to use TerminateInstanceRequest.
type TerminateInstanceRequest struct {

	// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the instance.
	InstanceId *string `mandatory:"true" contributesTo:"path" name:"instanceId"`

	// For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match`
	// parameter to the value of the etag from a previous GET or POST response for that resource. The resource
	// will be updated or deleted only if the etag you provide matches the resource's current etag value.
	IfMatch *string `mandatory:"false" contributesTo:"header" name:"if-match"`

	// Specifies whether to delete or preserve the boot volume when terminating an instance.
	// The default value is false.
	PreserveBootVolume *bool `mandatory:"false" contributesTo:"query" name:"preserveBootVolume"`

	// Unique Oracle-assigned identifier for the request.
	// If you need to contact Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`

	// Metadata about the request. This information will not be transmitted to the service, but
	// represents information that the SDK will consume to drive retry behavior.
	RequestMetadata common.RequestMetadata
}

func (request TerminateInstanceRequest) String() string {
	return common.PointerString(request)
}

// HTTPRequest implements the OCIRequest interface
func (request TerminateInstanceRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {

	return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}

// BinaryRequestBody implements the OCIRequest interface
func (request TerminateInstanceRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {

	return nil, false

}

// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request TerminateInstanceRequest) RetryPolicy() *common.RetryPolicy {
	return request.RequestMetadata.RetryPolicy
}

// TerminateInstanceResponse wrapper for the TerminateInstance operation
type TerminateInstanceResponse struct {

	// The underlying http response
	RawResponse *http.Response

	// Unique Oracle-assigned identifier for the request. If you need to contact
	// Oracle about a particular request, please provide the request ID.
	OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}

func (response TerminateInstanceResponse) String() string {
	return common.PointerString(response)
}

// HTTPResponse implements the OCIResponse interface
func (response TerminateInstanceResponse) HTTPResponse() *http.Response {
	return response.RawResponse
}


text:
import { Directive, Input, forwardRef } from '@angular/core';
import { NG_VALIDATORS, Validator, Validators, AbstractControl, ValidatorFn } from '@angular/forms';

import { CovalentValidators } from '../validators';

export const MIN_VALIDATOR: any = {
  provide: NG_VALIDATORS,
  useExisting: forwardRef(() => TdMinValidator),
  multi: true,
};

@Directive({
  selector: '[min][formControlName],[min][formControl],[min][ngModel]',
  providers: [ MIN_VALIDATOR ],
})
export class TdMinValidator implements Validator {

  private _validator: ValidatorFn;

  @Input('min')
  set min(min: number) {
    this._validator = CovalentValidators.min(min);
  }

  validate(c: AbstractControl): {[key: string]: any} {
    return this._validator(c);
  }
}


text:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^events/$', views.events),
    url(r'^user/new/$', views.user_new, name='user_new'),
]


text:
from __future__ import unicode_literals

from django.db import models
from compute.models import Computer
from image.models import Imagerevision
# Create your models here.

class Openstackcomputermap(models.Model):
    instanceid = models.CharField(primary_key=True, max_length=50)
    computerid = models.OneToOneField(Computer, db_column='computerid', blank=True, null=True)

    class Meta:

        db_table = 'openstackcomputermap'

class Openstackimagerevision(models.Model):
    imagerevisionid = models.OneToOneField(Imagerevision, db_column='imagerevisionid', primary_key=True)
    imagedetails = models.TextField()
    flavordetails = models.TextField()

    class Meta:

        db_table = 'openstackimagerevision'


text:
if ( [ -z "$GHA2DB_PROJECT" ] || [ -z "$PG_DB" ] || [ -z "$PG_PASS" ] )
then
  echo "$0: you need to set GHA2DB_PROJECT, PG_DB, PG_PASS env variables to use this script"
  exit 1
fi
function finish {
    sync_unlock.sh
}
if [ -z "$TRAP" ]
then
  sync_lock.sh || exit -1
  trap finish EXIT
  export TRAP=1
fi
GHA2DB_LOCAL=1 ./runq scripts/clean_affiliations.sql || exit 1
GHA2DB_LOCAL=1 ./import_affs github_users.json || exit 2
GHA2DB_LOCAL=1 ./runq util_sql/update_country_names.sql || exit 3
GHA2DB_TAGS_YAML=metrics/$GHA2DB_PROJECT/tags_affs.yaml GHA2DB_LOCAL=1 ./tags


text:
/*Package onion is a layer based, pluggable config manager for golang.
The goal is to have multiple layer and load value base on this layers. the first layer with the response
is used to provide the response.
*/
package onion


text:
package models

import (
	"github.com/UserStack/ustackd/backends"
	"github.com/UserStack/ustackweb/backend"
)

type UserCollection struct {
}

func (this *UserCollection) collect(backendUsers []backends.User) (users []User) {
	users = make([]User, len(backendUsers))
	for idx, backendUser := range backendUsers {
		users[idx] = User{backendUser}
	}
	return
}

func (this *UserCollection) All() (users []User, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendUsers, backendError := connection.Users()
	if backendError == nil {
		users = this.collect(backendUsers)
	}
	return
}

func (this *UserCollection) AllByGroup(groupId string) (users []User, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendUsers, backendError := connection.GroupUsers(groupId)
	if backendError == nil {
		users = this.collect(backendUsers)
	}
	return
}

func (this *UserCollection) Find(uid int64) (user *User, err *backend.Error) {
	allUsers, err := this.All()
	if err != nil {
		return
	}
	for _, aUser := range allUsers {
		if aUser.Uid == uid {
			user = &aUser
			return
		}
	}
	return
}

func (this *UserCollection) FindByName(username string) (user *User, err *backend.Error) {
	allUsers, err := this.All()
	if err != nil {
		return
	}
	for _, aUser := range allUsers {
		if aUser.Name == username {
			user = &aUser
			return
		}
	}
	return
}

func (this *UserCollection) Login(username string, password string) (loggedIn bool, id int64, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	id, backendError := connection.LoginUser(username, password)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		loggedIn = id > 0
	}
	return
}

func (this *UserCollection) Create(username string, password string) (created bool, id int64, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	id, backendError := connection.CreateUser(username, password)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		created = id > 0
	}
	return
}

func (this *UserCollection) UpdateUsername(name_or_uid string, password string, newUsername string) (updated bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.ChangeUserName(name_or_uid, password, newUsername)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		updated = err == nil
	}
	return
}

func (this *UserCollection) UpdatePassword(name_or_uid string, password string, newPassword string) (updated bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.ChangeUserPassword(name_or_uid, password, newPassword)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		updated = err == nil
	}
	return
}

func (this *UserCollection) AddUserToGroup(name_or_uid string, group_id string) (updated bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.AddUserToGroup(name_or_uid, group_id)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		updated = err == nil
	}
	return
}

func (this *UserCollection) RemoveUserFromGroup(name_or_uid string, group_id string) (updated bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.RemoveUserFromGroup(name_or_uid, group_id)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		updated = err == nil
	}
	return
}

func (this *UserCollection) Destroy(name_or_uid string) (deleted bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.DeleteUser(name_or_uid)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		deleted = err == nil
	}
	return
}

func (this *UserCollection) Enable(name_or_uid string) (deleted bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.EnableUser(name_or_uid)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		deleted = err == nil
	}
	return
}

func (this *UserCollection) Disable(name_or_uid string) (deleted bool, err *backend.Error) {
	connection, err := backend.Connection()
	if err != nil {
		return
	}
	backendError := connection.DisableUser(name_or_uid)
	backend.VerifyConnection(backendError)
	if backendError == nil {
		deleted = err == nil
	}
	return
}

func Users() *UserCollection {
	return &UserCollection{}
}


text:
using Itinero.Algorithms.Weights;
using Itinero.Data.Contracted;
using Itinero.Graphs.Directed;
using Itinero.Profiles;
using System;
using System.Collections.Generic;
using System.Threading;

namespace Itinero.Algorithms.Contracted.Dual.ManyToMany
{
    /// <summary>
    /// An algorithm to calculate many-to-many weights based on a contraction hierarchy between source and target vertices.
    /// </summary>
    public class VertexToVertexAlgorithm<T> : AlgorithmBase
        where T : struct
    {
        private readonly DirectedMetaGraph _graph;
        private readonly DykstraSource<T>[] _sources;
        private readonly DykstraSource<T>[] _targets;
        private readonly Dictionary<uint, Dictionary<int, EdgePath<T>>> _buckets;
        private readonly WeightHandler<T> _weightHandler;
        private readonly T _max;

        /// <summary>
        /// Creates a new algorithm.
        /// </summary>
        public VertexToVertexAlgorithm(DirectedMetaGraph graph, WeightHandler<T> weightHandler, DykstraSource<T>[] sources,
            DykstraSource<T>[] targets, T max)
        {
            _graph = graph;
            _sources = sources;
            _targets = targets;
            _weightHandler = weightHandler;
            _max = max;

            _buckets = new Dictionary<uint, Dictionary<int, EdgePath<T>>>();
        }

        private struct Solution
        {
            public EdgePath<T> Path1 { get; set; }

            public EdgePath<T> Path2 { get; set; }

            public EdgePath<T> Path { get; set; }
        }

        private Solution[][] _solutions;

        /// <summary>
        /// Executes the actual run.
        /// </summary>
        protected override void DoRun(CancellationToken cancellationToken)
        {
            _solutions = new Solution[_sources.Length][];
            for(var s = 0; s < _sources.Length; s++)
            {
                _solutions[s] = new Solution[_targets.Length];
            }

            // do forward searches into buckets.
            for (var i = 0; i < _sources.Length; i++)
            {
                var forward = new Dykstra<T>(_graph, _weightHandler, _sources[i], false, _max);
                forward.WasFound += (p, v, w) =>
                {
                    return this.ForwardVertexFound(forward, i, p, v, w);
                };
                forward.Run(cancellationToken);
            }

            // do backward searches into buckets.
            for (var i = 0; i < _targets.Length; i++)
            {
                var backward = new Dykstra<T>(_graph, _weightHandler, _targets[i], true, _max);
                backward.WasFound += (p, v, w) =>
                {
                    return this.BackwardVertexFound(backward, i, p, v, w);
                };
                backward.Run(cancellationToken);
            }

            this.HasSucceeded = true;
        }

        /// <summary>
        /// Gets the weights.
        /// </summary>
        public EdgePath<T> GetPath(int source, int target)
        {
            this.CheckHasRunAndHasSucceeded();

            var solution = _solutions[source][target];
            if (solution.Path == null)
            {
                if (solution.Path1 == null || solution.Path2 == null)
                {
                    return null;
                }
                if (solution.Path != null)
                {
                    return solution.Path;
                }

                var fromSource = solution.Path1;
                var toTarget = solution.Path2;
                var vertices = new List<uint>();

                // add vertices from source.
                vertices.Add(fromSource.Vertex);
                while (fromSource.From != null)
                {
                    if (fromSource.From.Vertex != Constants.NO_VERTEX)
                    { // this should be the end of the path.
                        if (fromSource.Edge == Constants.NO_EDGE)
                        { // only expand when there is no edge id.
                            _graph.ExpandEdge(fromSource.From.Vertex, fromSource.Vertex, vertices, false, true);
                        }
                    }
                    vertices.Add(fromSource.From.Vertex);
                    fromSource = fromSource.From;
                }
                vertices.Reverse();

                // and add vertices to target.
                while (toTarget.From != null)
                {
                    if (toTarget.From.Vertex != Constants.NO_VERTEX)
                    { // this should be the end of the path.
                        if (toTarget.Edge == Constants.NO_EDGE)
                        { // only expand when there is no edge id.
                            _graph.ExpandEdge(toTarget.From.Vertex, toTarget.Vertex, vertices, false, false);
                        }
                    }
                    vertices.Add(toTarget.From.Vertex);
                    toTarget = toTarget.From;
                }

                var path = new EdgePath<T>(vertices[0]);
                for (var i = 1; i < vertices.Count; i++)
                {
                    path = new EdgePath<T>(vertices[i], default(T), path);
                }

                solution.Path = path;
            }
            return solution.Path;
        }

        /// <summary>
        /// Called when a forward vertex was found.
        /// </summary>
        /// <returns></returns>
        private bool ForwardVertexFound(Dykstra<T> dykstra, int i, uint pointer, uint vertex, T weight)
        {
            Dictionary<int, EdgePath<T>> bucket;
            if (!_buckets.TryGetValue(vertex, out bucket))
            {
                bucket = new Dictionary<int, EdgePath<T>>();
                _buckets.Add(vertex, bucket);
                bucket[i] = dykstra.GetPath(pointer);
            }
            else
            {
                EdgePath<T> existing;
                if (bucket.TryGetValue(i, out existing))
                {
                    if (_weightHandler.IsSmallerThan(weight, existing.Weight))
                    {
                        bucket[i] = dykstra.GetPath(pointer);
                    }
                }
                else
                {
                    bucket[i] = dykstra.GetPath(pointer);
                }
            }
            return false;
        }

        /// <summary>
        /// Called when a backward vertex was found.
        /// </summary>
        /// <returns></returns>
        private bool BackwardVertexFound(Dykstra<T> dykstra, int i, uint pointer, uint vertex, T weight)
        {
            Dictionary<int, EdgePath<T>> bucket;
            if (_buckets.TryGetValue(vertex, out bucket))
            {
                foreach (var pair in bucket)
                {
                    var existing = _solutions[pair.Key][i];
                    var total = _weightHandler.Add(weight, pair.Value.Weight);
                    var existingWeight = _weightHandler.Infinite;
                    if (existing.Path != null)
                    {
                        existingWeight = existing.Path.Weight;
                    }
                    else if (existing.Path1 != null &&
                        existing.Path2 != null)
                    {
                        existingWeight = _weightHandler.Add(existing.Path1.Weight,
                            existing.Path2.Weight);
                    }
                    if (_weightHandler.IsSmallerThan(total, existingWeight))
                    { // append the backward to the forward path.
                        _solutions[pair.Key][i] = new Solution()
                        {
                            Path1 = pair.Value,
                            Path2 = dykstra.GetPath(pointer)
                        };
                    }
                }
            }
            return false;
        }
    }

    // TODO: implement a non-generic non-weighthandler version.
}


text:
(function ($) {
    function Pagination (opts) {
        this.itemsCount = opts.itemsCount;
        this.pageSize = opts.pageSize;
        this.displayPage = opts.displayPage;
        opts.itemsCount % opts.pageSize == 0 ? this.pages = opts.itemsCount / opts.pageSize : this.pages = parseInt(opts.itemsCount / opts.pageSize) + 1;
        this.currentPage = opts.currentPage;
        this.styleClass = opts.styleClass;
    };

    Pagination.prototype = {
        //generate the outer wrapper with the config of custom style
        _draw: function (hookNode) {
                var tpl = '<div class="pagination';
                for (var i = 0; i < this.styleClass.length; i++) {
                    tpl += ' '+ this.styleClass[i];
                }
                tpl += '">
'
            hookNode.html(tpl);
            this._drawInner(hookNode);
        },
        //generate the true pagination
        _drawInner: function (hookNode) {
            var outer = hookNode.children('.pagination');
            var tpl = '
'
                    + '
«上一页
';
            if ( this.pages <= this.displayPage) {
                for ( var i = 1; i < this.pages + 1; i++) {
                    i == this.currentPage ? (tpl += '
' +i + '
') : (tpl += '
' +i + '
');
                }

            } else {

            }
                /*tpl += '
...
'*/
                tpl += '
 this.pages ? ' disabled' : ' ') + '">下一页»
'
                    + '
'
            outer.html(tpl);
        },

        _select: function (opts, hookNode) {
            var self = this;
            hookNode.children('.pagination').on('click', 'a', function (e) {
                e.preventDefault();
                if ( !$(this).parent().hasClass('disabled') && !$(this).parent().hasClass('active') ) {
                    self.currentPage = parseInt($(this).attr('data'));
                    self._drawInner(hookNode);
                    if ( $.isFunction( opts.selectCallBack ) ) {
                        opts.selectCallBack.call(this, $(this).attr('data'));
                    }
                }
            })
        },

        init: function (opts, hookNode) {
            this._draw(hookNode);
            this._select(opts, hookNode);
        },

        updateItemsCount: function (itemsCount, hookNode) {
            itemsCount % this.pageSize == 0 ? this.pages = itemsCount / this.pageSize : this.pages = parseInt(itemsCount / this.pageSize) + 1;
            this._drawInner(hookNode);
        }
    }

    $.fn.pagination = function (options) {
        var opts = $.extend({}, $.fn.pagination.defaults, options);
        return this.each( function () {
            new Pagination(opts).init(opts, $(this));
        });
    };

    $.fn.pagination.defaults = {
        pageSize: 10,
        displayPage: 6,
        currentPage: 1,
        itemsCount: 100,
        styleClass: [],
        selectCallBack: null
    }

})(window.jQuery)


text:
<?php
/**
 * Created by PhpStorm.
 * Date: 23.09.2016
 */
defined('BASEPATH') OR exit('No direct script access allowed');
?>

<?=$tplTitle;?>

            <?=bootstrapAlert($tplData);?>
            <?=form_open('tutorial/createcat'); ?>

                <?=lang('label_title_de');?>*
                <input type="text" class="form-control" name="title_de" value="">

                <?=lang('label_title_en');?>*
                <input type="text" class="form-control" name="title_en" value="">

                <?=lang('label_page_index');?>*

                <input type="number" name="zIndex" value="<?=($tplData['maxCatZIndex']*1+1);?>" min="1" max="<?=($tplData['maxCatZIndex']*1+1);?>">

                <?=lang('label_active');?>

                <?=bootstrapBtnGroupUnique(1,['no','yes'],['name'=>'active']);?>

                <?=bootstrapHelpBlock(lang('label_help_input_required'));?>

            <button type="submit" class="btn btn-default"><?=lang('label_save'); ?></button>
            </form>


text:
Quiz Game
=========

In this lab you are going to create a game that asks a user 5 random questions from a list of questions. You will read your questions from a file and then select 5 random questions from the list.

1. You will need to create a file format to store your question and answer pairs in. For example, you could separate them using pipes:

::

    How many symphonies did Ludwig van Beethoven compose?|9
    How many prime numbers are there between 50 and 100?|10
    Which U.S. city has these three nicknames: air crossroads of the world, Chicago of the north, largest city in the largest state?|ANCHORAGE

2. You will read your file as a list of lines. To get the length of your list use the :code:`len(questions)` command. Generate 5 random numbers between 0 and length of list. Make sure they're all different!

3. Separate your question from your answer and print your question. Prompt for the users input. If it's a string you may want to remove spaces and punctuation from the answer and convert it to all upper case before comparing to your answer.

4. At the end of the 5 questions, print the user's score.

Don't forget your README file and to put your program on GitHub named :code:`cs110-math-quiz` so it can be graded.

Rubric
------

- **[5 Points]** Student has a GitHub repository under their username named :code:`cs110-quiz-game` that contains the quiz game Python file.
- **[10 Points]** Correctly uses randint() function to generate different random numbers.
- **[10 Points]** Correctly prints the question
- **[30 Points]** Allows user to input their response and converts it properly
- **[30 Points]** Script correctly determines whether user's answer was correct and outputs appropriate message at end of game.
- **[10 Points]** Student has a properly formated `README.md` file in their repository
- **[5 Points]** Commit messages


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Threading.Tasks;
using Azure.AI.FormRecognizer.Training;
using Azure.Core;
using Azure.Core.TestFramework;

namespace Azure.AI.FormRecognizer.Tests
{
    public class FormRecognizerLiveTestBase : RecordedTestBase<FormRecognizerTestEnvironment>
    {
        protected TimeSpan PollingInterval => TimeSpan.FromSeconds(Mode == RecordedTestMode.Playback ? 0 : 1);

        public FormRecognizerLiveTestBase(bool isAsync)
            : base(isAsync)
        {
            Sanitizer = new FormRecognizerRecordedTestSanitizer();
        }

        /// <summary>
        /// Creates a <see cref="FormRecognizerClient" /> with the endpoint and API key provided via environment
        /// variables and instruments it to make use of the Azure Core Test Framework functionalities.
        /// </summary>
        /// <param name="useTokenCredential">Whether or not to use a <see cref="TokenCredential"/> to authenticate. An <see cref="AzureKeyCredential"/> is used by default.</param>
        /// <param name="apiKey">The API key to use for authentication. Defaults to <see cref="FormRecognizerTestEnvironment.ApiKey"/>.</param>
        /// <param name="skipInstrumenting">Whether or not instrumenting should be skipped. Avoid skipping it as much as possible.</param>
        /// <returns>The instrumented <see cref="FormRecognizerClient" />.</returns>
        protected FormRecognizerClient CreateFormRecognizerClient(bool useTokenCredential = false, string apiKey = default, bool skipInstrumenting = false)
        {
            var endpoint = new Uri(TestEnvironment.Endpoint);
            var options = InstrumentClientOptions(new FormRecognizerClientOptions());
            FormRecognizerClient client;

            if (useTokenCredential)
            {
                client = new FormRecognizerClient(endpoint, TestEnvironment.Credential, options);
            }
            else
            {
                var credential = new AzureKeyCredential(apiKey ?? TestEnvironment.ApiKey);
                client = new FormRecognizerClient(endpoint, credential, options);
            }

            return skipInstrumenting ? client : InstrumentClient(client);
        }

        /// <summary>
        /// Creates a <see cref="FormTrainingClient" /> with the endpoint and API key provided via environment
        /// variables and instruments it to make use of the Azure Core Test Framework functionalities.
        /// </summary>
        /// <param name="useTokenCredential">Whether or not to use a <see cref="TokenCredential"/> to authenticate. An <see cref="AzureKeyCredential"/> is used by default.</param>
        /// <param name="apiKey">The API key to use for authentication. Defaults to <see cref="FormRecognizerTestEnvironment.ApiKey"/>.</param>
        /// <param name="skipInstrumenting">Whether or not instrumenting should be skipped. Avoid skipping it as much as possible.</param>
        /// <returns>The instrumented <see cref="FormTrainingClient" />.</returns>
        protected FormTrainingClient CreateFormTrainingClient(bool useTokenCredential = false, string apiKey = default, bool skipInstrumenting = false)
        {
            var endpoint = new Uri(TestEnvironment.Endpoint);
            var options = InstrumentClientOptions(new FormRecognizerClientOptions());
            FormTrainingClient client;

            if (useTokenCredential)
            {
                client = new FormTrainingClient(endpoint, TestEnvironment.Credential, options);
            }
            else
            {
                var credential = new AzureKeyCredential(apiKey ?? TestEnvironment.ApiKey);
                client = new FormTrainingClient(endpoint, credential, options);
            }

            return skipInstrumenting ? client : InstrumentClient(client);
        }

        /// <summary>
        /// Trains a model and returns the associated <see cref="DisposableTrainedModel"/> instance, from which
        /// the model ID can be obtained. Upon disposal, the model will be deleted.
        /// </summary>
        /// <param name="useTrainingLabels">If <c>true</c>, use a label file created in the <link-to-label-tool-doc> to provide training-time labels for training a model. If <c>false</c>, the model will be trained from forms only.</param>
        /// <param name="useMultipageFiles">Whether or not to use multipage files for training.</param>
        /// <returns>A <see cref="DisposableTrainedModel"/> instance from which the trained model ID can be obtained.</returns>
        protected async Task<DisposableTrainedModel> CreateDisposableTrainedModelAsync(bool useTrainingLabels, ContainerType containerType = default)
        {
            var trainingClient = CreateFormTrainingClient();

            string trainingFiles = containerType switch
            {
                ContainerType.Singleforms => TestEnvironment.BlobContainerSasUrl,
                ContainerType.MultipageFiles => TestEnvironment.MultipageBlobContainerSasUrl,
                ContainerType.SelectionMarks => TestEnvironment.SelectionMarkBlobContainerSasUrl,
                _ => TestEnvironment.BlobContainerSasUrl,
            };
            var trainingFilesUri = new Uri(trainingFiles);

            return await DisposableTrainedModel.TrainModelAsync(trainingClient, trainingFilesUri, useTrainingLabels, PollingInterval);
        }

        protected enum ContainerType
        {
            Singleforms,
            MultipageFiles,
            SelectionMarks
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 45: 911 (1953)

#### Original name
Galerina pallidispora A.H. Sm.

### Remarks
null


text:
package org.springframework.orm.jpa;

import javax.persistence.EntityManager;

/**
 * Extension of the standard JPA EntityManager interface, linking in
 * Spring's EntityManagerPlusOperations interface which defines additional
 * operations (beyond JPA 1.0) in a vendor-independent fashion.
 *
 * @author Rod Johnson
 * @since 2.0
 * @see javax.persistence.EntityManager
 */
public interface EntityManagerPlus extends EntityManager, EntityManagerPlusOperations {

}


text:
from zadarapy import session
from zadarapy.vpsa.drives import get_all_drives
import pytest

@pytest.fixture(scope="session")
def zsession():
    return session.Session()

@pytest.fixture(scope="function")
def all_drives(zsession):
    return get_all_drives(zsession)


text:
layout: page
title: About
permalink: /about/
---

Tracy Canfield's [short fiction](/fiction/) has appeared in Analog,
Strange Horizons, Fantasy Magazine, and numerous other
magazines and anthologies.  Her story "Starship Down" won the *Analyitical
Laboratory Award* for best short story appearing in *Analog*, and her story
["The Seal of Sulaymaan"](http://www.fantasy-magazine.com/fiction/the-seal-of-sulaymaan/) was a Million Writers Award Notable Story.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>it.andreascarpino</groupId>
	<artifactId>ansible-inventory-java</artifactId>
	<version>1.0-SNAPSHOT</version>

	<name>Ansible Inventory Java</name>
	<description>A library to read and write Ansible static inventories</description>
	<url>https://gitlab.com/ilpianista/ansible-inventory-java</url>

	<licenses>
		<license>
			<name>MIT License</name>
			<url>https://opensource.org/licenses/mit</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<scm>
		<url>https://gitlab.com/ilpianista/ansible-inventory-java.git</url>
	</scm>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-failsafe-plugin</artifactId>
				<version>3.0.0-M5</version>
				<configuration>
					<includes>
						<include>*IT.java</include>
					</includes>
				</configuration>
				<executions>
					<execution>
						<id>integration-test</id>
						<phase>integration-test</phase>
						<goals>
							<goal>integration-test</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.10.3</version>
				<executions>
					<execution>
						<id>attach-javadocs</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>3.0.0</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.4</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.13.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

</project>


text:
<?php

namespace Doctrine\Search;

use Doctrine\Search\SearchManager;
use Doctrine\Search\Exception\DoctrineSearchException;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Search\Mapping\ClassMetadata;
use Traversable;

class UnitOfWork
{
    /**
     * The SearchManager that "owns" this UnitOfWork instance.
     *
     * @var \Doctrine\Search\SearchManager
     */
    private $sm;

    /**
     * The EventManager used for dispatching events.
     *
     * @var \Doctrine\Common\EventManager
     */
    private $evm;

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

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

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

    /**
     * Initializes a new UnitOfWork instance, bound to the given SearchManager.
     *
     * @param \Doctrine\Search\EntityManager $sm
     */
    public function __construct(SearchManager $sm)
    {
        $this->sm = $sm;
        $this->evm = $sm->getEventManager();
    }

    /**
     * Persists an entity as part of the current unit of work.
     *
     * @param object $entity The entity to persist.
     */
    public function persist($entity)
    {
        if ($this->evm->hasListeners(Events::prePersist)) {
            $this->evm->dispatchEvent(Events::prePersist, new Event\LifecycleEventArgs($entity, $this->sm));
        }

        $oid = spl_object_hash($entity);
        $this->scheduledForPersist[$oid] = $entity;

        if ($this->evm->hasListeners(Events::postPersist)) {
            $this->evm->dispatchEvent(Events::postPersist, new Event\LifecycleEventArgs($entity, $this->sm));
        }
    }

    /**
     * Deletes an entity as part of the current unit of work.
     *
     * @param object $entity The entity to remove.
     */
    public function remove($entity)
    {
        if ($this->evm->hasListeners(Events::preRemove)) {
            $this->evm->dispatchEvent(Events::preRemove, new Event\LifecycleEventArgs($entity, $this->sm));
        }

        $oid = spl_object_hash($entity);
        $this->scheduledForDelete[$oid] = $entity;

        if ($this->evm->hasListeners(Events::postRemove)) {
            $this->evm->dispatchEvent(Events::postRemove, new Event\LifecycleEventArgs($entity, $this->sm));
        }
    }

    /**
     * Clears the UnitOfWork.
     *
     * @param string $entityName if given, only entities of this type will get detached
     */
    public function clear($entityName = null)
    {
        if ($entityName === null) {
            $this->scheduledForDelete =
            $this->scheduledForPersist =
            $this->updatedIndexes = array();
        } else {
            //TODO: implement for named entity classes
        }

        if ($this->evm->hasListeners(Events::onClear)) {
            $this->evm->dispatchEvent(Events::onClear, new Event\OnClearEventArgs($this->sm, $entityName));
        }
    }

    /**
     * Commits the UnitOfWork, executing all operations that have been postponed
     * up to this point.
     *
     * The operations are executed in the following order:
     *
     * 1) All entity inserts
     * 2) All entity deletions
     *
     * @param null|object|array $entity
     */
    public function commit($entity = null)
    {
        if ($this->evm->hasListeners(Events::preFlush)) {
            $this->evm->dispatchEvent(Events::preFlush, new Event\PreFlushEventArgs($this->sm));
        }

        //TODO: single/array entity commit handling
        $this->commitRemoved();
        $this->commitPersisted();

        //Force refresh of updated indexes
        if ($entity === true) {
            $client = $this->sm->getClient();
            foreach (array_unique($this->updatedIndexes) as $index) {
                $client->refreshIndex($index);
            }
        }

        $this->clear();

        if ($this->evm->hasListeners(Events::postFlush)) {
            $this->evm->dispatchEvent(Events::postFlush, new Event\PostFlushEventArgs($this->sm));
        }
    }

    /**
     * Commit persisted entities to the database
     */
    private function commitPersisted()
    {
        $sortedDocuments = $this->sortObjects($this->scheduledForPersist);
        $client = $this->sm->getClient();

        foreach ($sortedDocuments as $entityName => $documents) {
            $classMetadata = $this->sm->getClassMetadata($entityName);
            $this->updatedIndexes[] = $classMetadata->index;
            $client->addDocuments($classMetadata, $documents);
        }
    }

    /**
     * Commit deleted entities to the database
     */
    private function commitRemoved()
    {
        $documents = $this->sortObjects($this->scheduledForDelete, false);
        $client = $this->sm->getClient();

        foreach ($documents as $entityName => $documents) {
            $classMetadata = $this->sm->getClassMetadata($entityName);
            $this->updatedIndexes[] = $classMetadata->index;
            $client->removeDocuments($classMetadata, $documents);
        }
    }

    /**
     * Prepare entities for commit. Entities scheduled for deletion do not need
     * to be serialized.
     *
     * @param array $objects
     * @param boolean $serialize
     * @throws DoctrineSearchException
     * @return array
     */
    private function sortObjects(array $objects, $serialize = true)
    {
        $documents = array();
        $serializer = $this->sm->getSerializer();

        foreach ($objects as $object) {
            $document = $serialize ? $serializer->serialize($object) : $object;

            $id = (string) $object->getId();
            if (!$id) {
                throw new DoctrineSearchException('Entity must have an id to be indexed');
            }

            $documents[get_class($object)][$id] = $document;
        }

        return $documents;
    }

    /**
     * Load and hydrate a document model
     *
     * @param ClassMetadata $class
     * @param mixed $value
     * @param array $options
     */
    public function load(ClassMetadata $class, $value, $options = array())
    {
        $client = $this->sm->getClient();

        if (isset($options['field'])) {
            $document = $client->findOneBy($class, $options['field'], $value);
        } else {
            $document = $client->find($class, $value, $options);
        }

        return $this->hydrateEntity($class, $document);
    }

    /**
     * Load and hydrate a document collection
     *
     * @param array $classes
     * @param unknown $query
     */
    public function loadCollection(array $classes, $query)
    {
        $results = $this->sm->getClient()->search($query, $classes);
        return $this->hydrateCollection($classes, $results);
    }

    /**
     * Construct an entity collection
     *
     * @param array $classes
     * @param Traversable $resultSet
     */
    public function hydrateCollection(array $classes, Traversable $resultSet)
    {
        $collection = new ArrayCollection();
        foreach ($resultSet as $document) {
            foreach ($classes as $class) {
                if ($document->getIndex() == $class->index && $document->getType() == $class->type) {
                    break;
                }
            }
            $collection[] = $this->hydrateEntity($class, $document);
        }

        return $collection;
    }

    /**
     * Construct an entity object
     *
     * @param ClassMetadata $class
     * @param object $document
     */
    public function hydrateEntity(ClassMetadata $class, $document)
    {
        // TODO: add support for different result set types from different clients
        // perhaps by wrapping documents in a layer of abstraction
        $data = $document->getData();
        $fields = array_merge(
            $document->hasFields() ? $document->getFields() : array(),
            array('_version' => $document->getVersion())
        );

        foreach ($fields as $name => $value) {
            if (isset($class->parameters[$name])) {
                $data[$name] = $value;
            } else {
                foreach ($class->parameters as $param => $mapping) {
                    if (isset($mapping['fieldName']) && $mapping['fieldName'] == $name) {
                        $data[$param] = $value;
                        break;
                    }
                }
            }
        }

        $data[$class->getIdentifier()] = $document->getId();

        $entity = $this->sm->getSerializer()->deserialize($class->className, json_encode($data));

        if ($this->evm->hasListeners(Events::postLoad)) {
            $this->evm->dispatchEvent(Events::postLoad, new Event\LifecycleEventArgs($entity, $this->sm));
        }

        return $entity;
    }

    /**
     * Checks whether an entity is registered in the identity map of this UnitOfWork.
     *
     * @param object $entity
     *
     * @return boolean
     */
    public function isInIdentityMap($entity)
    {
        $oid = spl_object_hash($entity);
        return isset($this->scheduledForPersist[$oid]) || isset($this->scheduledForDelete[$oid]);
    }
}


text:
/* eslint-disable
  @typescript-eslint/no-unsafe-argument,
  @typescript-eslint/no-unsafe-assignment,
  @typescript-eslint/no-unsafe-call,
*/
import { promises as fsPromises } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import * as readline from 'node:readline'
import { promisify } from 'node:util'

import type { Collection } from '@transifex/api'
import { transifexApi } from '@transifex/api'
import axios from 'axios'

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
})

// eslint-disable-next-line @typescript-eslint/unbound-method
const question = promisify(rl.question).bind(rl)

const organizationSlug = 'foray1010'
const projectSlug = 'popup-my-bookmarks'
const resourceSlug = 'messagesjson-1'

const localesPath = path.join('src', 'core', '_locales')

async function main(): Promise<void> {
  // @ts-expect-error somehow promisify does not work correctly with readline.question
  const transifexApiKey: string = await question(
    'transifex api key (get from https://www.transifex.com/user/settings/api/): ',
  )
  if (!transifexApiKey) throw new Error('transifexApiKey is required')

  transifexApi.setup({
    host: undefined, // use default host
    auth: transifexApiKey,
  })

  const organization = await transifexApi.Organization.get({
    slug: organizationSlug,
  })

  const project = await transifexApi.Project.get({
    organization,
    slug: projectSlug,
  })

  const resource = await transifexApi.Resource.get({
    project,
    slug: resourceSlug,
  })

  const languages = (await project.fetch('languages', false)) as Collection & {
    data: ReadonlyArray<{
      readonly attributes: {
        readonly code: string
      }
    }>
  }
  await languages.fetch()

  await Promise.all(
    languages.data.map(async (language) => {
      let mappedLanguage: string
      switch (language.attributes.code) {
        case 'nb_NO':
          mappedLanguage = 'nb'
          break

        case 'es_ES':
          mappedLanguage = 'es'
          break

        default:
          mappedLanguage = language.attributes.code
      }

      console.log(`processing "${mappedLanguage}"...`)

      // @ts-expect-error missing this type
      const url = await transifexApi.ResourceTranslationsAsyncDownload.download(
        {
          resource,
          language,
          mode: 'onlytranslated',
        },
      )
      const { data: messagesJson } = await axios.get<
        Record<
          string,
          {
            readonly message: string
            readonly description?: string
          }
        >
      >(url)

      const sortedMessagesJson = Object.fromEntries(
        Object.entries(messagesJson)
          .map(([k, v]) => {
            const trimmedMessage = v.message.trim()
            if (!trimmedMessage) return undefined

            return [k, { ...v, message: trimmedMessage }] as const
          })
          .filter(<T>(x: T | undefined): x is T => x !== undefined)
          .sort(([a], [b]) => a.localeCompare(b)),
      )

      await fsPromises.mkdir(path.join(localesPath, mappedLanguage), {
        recursive: true,
      })

      await fsPromises.writeFile(
        path.join(localesPath, mappedLanguage, 'messages.json'),
        JSON.stringify(sortedMessagesJson, null, 2) + '\n',
      )

      console.log(`"${mappedLanguage}" is generated`)
    }),
  )
}

main()
  .then(() => {
    rl.close()
  })
  .catch((err: Error) => {
    console.error(err)
    process.exit(1)
  })


text:
package com.facebook.buck.rules;

/**
 * Marker interface for java objects that acts as arguments to {@link ConstructorArgMarshaller}.
 *
 * The constructor arg is examined for public fields. Reflection is used to determine the type of
 * the field, and it's possible to indicate that a field isn't mandatory by using
 * {@link com.google.common.base.Optional} declarations. If the name of the property to be exposed
 * to a build file does not match the field name, then a {@link Hint} can be used to set it.
 *
 * As an example, the arguments for a build target defined as:
 *

 *    example_library(
 *      name = 'example',
 *      srcs = [ '//foo:bar', 'Eggs.java', ],
 *      optional_thing = True,
 *    )
 *

 * Could be defined as a constructor arg that looks like:
 *

 *     public class ExampleLibraryArg {
 *       public String name;
 *       public ImmutableSortedSet>SourcePath> srcs;
 *       {@literal @}Hint(name = "optional_thing")
 *       public Optional>Boolean> isNeeded;
 *     }
 *

 *
 * Values for individual fields are coerced from the java object representations of the json
 * generated by the python build rules by instances of
 * {@link com.facebook.buck.rules.coercer.TypeCoercer}.
 *
 * See {@link com.facebook.buck.rules.coercer.TypeCoercerFactory} supported types, and how the type
 * coercer is picked given an input type.
 */
public interface ConstructorArg {
}


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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                               android:layout_width="match_parent"
                               android:layout_height="match_parent">

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/logoImage"
            android:src="@drawable/logo"
            android:scaleType="centerCrop"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:contentDescription="@string/act_disconnected_logo"/>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/act_disconnected_waiting_for_network"
            android:id="@+id/textView"
            android:layout_marginTop="45dp"
            android:layout_below="@+id/logoImage"
            android:layout_centerHorizontal="true"/>
    <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"
            android:layout_below="@+id/logoImage"
            android:layout_centerHorizontal="true"/>
</RelativeLayout>


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="resource.images.skinicons.wide" name="Skin Icons - Wide" version="1.0.3" provider-name="marcelveldt">
	<extension point="kodi.resource.images" compile="false" type="skinicons" />
	<requires>
		<import addon="kodi.resource" version="1.0.0"/>
	</requires>
	<extension point="xbmc.addon.metadata">
		<summary lang="en">Skin Icons Pack - Wide</summary>
		<description lang="en">Skin Icons Pack - Wide</description>
		<platform>all</platform>
	</extension>
</addon>


text:
package apple.addressbook.enums;

import org.moe.natj.general.ann.Generated;

/**
 * Images
 */
@Generated
public final class ABPersonImageFormat {
    /**
     * deprecated
     */
    @Generated public static final int kABPersonImageFormatThumbnail = 0x00000000;
    /**
     * deprecated
     */
    @Generated public static final int kABPersonImageFormatOriginalSize = 0x00000002;

    @Generated
    private ABPersonImageFormat() {
    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DependencyResolver.Model
{
    [Table("Teachers")]
    public class Teacher : Person
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public virtual int Id { get; set; }
        public virtual Decimal Salary { get; set; }
    }
}


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

package snapshot_test

import (
	"context"
	"fmt"
	"math/rand"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"go.etcd.io/etcd/client/pkg/v3/testutil"
	"go.etcd.io/etcd/client/v3"
	"go.etcd.io/etcd/etcdutl/v3/snapshot"
	"go.etcd.io/etcd/server/v3/embed"
	"go.etcd.io/etcd/tests/v3/integration"
	"go.uber.org/zap/zapcore"
	"go.uber.org/zap/zaptest"
)

// TestSnapshotV3RestoreSingle tests single node cluster restoring
// from a snapshot file.
func TestSnapshotV3RestoreSingle(t *testing.T) {
	integration.BeforeTest(t)
	kvs := []kv{{"foo1", "bar1"}, {"foo2", "bar2"}, {"foo3", "bar3"}}
	dbPath := createSnapshotFile(t, kvs)

	clusterN := 1
	urls := newEmbedURLs(clusterN * 2)
	cURLs, pURLs := urls[:clusterN], urls[clusterN:]

	cfg := integration.NewEmbedConfig(t, "s1")
	cfg.InitialClusterToken = testClusterTkn
	cfg.ClusterState = "existing"
	cfg.LCUrls, cfg.ACUrls = cURLs, cURLs
	cfg.LPUrls, cfg.APUrls = pURLs, pURLs
	cfg.InitialCluster = fmt.Sprintf("%s=%s", cfg.Name, pURLs[0].String())

	sp := snapshot.NewV3(zaptest.NewLogger(t))
	pss := make([]string, 0, len(pURLs))
	for _, p := range pURLs {
		pss = append(pss, p.String())
	}
	if err := sp.Restore(snapshot.RestoreConfig{
		SnapshotPath:        dbPath,
		Name:                cfg.Name,
		OutputDataDir:       cfg.Dir,
		InitialCluster:      cfg.InitialCluster,
		InitialClusterToken: cfg.InitialClusterToken,
		PeerURLs:            pss,
	}); err != nil {
		t.Fatal(err)
	}

	srv, err := embed.StartEtcd(cfg)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		srv.Close()
	}()
	select {
	case <-srv.Server.ReadyNotify():
	case <-time.After(3 * time.Second):
		t.Fatalf("failed to start restored etcd member")
	}

	var cli *clientv3.Client
	cli, err = integration.NewClient(t, clientv3.Config{Endpoints: []string{cfg.ACUrls[0].String()}})
	if err != nil {
		t.Fatal(err)
	}
	defer cli.Close()
	for i := range kvs {
		var gresp *clientv3.GetResponse
		gresp, err = cli.Get(context.Background(), kvs[i].k)
		if err != nil {
			t.Fatal(err)
		}
		if string(gresp.Kvs[0].Value) != kvs[i].v {
			t.Fatalf("#%d: value expected %s, got %s", i, kvs[i].v, string(gresp.Kvs[0].Value))
		}
	}
}

// TestSnapshotV3RestoreMulti ensures that multiple members
// can boot into the same cluster after being restored from a same
// snapshot file.
func TestSnapshotV3RestoreMulti(t *testing.T) {
	integration.BeforeTest(t)
	kvs := []kv{{"foo1", "bar1"}, {"foo2", "bar2"}, {"foo3", "bar3"}}
	dbPath := createSnapshotFile(t, kvs)

	clusterN := 3
	cURLs, _, srvs := restoreCluster(t, clusterN, dbPath)
	defer func() {
		for i := 0; i < clusterN; i++ {
			srvs[i].Close()
		}
	}()

	// wait for leader election
	time.Sleep(time.Second)

	for i := 0; i < clusterN; i++ {
		cli, err := integration.NewClient(t, clientv3.Config{Endpoints: []string{cURLs[i].String()}})
		if err != nil {
			t.Fatal(err)
		}
		defer cli.Close()
		for i := range kvs {
			var gresp *clientv3.GetResponse
			gresp, err = cli.Get(context.Background(), kvs[i].k)
			if err != nil {
				t.Fatal(err)
			}
			if string(gresp.Kvs[0].Value) != kvs[i].v {
				t.Fatalf("#%d: value expected %s, got %s", i, kvs[i].v, string(gresp.Kvs[0].Value))
			}
		}
	}
}

// TestCorruptedBackupFileCheck tests if we can correctly identify a corrupted backup file.
func TestCorruptedBackupFileCheck(t *testing.T) {
	dbPath := integration.MustAbsPath("testdata/corrupted_backup.db")
	integration.BeforeTest(t)
	if _, err := os.Stat(dbPath); err != nil {
		t.Fatalf("test file [%s] does not exist: %v", dbPath, err)
	}

	sp := snapshot.NewV3(zaptest.NewLogger(t))
	_, err := sp.Status(dbPath)
	expectedErrKeywords := "snapshot file integrity check failed"
	/* example error message:
	snapshot file integrity check failed. 2 errors found.
	page 3: already freed
	page 4: unreachable unfreed
	*/
	if err == nil {
		t.Error("expected error due to corrupted snapshot file, got no error")
	}
	if !strings.Contains(err.Error(), expectedErrKeywords) {
		t.Errorf("expected error message to contain the following keywords:\n%s\n"+
			"actual error message:\n%s",
			expectedErrKeywords, err.Error())
	}
}

type kv struct {
	k, v string
}

// creates a snapshot file and returns the file path.
func createSnapshotFile(t *testing.T, kvs []kv) string {
	testutil.SkipTestIfShortMode(t,
		"Snapshot creation tests are depending on embedded etcServer so are integration-level tests.")
	clusterN := 1
	urls := newEmbedURLs(clusterN * 2)
	cURLs, pURLs := urls[:clusterN], urls[clusterN:]

	cfg := integration.NewEmbedConfig(t, "default")
	cfg.ClusterState = "new"
	cfg.LCUrls, cfg.ACUrls = cURLs, cURLs
	cfg.LPUrls, cfg.APUrls = pURLs, pURLs
	cfg.InitialCluster = fmt.Sprintf("%s=%s", cfg.Name, pURLs[0].String())
	srv, err := embed.StartEtcd(cfg)
	if err != nil {
		t.Fatal(err)
	}
	defer func() {
		srv.Close()
	}()
	select {
	case <-srv.Server.ReadyNotify():
	case <-time.After(3 * time.Second):
		t.Fatalf("failed to start embed.Etcd for creating snapshots")
	}

	ccfg := clientv3.Config{Endpoints: []string{cfg.ACUrls[0].String()}}
	cli, err := integration.NewClient(t, ccfg)
	if err != nil {
		t.Fatal(err)
	}
	defer cli.Close()
	for i := range kvs {
		ctx, cancel := context.WithTimeout(context.Background(), testutil.RequestTimeout)
		_, err = cli.Put(ctx, kvs[i].k, kvs[i].v)
		cancel()
		if err != nil {
			t.Fatal(err)
		}
	}

	sp := snapshot.NewV3(zaptest.NewLogger(t))
	dpPath := filepath.Join(t.TempDir(), fmt.Sprintf("snapshot%d.db", time.Now().Nanosecond()))
	_, err = sp.Save(context.Background(), ccfg, dpPath)
	if err != nil {
		t.Fatal(err)
	}
	return dpPath
}

const testClusterTkn = "tkn"

func restoreCluster(t *testing.T, clusterN int, dbPath string) (
	cURLs []url.URL,
	pURLs []url.URL,
	srvs []*embed.Etcd) {
	urls := newEmbedURLs(clusterN * 2)
	cURLs, pURLs = urls[:clusterN], urls[clusterN:]

	ics := ""
	for i := 0; i < clusterN; i++ {
		ics += fmt.Sprintf(",m%d=%s", i, pURLs[i].String())
	}
	ics = ics[1:]

	cfgs := make([]*embed.Config, clusterN)
	for i := 0; i < clusterN; i++ {
		cfg := integration.NewEmbedConfig(t, fmt.Sprintf("m%d", i))
		cfg.InitialClusterToken = testClusterTkn
		cfg.ClusterState = "existing"
		cfg.LCUrls, cfg.ACUrls = []url.URL{cURLs[i]}, []url.URL{cURLs[i]}
		cfg.LPUrls, cfg.APUrls = []url.URL{pURLs[i]}, []url.URL{pURLs[i]}
		cfg.InitialCluster = ics

		sp := snapshot.NewV3(
			zaptest.NewLogger(t, zaptest.Level(zapcore.InfoLevel)).Named(cfg.Name).Named("sm"))

		if err := sp.Restore(snapshot.RestoreConfig{
			SnapshotPath:        dbPath,
			Name:                cfg.Name,
			OutputDataDir:       cfg.Dir,
			PeerURLs:            []string{pURLs[i].String()},
			InitialCluster:      ics,
			InitialClusterToken: cfg.InitialClusterToken,
		}); err != nil {
			t.Fatal(err)
		}

		cfgs[i] = cfg
	}

	sch := make(chan *embed.Etcd, len(cfgs))
	for i := range cfgs {
		go func(idx int) {
			srv, err := embed.StartEtcd(cfgs[idx])
			if err != nil {
				t.Error(err)
			}

			<-srv.Server.ReadyNotify()
			sch <- srv
		}(i)
	}

	srvs = make([]*embed.Etcd, clusterN)
	for i := 0; i < clusterN; i++ {
		select {
		case srv := <-sch:
			srvs[i] = srv
		case <-time.After(5 * time.Second):
			t.Fatalf("#%d: failed to start embed.Etcd", i)
		}
	}
	return cURLs, pURLs, srvs
}

// TODO: TLS
func newEmbedURLs(n int) (urls []url.URL) {
	urls = make([]url.URL, n)
	for i := 0; i < n; i++ {
		rand.Seed(int64(time.Now().Nanosecond()))
		u, _ := url.Parse(fmt.Sprintf("unix://localhost:%d", rand.Intn(45000)))
		urls[i] = *u
	}
	return urls
}


text:
import lookupHelper, { findHelper } from 'ember-htmlbars/system/lookup-helper';
import ComponentLookup from 'ember-views/component_lookup';
import Registry from 'container/registry';
import Helper, { helper as makeHelper } from 'ember-htmlbars/helper';
import HandlebarsCompatibleHelper from 'ember-htmlbars/compat/helper';

function generateEnv(helpers, container) {
  return {
    container: container,
    helpers: (helpers ? helpers : {}),
    hooks: { keywords: {} },
    knownHelpers: {}
  };
}

function generateContainer() {
  var registry = new Registry();
  var container = registry.container();

  registry.register('component-lookup:main', ComponentLookup);

  return container;
}

QUnit.module('ember-htmlbars: lookupHelper hook');

QUnit.test('looks for helpers in the provided `env.helpers`', function() {
  var env = generateEnv({
    'flubarb'() { }
  });

  var actual = lookupHelper('flubarb', null, env);

  equal(actual, env.helpers.flubarb, 'helpers are looked up on env');
});

QUnit.test('returns undefined if no container exists (and helper is not found in env)', function() {
  var env = generateEnv();
  var view = {};

  var actual = findHelper('flubarb', view, env);

  equal(actual, undefined, 'does not blow up if view does not have a container');
});

QUnit.test('does not lookup in the container if the name does not contain a dash (and helper is not found in env)', function() {
  var env = generateEnv();
  var view = {
    container: {
      lookup() {
        ok(false, 'should not lookup in the container');
      }
    }
  };

  var actual = findHelper('flubarb', view, env);

  equal(actual, undefined, 'does not blow up if view does not have a container');
});

QUnit.test('does a lookup in the container if the name contains a dash (and helper is not found in env)', function() {
  var container = generateContainer();
  var env = generateEnv(null, container);
  var view = {
    container: container
  };

  var someName = Helper.extend();
  view.container._registry.register('helper:some-name', someName);

  var actual = lookupHelper('some-name', view, env);

  ok(someName.detect(actual), 'helper is an instance of the helper class');
});

QUnit.test('does a lookup in the container if the name is found in knownHelpers', function() {
  var container = generateContainer();
  var env = generateEnv(null, container);
  var view = {
    container: container
  };

  env.knownHelpers['t'] = true;
  var t = Helper.extend();
  view.container._registry.register('helper:t', t);

  var actual = lookupHelper('t', view, env);

  ok(t.detect(actual), 'helper is an instance of the helper class');
});

QUnit.test('looks up a shorthand helper in the container', function() {
  expect(2);
  var container = generateContainer();
  var env = generateEnv(null, container);
  var view = {
    container: container
  };
  var called;

  function someName() {
    called = true;
  }
  view.container._registry.register('helper:some-name', makeHelper(someName));

  var actual = lookupHelper('some-name', view, env);

  ok(actual.isHelperInstance, 'is a helper');

  actual.compute([], {});

  ok(called, 'HTMLBars compatible wrapper is wraping the provided function');
});

QUnit.test('fails with a useful error when resolving a function', function() {
  expect(2);
  var container = generateContainer();
  var env = generateEnv(null, container);
  var view = {
    container: container
  };

  function someName() {}
  view.container._registry.register('helper:some-name', someName);

  var actual;
  expectDeprecation(function() {
    actual = lookupHelper('some-name', view, env);
  }, /helper "some-name" is a deprecated bare function helper/);
  ok(actual instanceof HandlebarsCompatibleHelper, 'function looks up as compat helper');
});


text:
/*
 */
package com.moosylvania.twitterstreampuller;

import com.google.common.base.Joiner;
import com.twitter.hbc.core.Constants;
import com.twitter.hbc.core.HttpConstants;
import com.twitter.hbc.core.endpoint.DefaultStreamingEndpoint;
import com.twitter.hbc.core.endpoint.Location;
import java.util.List;

/**
 *
 * Twitter Endpoint - implements the Endpoint that twitter HBC posts to.
 */
public class TwitterEndpoint extends DefaultStreamingEndpoint {

    public static final String PATH = "/statuses/filter.json";

    public TwitterEndpoint() {
        this(false);
    }

    /**
     * @param backfillable set to true if you have elevated access
     */
    public TwitterEndpoint(boolean backfillable) {
        super(PATH, HttpConstants.HTTP_POST, backfillable);
    }

    public TwitterEndpoint followings(List<Long> userIds) {
        addPostParameter(Constants.FOLLOW_PARAM, Joiner.on(',').join(userIds));
        return this;
    }

    /**
     * @param terms a list of Strings to track. These strings should NOT be
     * url-encoded.
     */
    public TwitterEndpoint trackTerms(List<String> terms) {
        addPostParameter(Constants.TRACK_PARAM, Joiner.on(',').join(terms));
        return this;
    }

    public TwitterEndpoint locations(List<Location> locations) {
        addPostParameter(Constants.LOCATION_PARAM, Joiner.on(',').join(locations));
        return this;
    }
}


text:
package org.kuali.kra.authorizer;

import org.kuali.kra.authorization.Task;
import org.kuali.kra.authorization.TaskAuthorizerImpl;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.PermissionConstants;

public class CreateSubAwardAuthorizer extends TaskAuthorizerImpl{

    @Override
    public boolean isAuthorized(String userId, Task task) {
        return hasUnitPermission(userId, Constants.MODULE_NAMESPACE_SUBAWARD, PermissionConstants.CREATE_SUBAWARD);
    }

}