text:
package envoy_type_v3

import (
	"bytes"
	"errors"
	"fmt"
	"net"
	"net/mail"
	"net/url"
	"regexp"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/golang/protobuf/ptypes"
)

// ensure the imports are used
var (
	_ = bytes.MinRead
	_ = errors.New("")
	_ = fmt.Print
	_ = utf8.UTFMax
	_ = (*regexp.Regexp)(nil)
	_ = (*strings.Reader)(nil)
	_ = net.IPv4len
	_ = time.Duration(0)
	_ = (*url.URL)(nil)
	_ = (*mail.Address)(nil)
	_ = ptypes.DynamicAny{}
)

// Validate checks the field values on Percent with the rules defined in the
// proto definition for this message. If any rules are violated, an error is returned.
func (m *Percent) Validate() error {
	if m == nil {
		return nil
	}

	if val := m.GetValue(); val < 0 || val > 100 {
		return PercentValidationError{
			field:  "Value",
			reason: "value must be inside range [0, 100]",
		}
	}

	return nil
}

// PercentValidationError is the validation error returned by Percent.Validate
// if the designated constraints aren't met.
type PercentValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e PercentValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e PercentValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e PercentValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e PercentValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e PercentValidationError) ErrorName() string { return "PercentValidationError" }

// Error satisfies the builtin error interface
func (e PercentValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sPercent.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = PercentValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = PercentValidationError{}

// Validate checks the field values on FractionalPercent with the rules defined
// in the proto definition for this message. If any rules are violated, an
// error is returned.
func (m *FractionalPercent) Validate() error {
	if m == nil {
		return nil
	}

	// no validation rules for Numerator

	if _, ok := FractionalPercent_DenominatorType_name[int32(m.GetDenominator())]; !ok {
		return FractionalPercentValidationError{
			field:  "Denominator",
			reason: "value must be one of the defined enum values",
		}
	}

	return nil
}

// FractionalPercentValidationError is the validation error returned by
// FractionalPercent.Validate if the designated constraints aren't met.
type FractionalPercentValidationError struct {
	field  string
	reason string
	cause  error
	key    bool
}

// Field function returns field value.
func (e FractionalPercentValidationError) Field() string { return e.field }

// Reason function returns reason value.
func (e FractionalPercentValidationError) Reason() string { return e.reason }

// Cause function returns cause value.
func (e FractionalPercentValidationError) Cause() error { return e.cause }

// Key function returns key value.
func (e FractionalPercentValidationError) Key() bool { return e.key }

// ErrorName returns error name.
func (e FractionalPercentValidationError) ErrorName() string {
	return "FractionalPercentValidationError"
}

// Error satisfies the builtin error interface
func (e FractionalPercentValidationError) Error() string {
	cause := ""
	if e.cause != nil {
		cause = fmt.Sprintf(" | caused by: %v", e.cause)
	}

	key := ""
	if e.key {
		key = "key for "
	}

	return fmt.Sprintf(
		"invalid %sFractionalPercent.%s: %s%s",
		key,
		e.field,
		e.reason,
		cause)
}

var _ error = FractionalPercentValidationError{}

var _ interface {
	Field() string
	Reason() string
	Key() bool
	Cause() error
	ErrorName() string
} = FractionalPercentValidationError{}


text:
using Newtonsoft.Json;

namespace anime_downloader.Models.AniList
{
    public class StartDate
    {
        [JsonProperty("year")]
        public int? Year { get; set; }

        [JsonProperty("month")]
        public int? Month { get; set; }

        [JsonProperty("day")]
        public int? Day { get; set; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package nl.rivm.cib.episim.geard;

import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.function.Consumer;

import javax.inject.Singleton;

import io.coala.name.Id;
import io.coala.name.Identified;
import io.coala.rx.RxCollection;
import io.coala.time.Proactive;
import io.coala.time.Scheduler;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

/**
 * {@link Population} provides macro-level characteristics, following common
 * epidemic models
 * and approaches for
 * mathematical modeling of infectious disease, e.g. by
 * Geard et al. (2013)
 *
 *

 *

 * μ
 * Average death rate
 *

 *

 * B
 * Average birth rate
 *

 *

 *
 * @version $Id$
 * @author Rick van Krevelen
 */
@Deprecated
@Singleton
public interface Population<T extends Participant>
	extends Proactive, Identified<Population.ID>
{

	class ID extends Id.Ordinal<String>
	{
		public static ID of( final String value )
		{
			return Util.of( value, new ID() );
		}
	}

	RxCollection<T> members();

	Observable<DemographicEvent<T>> events();

	@SuppressWarnings( "rawtypes" )
	default <E extends DemographicEvent> Observable<E>
		on( final Class<E> eventType )
	{
		return events().ofType( eventType );
	}

	@SuppressWarnings( "rawtypes" )
	default <E extends DemographicEvent> Disposable
		on( final Class<E> eventType, final Consumer<E> consumer )
	{
		return on( eventType ).subscribe( event ->
		{
			consumer.accept( event );
		}, error ->
		{
		} );
	}

	void emit( final DemographicEvent<T> event );

	@SuppressWarnings( "unchecked" )
	default void birth( final T newborn )
	{
		Objects.requireNonNull( newborn );
		emit( DemographicEvent.Builder.of( Birth.class, now() )
				.withArrivals( Collections.singleton( newborn ) ).build() );
	}

	@SuppressWarnings( "unchecked" )
	default void death( final T diseased )
	{
		Objects.requireNonNull( diseased );
		members().remove( diseased );
		emit( DemographicEvent.Builder.of( Death.class, now() )
				.withDepartures( Collections.singleton( diseased ) ).build() );
	}

	@SuppressWarnings( "unchecked" )
	default void immigrate( final Collection<T> immigrants )
	{
		Objects.requireNonNull( immigrants );
		if( immigrants.isEmpty() ) throw new IllegalArgumentException();
		emit( DemographicEvent.Builder.of( Immigration.class, now() )
				.withArrivals( immigrants ).build() );
	}

	@SuppressWarnings( "unchecked" )
	default void emigrate( final Collection<T> emigrants )
	{
		Objects.requireNonNull( emigrants );
		if( emigrants.isEmpty() ) throw new IllegalArgumentException();
		emit( DemographicEvent.Builder.of( Emigration.class, now() )
				.withDepartures( emigrants ).build() );
	}

//	interface Factory
//	{
//		Population<?> create( String name );
//	}

	static <T extends Participant> Population<T> of( final String name,
		final RxCollection<T> members, final Scheduler scheduler )
	{
		return new Population<T>()
		{
			private final ID id = ID.of( name );

			private final Subject<DemographicEvent<T>> events = PublishSubject
					.create();

			@Override
			public Scheduler scheduler()
			{
				return scheduler;
			}

			@Override
			public RxCollection<T> members()
			{
				return members;
			}

			@Override
			public ID id()
			{
				return this.id;
			}

			@Override
			public Observable<DemographicEvent<T>> events()
			{
				return this.events;
			}

			@Override
			public void emit( final DemographicEvent<T> event )
			{
				at( now() ).call( () -> this.events.onNext( event ) );
			}
		};
	}

	public static class Birth<T extends Participant> extends DemographicEvent<T>
	{
	}

	public static class Death<T extends Participant> extends DemographicEvent<T>
	{
	}

	public static class Immigration<T extends Participant>
		extends DemographicEvent<T>
	{
	}

	public static class Emigration<T extends Participant>
		extends DemographicEvent<T>
	{
	}
}


text:
package org.apache.phoenix.job;

import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *
 * An bounded blocking queue implementation that keeps a virtual queue of elements on per-producer
 * basis and iterates through each producer queue in round robin fashion.
 *
 */
public abstract class AbstractRoundRobinQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>{

    /**
     * Construct an AbstractBlockingRoundRobinQueue that limits the size of the queued elements
     * to at most maxSize. Attempts to insert new elements after that point will cause the
     * caller to block.
     * @param maxSize
     */
    public AbstractRoundRobinQueue(int maxSize) {
        this(maxSize, false);
    }
    /**
     * @param newProducerToFront If true, new producers go to the front of the round-robin list, if false, they go to the end.
     */
    public AbstractRoundRobinQueue(int maxSize, boolean newProducerToFront) {
        this.producerMap = new HashMap<Object,ProducerList<E>>();
        this.producerLists = new LinkedList<ProducerList<E>>();
        this.lock = new Object();
        this.newProducerToFront = newProducerToFront;
        this.maxSize = maxSize;
    }

    @Override
    public Iterator<E> iterator() {
        synchronized(lock) {
            ArrayList<E> allElements = new ArrayList<E>(this.size);
            ListIterator<ProducerList<E>> iter = this.producerLists.listIterator(this.currentProducer);
            while(iter.hasNext()) {
                ProducerList<E> tList = iter.next();
                allElements.addAll(tList.list);
            }
            return allElements.iterator();
        }
    }

    @Override
    public boolean offer(E o, long timeout, TimeUnit unit) throws InterruptedException {
        boolean taken = false;
        long endAt = System.currentTimeMillis() + unit.toMillis(timeout);
        synchronized(lock) {
            long waitTime = endAt - System.currentTimeMillis();
            while (!(taken = offer(o)) && waitTime > 0) {
                this.lock.wait(waitTime);
                waitTime = endAt - System.currentTimeMillis();
            }
        }
        return taken;
    }

    @Override
    public boolean offer(E o) {
        if (o == null)
            throw new NullPointerException();

        final Object producerKey = extractProducer(o);

        ProducerList<E> producerList = null;
        synchronized(lock) {
            if (this.size == this.maxSize) {
                return false;
            }
            producerList = this.producerMap.get(producerKey);
            if (producerList == null) {
                producerList = new ProducerList<E>(producerKey);
                this.producerMap.put(producerKey, producerList);
                this.producerLists.add(this.currentProducer, producerList);
                if (!this.newProducerToFront) {
                    incrementCurrentProducerPointer();
                }
            }
            producerList.list.add(o);
            this.size++;
            lock.notifyAll();
        }
        return true;
    }

    /**
     * Implementations must extracts the producer object which is used as the key to identify a unique producer.
     */
    protected abstract Object extractProducer(E o);

    @Override
    public void put(E o) {
        offer(o);
    }

    @Override
    public E take() throws InterruptedException {
        synchronized(lock) {
            while (this.size == 0) {
                this.lock.wait();
            }
            E element = poll();
            assert element != null;
            return element;
        }
    }

    @Override
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long endAt = System.currentTimeMillis() + unit.toMillis(timeout);
        synchronized(lock) {
            long waitTime = endAt - System.currentTimeMillis();
            while (this.size == 0 && waitTime > 0) {
                this.lock.wait(waitTime);
                waitTime = endAt - System.currentTimeMillis();
            }
            return poll();
        }
    }

    @Override
    public E poll() {
        synchronized(lock) {
            ListIterator<ProducerList<E>> iter = this.producerLists.listIterator(this.currentProducer);
            while (iter.hasNext()) {
                ProducerList<E> tList = iter.next();
                if (tList.list.isEmpty()) {
                    iter.remove();
                    this.producerMap.remove(tList.producer);
                    adjustCurrentProducerPointer();
                } else {
                    E element = tList.list.removeFirst();
                    this.size--;
                    assert element != null;
                    // This is the round robin part. When we take an element from the current thread's queue
                    // we move on to the next thread.
                    if (tList.list.isEmpty()) {
                        iter.remove();
                        this.producerMap.remove(tList.producer);
                        adjustCurrentProducerPointer();
                    } else {
                        incrementCurrentProducerPointer();
                    }
                    lock.notifyAll();
                    return element;
                }
            }
            assert this.size == 0;
        }
        return null;
    }

    /**
     * Polls using the given producer key.
     */
    protected E pollProducer(Object producer) {
        synchronized(lock) {
            ProducerList<E> tList = this.producerMap.get(producer);
            if (tList != null && !tList.list.isEmpty()) {
                E element = tList.list.removeFirst();
                this.size--;
                if (tList.list.isEmpty()) {
                    this.producerLists.remove(tList);
                    this.producerMap.remove(tList.producer);
                    // we need to adjust the current thread pointer in case it pointed to this thread list, which is now removed
                    adjustCurrentProducerPointer();
                }
                lock.notifyAll();
                assert element != null;
                // Since this is only processing the current thread's work, we'll leave the
                // round-robin part alone and just return the work
                return element;
            }
        }
        return null;
    }

    @Override
    public E peek() {
        synchronized(lock) {
            ListIterator<ProducerList<E>> iter = this.producerLists.listIterator(this.currentProducer);
            while (iter.hasNext()) {
                ProducerList<E> tList = iter.next();
                if (tList.list.isEmpty()) {
                    iter.remove();
                    this.producerMap.remove(tList.producer);
                    adjustCurrentProducerPointer();
                } else {
                    E element = tList.list.getFirst();
                    assert element != null;
                    return element;
                }
            }
            assert this.size == 0;
        }
        return null;
    }

    @Override
    public int drainTo(Collection<? super E> c) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();

        synchronized(this.lock) {
            int originalSize = this.size;
            int drained = drainTo(c, this.size);
            assert drained == originalSize;
            assert this.size == 0;
            assert this.producerLists.isEmpty();
            assert this.producerMap.isEmpty();
            return drained;
        }
    }

    @Override
    public int drainTo(Collection<? super E> c, int maxElements) {
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();

        synchronized(this.lock) {
            int i = 0;
            while(i < maxElements) {
                E element = poll();
                if (element != null) {
                    c.add(element);
                    i++;
                } else {
                    break;
                }
            }
            return i;
        }
    }

    @Override
    public int remainingCapacity() {
        return Integer.MAX_VALUE;
    }

    @Override
    public int size() {
        synchronized(this.lock) {
            return this.size;
        }
    }

    private void incrementCurrentProducerPointer() {
        synchronized(lock) {
            if (this.producerLists.size() == 0) {
                this.currentProducer = 0;
            } else {
                this.currentProducer = (this.currentProducer+1)%this.producerLists.size();
            }
        }
    }

    /**
     * Adjusts the current pointer to a decrease in size.
     */
    private void adjustCurrentProducerPointer() {
        synchronized(lock) {
            if (this.producerLists.size() == 0) {
                this.currentProducer = 0;
            } else {
                this.currentProducer = (this.currentProducer)%this.producerLists.size();
            }
        }
    }

    private static class ProducerList<E> {
        public ProducerList(Object producer) {
            this.producer = producer;
            this.list = new LinkedList<E>();
        }
        private final Object producer;
        private final LinkedList<E> list;
    }

    private final Map<Object,ProducerList<E>> producerMap;
    private final LinkedList<ProducerList<E>> producerLists;
    private final Object lock;
    private final boolean newProducerToFront;
    private int currentProducer;
    private int size;
    private int maxSize;
}


text:
declare module 'bl' {
	import stream = require('stream');

	class BufferList  extends stream.Duplex {
		new (callback?:(err:Error, buffer:Buffer) => void): void;

		append(buffer: Buffer):void;
		get(index: number): number;
		slice(start?: number, end?: number): Buffer;
		copy(dest: Buffer, destStart?: number, srcStart?: number, srcEnd?: number): void;
		duplicate(): BufferList;
		consume(bytes?: number): void;
		toString(encoding?: string, start?: number, end?: number): string;
		length: number;

		readDoubleBE(offset: number, noAssert?: boolean): Buffer;
		readDoubleLE(offset: number, noAssert?: boolean): Buffer;
		readFloatBE(offset: number, noAssert?: boolean): Buffer;
		readFloatLE(offset: number, noAssert?: boolean): Buffer;
		readInt32BE(offset: number, noAssert?: boolean): Buffer;
		readInt32LE(offset: number, noAssert?: boolean): Buffer;
		readUInt32BE(offset: number, noAssert?: boolean): Buffer;
		readUInt32LE(offset: number, noAssert?: boolean): Buffer;
		readInt16BE(offset: number, noAssert?: boolean): Buffer;
		readInt16LE(offset: number, noAssert?: boolean): Buffer;
		readUInt16BE(offset: number, noAssert?: boolean): Buffer;
		readUInt16LE(offset: number, noAssert?: boolean): Buffer;
		readInt8(offset: number, noAssert?: boolean): Buffer;
		readUInt8(offset: number, noAssert?: boolean): Buffer;
	}

	export = BufferList;
}


text:
package com.ds.server;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.util.regex.Pattern;

public class ServerUtility {

	public static final String GET = "get";
	public static final String PUT = "put";
	public static final String LS = "ls";
	public static final String MKDIR = "mkdir";
	public static final String CD = "cd";
	public static final String PWD = "pwd";
	public static final String DELETE = "delete";
	public static final String QUIT = "quit";
	public static final String TERMINATE = "terminate";
	public final String ROOT = "user.dir";

	String currentDirectory = null;
	public static int cmdID = 123;

	public static ServerManager serverManager = new ServerManager();

	public ServerUtility(){
		this.currentDirectory = executePWD();
	}
	public String defaultMsg() {
		// TODO Auto-generated method stub
		return "Invalid FTP command. Please enter correct command";
	}

	public String executeLS() {
		// TODO Auto-generated method stub
		//ArrayList<String> fileNames = new ArrayList<String>();
		StringBuilder directoryList = new StringBuilder();

		try{

			File files = new File(currentDirectory);
			File[] fList = files.listFiles();
			for (File f: fList)
				directoryList.append(f.getName()+"\t");
				//fileNames.add(f.getName());

		}catch(Exception e){
			System.out.println("----Exception in LS command execution -----"+e.getMessage());
		}
		return directoryList.toString();
	}

	public String executePWD() {
		// TODO Auto-generated method stub

		try{
			if(currentDirectory==null)
				currentDirectory = myftpserver.serverRootDirectory;
		}catch(Exception e){
			System.out.println("----Exception in PWD command execution -----"+e.getMessage());
		}
		return currentDirectory;
	}

	public String executeCD(String dirPath) {
		// TODO Auto-generated method stub
		String retStatus = null;
		File curr = null;
		try{

			if(dirPath.equals("..")){
				if(currentDirectory!=null)
					curr = new File(currentDirectory);
				else
					curr = new File(executePWD());
				if(curr.getAbsoluteFile().getParent() != null) {
					System.setProperty(ROOT, curr.getAbsoluteFile().getParent());
					currentDirectory = curr.getAbsoluteFile().getParent();
				}
				else
					System.out.println("::: Reached root directory :::" + ROOT);
				retStatus = "Directory changed successfully";
			}else{
				File current = new File(executePWD() + File.separator +dirPath); //made change
				System.out.println("Inside CD ::" + current.getAbsolutePath());
				if(current.exists() && current.isDirectory()){
					//System.setProperty(ROOT, current.getAbsoluteFile().getPath());
					currentDirectory = current.getAbsoluteFile().getPath();
					retStatus = ":::: Directory changed successfully ::::";
				}
				else
					retStatus = "Directory does not exist. Enter correct directory name and try again.";
			}

		}catch(Exception e){
			System.out.println("----Exception in CD command execution -----"+e.getMessage());
		}

		return retStatus;
	}

	public void executeMKDIR(String parameters) {
		// TODO Auto-generated method stub
		try{
			File newDir = new File(currentDirectory + File.separator+parameters);
			if(!newDir.exists()){
				newDir.mkdir();
			}else{
				System.out.println("directory already exists");
				return;
			}

		}catch(Exception e){
			System.out.println("Exception in mkdir command execution" + e.getMessage());
		}

	}

	public boolean executeDELETE(String parameters) {
		// TODO Auto-generated method stub

		try{
			File file = new File(currentDirectory+File.separator+parameters);
			if(file.exists()) {
				if(!ServerManager.checkForFilesInExecution(file)){
					file.delete();
					return true;
				}else{
					System.out.println("file cannot be deleted :: " + file.getAbsolutePath());
					return false;
				}
			}
			else{
				System.out.println(":::: File does not exist ::: File:: " + currentDirectory+File.separator+parameters);
				return false;
			}
		}catch(Exception e){
			System.out.println("Exception in execute delete command"+e.getMessage());
		}
		return false;
	}

	public boolean executeGET(DataInputStream sockInp,DataOutputStream sockOutp) {
		// TODO Auto-generated method stub
		try{
			String fileName = sockInp.readUTF();

			File getFile = new File(currentDirectory+ File.separator + fileName);

			int id = ++cmdID;//***to be generated in servermanager
			System.out.println(":::: For command ID :: "+id+" getting file from Server path :: "+getFile.getAbsolutePath());

			if(getFile.exists()) {// && !ServerManager.transferMap.containsKey(Paths.get(getFile.getAbsolutePath()))) {
				ServerManager.addToPool(GET ,id);
				//polling

				while(ServerManager.pollForFileRead(id, getFile.getAbsolutePath())){
					Thread.sleep(100);
				}

				// file exists and is not in the trasferfilemap
				sockOutp.writeUTF("READY");// Status 1 : ready signal to client
				sockOutp.writeUTF(Integer.toString(id));//send cmdid to client
				//ServerManager.addNewTransferCommand(GET,cmdID, getFile.getAbsolutePath());

				Thread.sleep(1000);

				if(ServerManager.terminateSet.contains(cmdID)){
					//if cmd is in terminate set
					ServerManager.terminate(GET,cmdID, getFile.getAbsolutePath());
					return false;
				}else{
					if(!transferGetBytes(getFile,sockOutp))
						return false;
					ServerManager.remove(GET,getFile.getAbsolutePath());
				}
				//-----end----
				System.out.println("Server: File "+fileName+" sent successfully to client " + Thread.currentThread().getId());

			}else { //if(!getFile.exists()) {
				sockOutp.writeUTF("File Not Found");//send status2
				System.out.println(":::: GET file does not exist ::::");
			/*}
			else {//file exists and is in the transfermap and has a writelock
				sockOutp.writeUTF("File already in use");//send status2
				System.out.println(":::: GET file already in use :: Pooling the thread::");*/

				//add in readPool

			}

		}catch(Exception e){
			System.out.println("::::Exception in Get file function:: "+e.getMessage());
			e.printStackTrace();
		}
		return true;
	}

	public boolean transferGetBytes(File getFile, DataOutputStream sockOutp) {
		byte[] buffer = new byte[1000];
		try {
			File file = new File(getFile.getAbsolutePath());

			long fileSize = file.length();
			byte[] fileSizeBytes = ByteBuffer.allocate(8).putLong(fileSize).array();
			sockOutp.write(fileSizeBytes, 0, 8);
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
			int count = 0;
			while((count = in.read(buffer)) > 0){

				if(ServerManager.terminateSet.contains(cmdID)){
					ServerManager.terminate(GET,cmdID, getFile.getAbsolutePath());
					in.close();
					return false;
				}
				sockOutp.write(buffer, 0, count);

			}
			in.close();
		} catch(Exception e){
			e.printStackTrace();
		}
		return true;
	}

	public void executePUT(DataInputStream sockInp,DataOutputStream sockOutp) {
		// TODO Auto-generated method stub
		int id = ++cmdID;
		try{
			String fileName = sockInp.readUTF();
			File putFile = new File(currentDirectory + File.separator+ fileName);

			System.out.println("For command ID :: "+id+" :::: file is being copied to server directory path :: "+putFile.getAbsolutePath());
			//-----send status to client

			if(!putFile.exists()){
				sockOutp.writeUTF("File does not Exist");
			}
			if(putFile.exists()){
				sockOutp.writeUTF("File Already Exists");
			}
				if(!ServerManager.addNewTransferCommand(PUT, id, putFile.getAbsolutePath())){
					while(!ServerManager.pollForFileWrite(id, putFile.getAbsolutePath())){
						Thread.sleep(100);
					}
				}
				//Thread.sleep(100);

				//----begin sending file to client-----
				sockOutp.writeUTF(Integer.toString(id));//send commandID
				if(!transferPutBytes(putFile,sockInp))
					return;
				ServerManager.remove(PUT,putFile.getAbsolutePath());
				sockOutp.writeUTF("Server: File "+fileName+" uploaded successfully");
				//sockOutp.writeUTF(id + "completed successfully");
				//cmdStatus.remove(id);

				/*	}
		else if(putFile.exists()){// && !ServerManager.transferMap.containsKey(Paths.get(putFile.getAbsolutePath()))
				sockOutp.writeUTF("File Already Exists");
			}
			else
				sockOutp.writeUTF("File in use");*/

		}catch(Exception e){
			System.out.println(":::: Exception in executing PUT function :: "+ e.getMessage());
			e.printStackTrace();
		}
	}

	public boolean transferPutBytes(File putFile, DataInputStream sockInp) {
		try {

		byte[] fileSizeBuffer = new byte[8];
		sockInp.read(fileSizeBuffer);
		ByteArrayInputStream bais = new ByteArrayInputStream(fileSizeBuffer);
		DataInputStream dis = new DataInputStream(bais);
		long fileSize = dis.readLong();

		FileOutputStream f = new FileOutputStream(putFile);
		int count = 0;
		byte[] buffer = new byte[1000];
		long bytesReceived = 0;
		while(bytesReceived < fileSize) {
			if (ServerManager.terminateSet.contains(cmdID)) {
				ServerManager.terminate(PUT, cmdID, putFile.getAbsolutePath());
				ServerManager.deletePutFile(putFile);
				f.close();
				return false;
			}else{

				count = sockInp.read(buffer);
				f.write(buffer, 0, count);
				bytesReceived += count;
			}
		}
		f.close();
		}
		catch(Exception e) {
			System.out.println("Error in transferring file");
		}
		//-----end----
		return true;
	}

	private String getFileName(String param) {
		// TODO Auto-generated method stub
		String retFileName = null;
		try{

			if(param.indexOf('\\') > -1 ){
				String[] p = param.split(Pattern.quote("\\"));
				retFileName = p[p.length - 1];
			}
			else if(param.indexOf('/') > -1){
				String[] p = param.split("/");
				retFileName = p[p.length - 1];
			}
			else{
				retFileName = param;
			}
		}catch(Exception e){
			System.out.println("Exception in getFileName Functions" + e.getMessage());
		}
    	return retFileName;
	}

}


text:
require 'spec_helper'

describe GSGraph::Notification do
  let :attributes do
    {
      :id => 'notif_579612276_139149416',
      :title => 'Nobuhiro Nakajima commented on your status.',
      :message => 'Actual Comment Here',
      :link => 'http://www.gamestamper.com/matake/posts/10150574049082277',
      :unread => 0,
      :application => {
        :id => '19675640871',
        :name => 'Feed Comments'
      },
      :from => {
        :id => '1260873121',
        :name => 'Nobuhiro Nakajima'
      },
      :to => {
        :id => '579612276',
        :name => 'Nov Matake'
      },
      :created_time => '2012-01-25T04:01:09+0000',
      :updated_time => '2012-01-25T04:01:20+0000'
    }
  end

  it 'should setup all supported attributes' do
    notification = GSGraph::Notification.new(attributes[:id], attributes)
    notification.identifier.should == attributes[:id]
    notification.title.should      == attributes[:title]
    notification.message.should    == attributes[:message]
    notification.link.should       == attributes[:link]
    notification.unread.should be_false
    notification.application.should == GSGraph::Application.new(
      attributes[:application][:id], attributes[:application]
    )
    notification.from.should == GSGraph::User.new(
      attributes[:from][:id], attributes[:from]
    )
    notification.to.should == GSGraph::User.new(
      attributes[:to][:id], attributes[:to]
    )
    notification.created_time.should == Time.parse('2012-01-25T04:01:09+0000')
    notification.updated_time.should == Time.parse('2012-01-25T04:01:20+0000')
  end

  describe '#read!' do
    it 'should update unread to read' do
      mock_graph :post, 'notification_id', 'true', :params => {
        :unread => 'false'
      }, :access_token => 'access_token' do
        GSGraph::Notification.new('notification_id').read!(
          :access_token => 'access_token'
        ).should be_true
      end
    end
  end
end


text:
package de.danoeh.antennapod.config;

import android.app.Application;
import android.content.Context;
import android.content.Intent;

import de.danoeh.antennapod.PodcastApp;
import de.danoeh.antennapod.activity.StorageErrorActivity;
import de.danoeh.antennapod.core.ApplicationCallbacks;
import de.danoeh.antennapod.core.preferences.UserPreferences;

public class ApplicationCallbacksImpl implements ApplicationCallbacks {

    @Override
    public Application getApplicationInstance() {
        return PodcastApp.getInstance();
    }

    @Override
    public Intent getStorageErrorActivity(Context context) {
        return new Intent(context, StorageErrorActivity.class);
    }

    @Override
    public void setUpdateInterval(long updateInterval) {
        UserPreferences.restartUpdateAlarm(updateInterval, updateInterval);
    }
}


text:
package java.lang;

/**
 * The wrapper for the primitive type {@code long}.
 *

 * As with the specification, this implementation relies on code laid out in Henry S. Warren, Jr.'s Hacker's
 * Delight, (Addison Wesley, 2002) as well as The Aggregate's Magic Algorithms.
 *
 * @see java.lang.Number
 * @since 1.0
 */
public final class Long extends Number implements Comparable<Long> {

    private static final long serialVersionUID = 4290774380558885855L;

    /**
     * The value which the receiver represents.
     */
    private final long value;

    /**
     * Constant for the maximum {@code long} value, 263-1.
     */
    public static final long MAX_VALUE = 0x7FFFFFFFFFFFFFFFL;

    /**
     * Constant for the minimum {@code long} value, -263.
     */
    public static final long MIN_VALUE = 0x8000000000000000L;

    /**
     * The {@link Class} object that represents the primitive type {@code long}.
     */
    @SuppressWarnings("unchecked")
    public static final Class<Long> TYPE = (Class<Long>) new long[0].getClass()
            .getComponentType();

    // Note: This can't be set to "long.class", since *that* is
    // defined to be "java.lang.Long.TYPE";

    /**
     * Constant for the number of bits needed to represent a {@code long} in
     * two's complement form.
     *
     * @since 1.5
     */
    public static final int SIZE = 64;

    /**
     * Constructs a new {@code Long} with the specified primitive long value.
     *
     * @param value
     *            the primitive long value to store in the new instance.
     */
    public Long(long value) {
        this.value = value;
    }

    /**
     * Constructs a new {@code Long} from the specified string.
     *
     * @param string
     *            the string representation of a long value.
     * @throws NumberFormatException
     *             if {@code string} can not be decoded into a long value.
     * @see #parseLong(String)
     */
    public Long(String string) throws NumberFormatException {
        this(parseLong(string));
    }

    @Override
    public byte byteValue() {
        return (byte) value;
    }

    /**
     * Compares this object to the specified long object to determine their
     * relative order.
     *
     * @param object
     *            the long object to compare this object to.
     * @return a negative value if the value of this long is less than the value
     *         of {@code object}; 0 if the value of this long and the value of
     *         {@code object} are equal; a positive value if the value of this
     *         long is greater than the value of {@code object}.
     * @see java.lang.Comparable
     * @since 1.2
     */
    public int compareTo(Long object) {
        return value > object.value ? 1 : (value < object.value ? -1 : 0);
    }

    /**
     * Parses the specified string and returns a {@code Long} instance if the
     * string can be decoded into a long value. The string may be an optional
     * minus sign "-" followed by a hexadecimal ("0x..." or "#..."), octal
     * ("0..."), or decimal ("...") representation of a long.
     *
     * @param string
     *            a string representation of a long value.
     * @return a {@code Long} containing the value represented by {@code string}.
     * @throws NumberFormatException
     *             if {@code string} can not be parsed as a long value.
     */
    public static Long decode(String string) throws NumberFormatException {
        int length = string.length(), i = 0;
        if (length == 0) {
            throw new NumberFormatException();
        }
        char firstDigit = string.charAt(i);
        boolean negative = firstDigit == '-';
        if (negative) {
            if (length == 1) {
                throw new NumberFormatException(string);
            }
            firstDigit = string.charAt(++i);
        }

        int base = 10;
        if (firstDigit == '0') {
            if (++i == length) {
                return valueOf(0L);
            }
            if ((firstDigit = string.charAt(i)) == 'x' || firstDigit == 'X') {
                if (i == length) {
                    throw new NumberFormatException(string);
                }
                i++;
                base = 16;
            } else {
                base = 8;
            }
        } else if (firstDigit == '#') {
            if (i == length) {
                throw new NumberFormatException(string);
            }
            i++;
            base = 16;
        }

        long result = parse(string, i, base, negative);
        return valueOf(result);
    }

    @Override
    public double doubleValue() {
        return value;
    }

    /**
     * Compares this instance with the specified object and indicates if they
     * are equal. In order to be equal, {@code o} must be an instance of
     * {@code Long} and have the same long value as this object.
     *
     * @param o
     *            the object to compare this long with.
     * @return {@code true} if the specified object is equal to this
     *         {@code Long}; {@code false} otherwise.
     */
    @Override
    public boolean equals(Object o) {
        return (o instanceof Long)
                && (value == ((Long) o).value);
    }

    @Override
    public float floatValue() {
        return value;
    }

    /**
     * Returns the {@code Long} value of the system property identified by
     * {@code string}. Returns {@code null} if {@code string} is {@code null}
     * or empty, if the property can not be found or if its value can not be
     * parsed as a long.
     *
     * @param string
     *            the name of the requested system property.
     * @return the requested property's value as a {@code Long} or {@code null}.
     */
    public static Long getLong(String string) {
        if (string == null || string.length() == 0) {
            return null;
        }
        String prop = System.getProperty(string);
        if (prop == null) {
            return null;
        }
        try {
            return decode(prop);
        } catch (NumberFormatException ex) {
            return null;
        }
    }

    /**
     * Returns the {@code Long} value of the system property identified by
     * {@code string}. Returns the specified default value if {@code string} is
     * {@code null} or empty, if the property can not be found or if its value
     * can not be parsed as a long.
     *
     * @param string
     *            the name of the requested system property.
     * @param defaultValue
     *            the default value that is returned if there is no long system
     *            property with the requested name.
     * @return the requested property's value as a {@code Long} or the default
     *         value.
     */
    public static Long getLong(String string, long defaultValue) {
        if (string == null || string.length() == 0) {
            return valueOf(defaultValue);
        }
        String prop = System.getProperty(string);
        if (prop == null) {
            return valueOf(defaultValue);
        }
        try {
            return decode(prop);
        } catch (NumberFormatException ex) {
            return valueOf(defaultValue);
        }
    }

    /**
     * Returns the {@code Long} value of the system property identified by
     * {@code string}. Returns the specified default value if {@code string} is
     * {@code null} or empty, if the property can not be found or if its value
     * can not be parsed as a long.
     *
     * @param string
     *            the name of the requested system property.
     * @param defaultValue
     *            the default value that is returned if there is no long system
     *            property with the requested name.
     * @return the requested property's value as a {@code Long} or the default
     *         value.
     */
    public static Long getLong(String string, Long defaultValue) {
        if (string == null || string.length() == 0) {
            return defaultValue;
        }
        String prop = System.getProperty(string);
        if (prop == null) {
            return defaultValue;
        }
        try {
            return decode(prop);
        } catch (NumberFormatException ex) {
            return defaultValue;
        }
    }

    @Override
    public int hashCode() {
        return (int) (value ^ (value >>> 32));
    }

    @Override
    public int intValue() {
        return (int) value;
    }

    /**
     * Gets the primitive value of this long.
     *
     * @return this object's primitive value.
     */
    @Override
    public long longValue() {
        return value;
    }

    /**
     * Parses the specified string as a signed decimal long value. The ASCII
     * character \u002d ('-') is recognized as the minus sign.
     *
     * @param string
     *            the string representation of a long value.
     * @return the primitive long value represented by {@code string}.
     * @throws NumberFormatException
     *             if {@code string} is {@code null}, has a length of zero or
     *             can not be parsed as a long value.
     */
    public static long parseLong(String string) throws NumberFormatException {
        return parseLong(string, 10);
    }

    /**
     * Parses the specified string as a signed long value using the specified
     * radix. The ASCII character \u002d ('-') is recognized as the minus sign.
     *
     * @param string
     *            the string representation of a long value.
     * @param radix
     *            the radix to use when parsing.
     * @return the primitive long value represented by {@code string} using
     *         {@code radix}.
     * @throws NumberFormatException
     *             if {@code string} is {@code null} or has a length of zero,
     *             {@code radix < Character.MIN_RADIX},
     *             {@code radix > Character.MAX_RADIX}, or if {@code string}
     *             can not be parsed as a long value.
     */
    public static long parseLong(String string, int radix)
            throws NumberFormatException {
        if (string == null || radix < Character.MIN_RADIX
                || radix > Character.MAX_RADIX) {
            throw new NumberFormatException();
        }
        int length = string.length(), i = 0;
        if (length == 0) {
            throw new NumberFormatException(string);
        }
        boolean negative = string.charAt(i) == '-';
        if (negative && ++i == length) {
            throw new NumberFormatException(string);
        }

        return parse(string, i, radix, negative);
    }

    private static long parse(String string, int offset, int radix,
            boolean negative) {
        long max = Long.MIN_VALUE / radix;
        long result = 0, length = string.length();
        while (offset < length) {
            int digit = Character.digit(string.charAt(offset++), radix);
            if (digit == -1) {
                throw new NumberFormatException(string);
            }
            if (max > result) {
                throw new NumberFormatException(string);
            }
            long next = result * radix - digit;
            if (next > result) {
                throw new NumberFormatException(string);
            }
            result = next;
        }
        if (!negative) {
            result = -result;
            if (result < 0) {
                throw new NumberFormatException(string);
            }
        }
        return result;
    }

    @Override
    public short shortValue() {
        return (short) value;
    }

    /**
     * Converts the specified long value into its binary string representation.
     * The returned string is a concatenation of '0' and '1' characters.
     *
     * @param l
     *            the long value to convert.
     * @return the binary string representation of {@code l}.
     */
    public static String toBinaryString(long l) {
        int count = 1;
        long j = l;

        if (l < 0) {
            count = 64;
        } else {
            while ((j >>= 1) != 0) {
                count++;
            }
        }

        char[] buffer = new char[count];
        do {
            buffer[--count] = (char) ((l & 1) + '0');
            l >>= 1;
        } while (count > 0);
        return new String(0, buffer.length, buffer);
    }

    /**
     * Converts the specified long value into its hexadecimal string
     * representation. The returned string is a concatenation of characters from
     * '0' to '9' and 'a' to 'f'.
     *
     * @param l
     *            the long value to convert.
     * @return the hexadecimal string representation of {@code l}.
     */
    public static String toHexString(long l) {
        int count = 1;
        long j = l;

        if (l < 0) {
            count = 16;
        } else {
            while ((j >>= 4) != 0) {
                count++;
            }
        }

        char[] buffer = new char[count];
        do {
            int t = (int) (l & 15);
            if (t > 9) {
                t = t - 10 + 'a';
            } else {
                t += '0';
            }
            buffer[--count] = (char) t;
            l >>= 4;
        } while (count > 0);
        return new String(0, buffer.length, buffer);
    }

    /**
     * Converts the specified long value into its octal string representation.
     * The returned string is a concatenation of characters from '0' to '7'.
     *
     * @param l
     *            the long value to convert.
     * @return the octal string representation of {@code l}.
     */
    public static String toOctalString(long l) {
        int count = 1;
        long j = l;

        if (l < 0) {
            count = 22;
        } else {
            while ((j >>>= 3) != 0) {
                count++;
            }
        }

        char[] buffer = new char[count];
        do {
            buffer[--count] = (char) ((l & 7) + '0');
            l >>>= 3;
        } while (count > 0);
        return new String(0, buffer.length, buffer);
    }

    @Override
    public String toString() {
        return Long.toString(value);
    }

    /**
     * Converts the specified long value into its decimal string representation.
     * The returned string is a concatenation of a minus sign if the number is
     * negative and characters from '0' to '9'.
     *
     * @param l
     *            the long to convert.
     * @return the decimal string representation of {@code l}.
     */
    public static String toString(long l) {
        return toString(l, 10);
    }

    /**
     * Converts the specified long value into a string representation based on
     * the specified radix. The returned string is a concatenation of a minus
     * sign if the number is negative and characters from '0' to '9' and 'a' to
     * 'z', depending on the radix. If {@code radix} is not in the interval
     * defined by {@code Character.MIN_RADIX} and {@code Character.MAX_RADIX}
     * then 10 is used as the base for the conversion.
     *
     * @param l
     *            the long to convert.
     * @param radix
     *            the base to use for the conversion.
     * @return the string representation of {@code l}.
     */
    public static String toString(long l, int radix) {
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) {
            radix = 10;
        }
        if (l == 0) {
            return "0"; //$NON-NLS-1$
        }

        int count = 2;
        long j = l;
        boolean negative = l < 0;
        if (!negative) {
            count = 1;
            j = -l;
        }
        while ((l /= radix) != 0) {
            count++;
        }

        char[] buffer = new char[count];
        do {
            int ch = 0 - (int) (j % radix);
            if (ch > 9) {
                ch = ch - 10 + 'a';
            } else {
                ch += '0';
            }
            buffer[--count] = (char) ch;
        } while ((j /= radix) != 0);
        if (negative) {
            buffer[0] = '-';
        }
        return new String(0, buffer.length, buffer);
    }

    /**
     * Parses the specified string as a signed decimal long value.
     *
     * @param string
     *            the string representation of a long value.
     * @return a {@code Long} instance containing the long value represented by
     *         {@code string}.
     * @throws NumberFormatException
     *             if {@code string} is {@code null}, has a length of zero or
     *             can not be parsed as a long value.
     * @see #parseLong(String)
     */
    public static Long valueOf(String string) throws NumberFormatException {
        return valueOf(parseLong(string));
    }

    /**
     * Parses the specified string as a signed long value using the specified
     * radix.
     *
     * @param string
     *            the string representation of a long value.
     * @param radix
     *            the radix to use when parsing.
     * @return a {@code Long} instance containing the long value represented by
     *         {@code string} using {@code radix}.
     * @throws NumberFormatException
     *             if {@code string} is {@code null} or has a length of zero,
     *             {@code radix < Character.MIN_RADIX},
     *             {@code radix > Character.MAX_RADIX}, or if {@code string}
     *             can not be parsed as a long value.
     * @see #parseLong(String, int)
     */
    public static Long valueOf(String string, int radix)
            throws NumberFormatException {
        return valueOf(parseLong(string, radix));
    }

    /**
     * Determines the highest (leftmost) bit of the specified long value that is
     * 1 and returns the bit mask value for that bit. This is also referred to
     * as the Most Significant 1 Bit. Returns zero if the specified long is
     * zero.
     *
     * @param lng
     *            the long to examine.
     * @return the bit mask indicating the highest 1 bit in {@code lng}.
     * @since 1.5
     */
    public static long highestOneBit(long lng) {
        lng |= (lng >> 1);
        lng |= (lng >> 2);
        lng |= (lng >> 4);
        lng |= (lng >> 8);
        lng |= (lng >> 16);
        lng |= (lng >> 32);
        return (lng & ~(lng >>> 1));
    }

    /**
     * Determines the lowest (rightmost) bit of the specified long value that is
     * 1 and returns the bit mask value for that bit. This is also referred to
     * as the Least Significant 1 Bit. Returns zero if the specified long is
     * zero.
     *
     * @param lng
     *            the long to examine.
     * @return the bit mask indicating the lowest 1 bit in {@code lng}.
     * @since 1.5
     */
    public static long lowestOneBit(long lng) {
        return (lng & (-lng));
    }

    /**
     * Determines the number of leading zeros in the specified long value prior
     * to the {@link #highestOneBit(long) highest one bit}.
     *
     * @param lng
     *            the long to examine.
     * @return the number of leading zeros in {@code lng}.
     * @since 1.5
     */
    public static int numberOfLeadingZeros(long lng) {
        lng |= lng >> 1;
        lng |= lng >> 2;
        lng |= lng >> 4;
        lng |= lng >> 8;
        lng |= lng >> 16;
        lng |= lng >> 32;
        return bitCount(~lng);
    }

    /**
     * Determines the number of trailing zeros in the specified long value after
     * the {@link #lowestOneBit(long) lowest one bit}.
     *
     * @param lng
     *            the long to examine.
     * @return the number of trailing zeros in {@code lng}.
     * @since 1.5
     */
    public static int numberOfTrailingZeros(long lng) {
        return bitCount((lng & -lng) - 1);
    }

    /**
     * Counts the number of 1 bits in the specified long value; this is also
     * referred to as population count.
     *
     * @param lng
     *            the long to examine.
     * @return the number of 1 bits in {@code lng}.
     * @since 1.5
     */
    public static int bitCount(long lng) {
        lng = (lng & 0x5555555555555555L) + ((lng >> 1) & 0x5555555555555555L);
        lng = (lng & 0x3333333333333333L) + ((lng >> 2) & 0x3333333333333333L);
        // adjust for 64-bit integer
        int i = (int) ((lng >>> 32) + lng);
        i = (i & 0x0F0F0F0F) + ((i >> 4) & 0x0F0F0F0F);
        i = (i & 0x00FF00FF) + ((i >> 8) & 0x00FF00FF);
        i = (i & 0x0000FFFF) + ((i >> 16) & 0x0000FFFF);
        return i;
    }

    /**
     * Rotates the bits of the specified long value to the left by the specified
     * number of bits.
     *
     * @param lng
     *            the long value to rotate left.
     * @param distance
     *            the number of bits to rotate.
     * @return the rotated value.
     * @since 1.5
     */
    public static long rotateLeft(long lng, int distance) {
        if (distance == 0) {
            return lng;
        }
        /*
         * According to JLS3, 15.19, the right operand of a shift is always
         * implicitly masked with 0x3F, which the negation of 'distance' is
         * taking advantage of.
         */
        return ((lng << distance) | (lng >>> (-distance)));
    }

    /**
     *

     * Rotates the bits of the specified long value to the right by the
     * specified number of bits.
     *
     * @param lng
     *            the long value to rotate right.
     * @param distance
     *            the number of bits to rotate.
     * @return the rotated value.
     * @since 1.5
     */
    public static long rotateRight(long lng, int distance) {
        if (distance == 0) {
            return lng;
        }
        /*
         * According to JLS3, 15.19, the right operand of a shift is always
         * implicitly masked with 0x3F, which the negation of 'distance' is
         * taking advantage of.
         */
        return ((lng >>> distance) | (lng << (-distance)));
    }

    /**
     * Reverses the order of the bytes of the specified long value.
     *
     * @param lng
     *            the long value for which to reverse the byte order.
     * @return the reversed value.
     * @since 1.5
     */
    public static long reverseBytes(long lng) {
        long b7 = lng >>> 56;
        long b6 = (lng >>> 40) & 0xFF00L;
        long b5 = (lng >>> 24) & 0xFF0000L;
        long b4 = (lng >>> 8) & 0xFF000000L;
        long b3 = (lng & 0xFF000000L) << 8;
        long b2 = (lng & 0xFF0000L) << 24;
        long b1 = (lng & 0xFF00L) << 40;
        long b0 = lng << 56;
        return (b0 | b1 | b2 | b3 | b4 | b5 | b6 | b7);
    }

    /**
     * Reverses the order of the bits of the specified long value.
     *
     * @param lng
     *            the long value for which to reverse the bit order.
     * @return the reversed value.
     * @since 1.5
     */
    public static long reverse(long lng) {
        // From Hacker's Delight, 7-1, Figure 7-1
        lng = (lng & 0x5555555555555555L) << 1 | (lng >> 1)
                & 0x5555555555555555L;
        lng = (lng & 0x3333333333333333L) << 2 | (lng >> 2)
                & 0x3333333333333333L;
        lng = (lng & 0x0F0F0F0F0F0F0F0FL) << 4 | (lng >> 4)
                & 0x0F0F0F0F0F0F0F0FL;
        return reverseBytes(lng);
    }

    /**
     * Returns the value of the {@code signum} function for the specified long
     * value.
     *
     * @param lng
     *            the long value to check.
     * @return -1 if {@code lng} is negative, 1 if {@code lng} is positive, 0 if
     *         {@code lng} is zero.
     * @since 1.5
     */
    public static int signum(long lng) {
        return (lng == 0 ? 0 : (lng < 0 ? -1 : 1));
    }

    /**
     * Returns a {@code Long} instance for the specified long value.
     *

     * If it is not necessary to get a new {@code Long} instance, it is
     * recommended to use this method instead of the constructor, since it
     * maintains a cache of instances which may result in better performance.
     *
     * @param lng
     *            the long value to store in the instance.
     * @return a {@code Long} instance containing {@code lng}.
     * @since 1.5
     */
    public static Long valueOf(long lng) {
        if (lng < -128 || lng > 127) {
            return new Long(lng);
        }
        return valueOfCache.CACHE[128+(int)lng];
    }

    static class valueOfCache {
        /**
         *

         * A cache of instances used by {@link Long#valueOf(long)} and auto-boxing.
         */
        static final Long[] CACHE = new Long[256];

        static {
            for(int i=-128; i<=127; i++) {
                CACHE[i+128] = new Long(i);
            }
        }
    }
}


text:
import 'babel-polyfill';

import React                        from 'react';
import ReactDOM                     from 'react-dom';
import { Provider }                 from 'react-redux';
import { Router, browserHistory }   from 'react-router';

import getRoutes                    from './routes.js';
import { ApiClient }                from 'utils/index.js';

import createStore                  from 'redux/create.js';

const client = new ApiClient(),
    destination = document.getElementById('content'),
    store = createStore(browserHistory, client, window.__data);

function createElement(Component, props) {
    if (Component.fetchInClientOnly) {
        Component.prototype.componentDidMount = () => {
            Component.fetchData(store.getState, store.dispatch, props.location, props.params);
        };
    } else if(Component.fetchData) {
        Component.fetchData(store.getState, store.dispatch, props.location, props.params);
    }
    return React.createElement(Component, props);
}

const component = (
    <Router createElement={ createElement } history={ browserHistory }>
        { getRoutes(store) }
    </Router>
);

ReactDOM.render(
    <Provider store={ store } key="provider">
        { component }
    </Provider>,
    destination
);

if(process.env.NODE_ENV !== 'production') {
    window.React = React; // enable debugger

    if(!destination || !destination.firstChild || !destination.firstChild.attributes || !destination.firstChild.attributes['data-react-checksum']) {
        console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
    }
}

if (__DEVTOOLS__) {
    const DevTools = require('./containers/DevTools/DevTools');
    ReactDOM.render(
        <Provider store={ store } key="provider">
            <div>
                { component }
                <DevTools />
            </div>
        </Provider>,
        destination
    );
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TurnNodeWeightParameters</title>
<meta name="date" content="2015-01-13" />
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style" />

 <meta name="generator" content="Adobe RoboHelp 10" />

概述
软件包
 类
树
已过时
索引
帮助

 上一个类   下一个类
    无框架     所有类

摘要: 嵌套 | 字段 | 构造方法 | 方法
详细信息: 字段 | 构造方法 | 方法

com.supermap.android.networkAnalyst

类 TurnNodeWeightParameters

java.lang.Object
  com.supermap.android.networkAnalyst.TurnNodeWeightParameters

所有已实现的接口:

java.io.Serializable

public class TurnNodeWeightParameters

extends java.lang.Object

implements java.io.Serializable

更新转向结点权值参数类。 通过本类可以设置目标结点 ID、目标转向结点的起始弧段 ID、目标转向结点的终止弧段 ID、转向权值字段的名称,以及指定的最新转向结点的权值。

另请参见:

序列化表格

字段摘要

 int
fromEdgeID

           目标转向结点的起始弧段 ID.

 int
nodeID

           目标结点 ID.

 int
toEdgeID

           目标转向结点的终止弧段 ID.

 int
weight

           指定的最新转向结点的权值.

 TurnNodeWeightFieldType
weightField

           转向权值字段的名称.

构造方法摘要

TurnNodeWeightParameters()

方法摘要

从类 java.lang.Object 继承的方法

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细信息

nodeID

public int nodeID

目标结点 ID.

fromEdgeID

public int fromEdgeID

目标转向结点的起始弧段 ID.

toEdgeID

public int toEdgeID

目标转向结点的终止弧段 ID.

weightField

public TurnNodeWeightFieldType weightField

转向权值字段的名称.

weight

public int weight

指定的最新转向结点的权值.

构造方法详细信息

TurnNodeWeightParameters

public TurnNodeWeightParameters()

概述
软件包
 类
树
已过时
索引
帮助

 上一个类   下一个类
    无框架     所有类

摘要: 嵌套 | 字段 | 构造方法 | 方法
详细信息: 字段 | 构造方法 | 方法


text:
package org.apache.hadoop.hive.metastore.tools;

import com.google.common.annotations.VisibleForTesting;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.DatabaseProduct;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Helper class that generates SQL queries with syntax specific to target DB
 * todo: why throw MetaException?
 */
@VisibleForTesting
public final class SQLGenerator {
  static final private Logger LOG = LoggerFactory.getLogger(SQLGenerator.class.getName());
  private final DatabaseProduct dbProduct;

  private final Configuration conf;

  public SQLGenerator(DatabaseProduct dbProduct, Configuration conf) {
    this.dbProduct = dbProduct;
    this.conf = conf;
  }

  /**
   * Generates "Insert into T(a,b,c) values(1,2,'f'),(3,4,'c')" for appropriate DB
   *
   * @param tblColumns   e.g. "T(a,b,c)"
   * @param rows         e.g. list of Strings like 3,4,'d'
   * @param paramsList   List of parameters which in turn is list of Strings to be set in PreparedStatement object
   * @return List PreparedStatement objects for fully formed INSERT INTO ... statements
   */
  public List<PreparedStatement> createInsertValuesPreparedStmt(Connection dbConn,
                                                                String tblColumns, List<String> rows,
                                                                List<List<String>> paramsList)
          throws SQLException {
    if (rows == null || rows.size() == 0) {
      return Collections.emptyList();
    }
    assert((paramsList == null) || (rows.size() == paramsList.size()));

    List<Integer> rowsCountInStmts = new ArrayList<>();
    List<String> insertStmts = createInsertValuesStmt(tblColumns, rows, rowsCountInStmts);
    assert(insertStmts.size() == rowsCountInStmts.size());

    List<PreparedStatement> preparedStmts = new ArrayList<>();
    int paramsListFromIdx = 0;
    try {
      for (int stmtIdx = 0; stmtIdx < insertStmts.size(); stmtIdx++) {
        String sql = insertStmts.get(stmtIdx);
        PreparedStatement pStmt = prepareStmtWithParameters(dbConn, sql, null);
        if (paramsList != null) {
          int paramIdx = 1;
          int paramsListToIdx = paramsListFromIdx + rowsCountInStmts.get(stmtIdx);
          for (int paramsListIdx = paramsListFromIdx; paramsListIdx < paramsListToIdx; paramsListIdx++) {
            List<String> params = paramsList.get(paramsListIdx);
            for (int i = 0; i < params.size(); i++, paramIdx++) {
              pStmt.setString(paramIdx, params.get(i));
            }
          }
          paramsListFromIdx = paramsListToIdx;
        }
        preparedStmts.add(pStmt);
      }
    } catch (SQLException e) {
      for (PreparedStatement pst : preparedStmts) {
        pst.close();
      }
      throw e;
    }
    return preparedStmts;
  }

  /**
   * Generates "Insert into T(a,b,c) values(1,2,'f'),(3,4,'c')" for appropriate DB
   *
   * @param tblColumns e.g. "T(a,b,c)"
   * @param rows       e.g. list of Strings like 3,4,'d'
   * @return fully formed INSERT INTO ... statements
   */
  public List<String> createInsertValuesStmt(String tblColumns, List<String> rows) {
    return createInsertValuesStmt(tblColumns, rows, null);
  }

  /**
   * Generates "Insert into T(a,b,c) values(1,2,'f'),(3,4,'c')" for appropriate DB
   *
   * @param tblColumns e.g. "T(a,b,c)"
   * @param rows       e.g. list of Strings like 3,4,'d'
   * @param rowsCountInStmts Output the number of rows in each insert statement returned.
   * @return fully formed INSERT INTO ... statements
   */
  private List<String> createInsertValuesStmt(String tblColumns, List<String> rows, List<Integer> rowsCountInStmts) {
    if (rows == null || rows.size() == 0) {
      return Collections.emptyList();
    }
    List<String> insertStmts = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    int numRowsInCurrentStmt = 0;
    switch (dbProduct) {
    case ORACLE:
      if (rows.size() > 1) {
        //http://www.oratable.com/oracle-insert-all/
        //https://livesql.oracle.com/apex/livesql/file/content_BM1LJQ87M5CNIOKPOWPV6ZGR3.html
        for (int numRows = 0; numRows < rows.size(); numRows++) {
          if (numRows % MetastoreConf.getIntVar(conf, ConfVars.DIRECT_SQL_MAX_ELEMENTS_VALUES_CLAUSE) == 0) {
            if (numRows > 0) {
              sb.append(" select * from dual");
              insertStmts.add(sb.toString());
              if (rowsCountInStmts != null) {
                rowsCountInStmts.add(numRowsInCurrentStmt);
              }
              numRowsInCurrentStmt = 0;
            }
            sb.setLength(0);
            sb.append("insert all ");
          }
          sb.append("into ").append(tblColumns).append(" values(").append(rows.get(numRows))
              .append(") ");
          numRowsInCurrentStmt++;
        }
        sb.append("select * from dual");
        insertStmts.add(sb.toString());
        if (rowsCountInStmts != null) {
          rowsCountInStmts.add(numRowsInCurrentStmt);
        }
        return insertStmts;
      }
      //fall through
    case DERBY:
    case MYSQL:
    case POSTGRES:
    case SQLSERVER:
      for (int numRows = 0; numRows < rows.size(); numRows++) {
        if (numRows % MetastoreConf.getIntVar(conf, ConfVars.DIRECT_SQL_MAX_ELEMENTS_VALUES_CLAUSE) == 0) {
          if (numRows > 0) {
            insertStmts.add(sb.substring(0, sb.length() - 1));//exclude trailing comma
            if (rowsCountInStmts != null) {
              rowsCountInStmts.add(numRowsInCurrentStmt);
            }
            numRowsInCurrentStmt = 0;
          }
          sb.setLength(0);
          sb.append("insert into ").append(tblColumns).append(" values");
        }
        sb.append('(').append(rows.get(numRows)).append("),");
        numRowsInCurrentStmt++;
      }
      insertStmts.add(sb.substring(0, sb.length() - 1));//exclude trailing comma
      if (rowsCountInStmts != null) {
        rowsCountInStmts.add(numRowsInCurrentStmt);
      }
      return insertStmts;
    default:
      String msg = "Unrecognized database product name <" + dbProduct + ">";
      LOG.error(msg);
      throw new IllegalStateException(msg);
    }
  }

  /**
   * Given a {@code selectStatement}, decorated it with FOR UPDATE or semantically equivalent
   * construct.  If the DB doesn't support, return original select.
   */
  public String addForUpdateClause(String selectStatement) throws MetaException {
    switch (dbProduct) {
    case DERBY:
      //https://db.apache.org/derby/docs/10.1/ref/rrefsqlj31783.html
      //sadly in Derby, FOR UPDATE doesn't meant what it should
      return selectStatement;
    case MYSQL:
      //http://dev.mysql.com/doc/refman/5.7/en/select.html
    case ORACLE:
      //https://docs.oracle.com/cd/E17952_01/refman-5.6-en/select.html
    case POSTGRES:
      //http://www.postgresql.org/docs/9.0/static/sql-select.html
      return selectStatement + " for update";
    case SQLSERVER:
      //https://msdn.microsoft.com/en-us/library/ms189499.aspx
      //https://msdn.microsoft.com/en-us/library/ms187373.aspx
      String modifier = " with (updlock)";
      int wherePos = selectStatement.toUpperCase().indexOf(" WHERE ");
      if (wherePos < 0) {
        return selectStatement + modifier;
      }
      return selectStatement.substring(0, wherePos) + modifier +
          selectStatement.substring(wherePos, selectStatement.length());
    default:
      String msg = "Unrecognized database product name <" + dbProduct + ">";
      LOG.error(msg);
      throw new MetaException(msg);
    }
  }

  /**
   * Suppose you have a query "select a,b from T" and you want to limit the result set
   * to the first 5 rows.  The mechanism to do that differs in different DBs.
   * Make {@code noSelectsqlQuery} to be "a,b from T" and this method will return the
   * appropriately modified row limiting query.
   * <p>
   * Note that if {@code noSelectsqlQuery} contains a join, you must make sure that
   * all columns are unique for Oracle.
   */
  public String addLimitClause(int numRows, String noSelectsqlQuery) throws MetaException {
    switch (dbProduct) {
    case DERBY:
      //http://db.apache.org/derby/docs/10.7/ref/rrefsqljoffsetfetch.html
      return "select " + noSelectsqlQuery + " fetch first " + numRows + " rows only";
    case MYSQL:
      //http://www.postgresql.org/docs/7.3/static/queries-limit.html
    case POSTGRES:
      //https://dev.mysql.com/doc/refman/5.0/en/select.html
      return "select " + noSelectsqlQuery + " limit " + numRows;
    case ORACLE:
      //newer versions (12c and later) support OFFSET/FETCH
      return "select * from (select " + noSelectsqlQuery + ") where rownum <= " + numRows;
    case SQLSERVER:
      //newer versions (2012 and later) support OFFSET/FETCH
      //https://msdn.microsoft.com/en-us/library/ms189463.aspx
      return "select TOP(" + numRows + ") " + noSelectsqlQuery;
    default:
      String msg = "Unrecognized database product name <" + dbProduct + ">";
      LOG.error(msg);
      throw new MetaException(msg);
    }
  }

  /**
   * Make PreparedStatement object with list of String type parameters to be set.
   * It is assumed the input sql string have the number of "?" equal to number of parameters
   * passed as input.
   * @param dbConn - Connection object
   * @param sql - SQL statement with "?" for input parameters.
   * @param parameters - List of String type parameters to be set in PreparedStatement object
   * @return PreparedStatement type object
   * @throws SQLException
   */
  public PreparedStatement prepareStmtWithParameters(Connection dbConn, String sql, List<String> parameters)
          throws SQLException {
    PreparedStatement pst = dbConn.prepareStatement(addEscapeCharacters(sql));
    if ((parameters == null) || parameters.isEmpty()) {
      return pst;
    }
    try {
      for (int i = 1; i <= parameters.size(); i++) {
        pst.setString(i, parameters.get(i - 1));
      }
    } catch (SQLException e) {
      pst.close();
      throw e;
    }
    return pst;
  }

  public DatabaseProduct getDbProduct() {
    return dbProduct;
  }

  // This is required for SQL executed directly. If the SQL has double quotes then some dbs tend to
  // remove the escape characters and store the variable without double quote.
  public String addEscapeCharacters(String s) {
    if (dbProduct ==  DatabaseProduct.MYSQL) {
      return s.replaceAll("\\\\", "\\\\\\\\");
    }
    return s;
  }

}


text:
<?php
class ModelAccountCustomField extends Model {
	public function getCustomField($custom_field_id) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "custom_field` cf LEFT JOIN `" . DB_PREFIX . "custom_field_description` cfd ON (cf.custom_field_id = cfd.custom_field_id) WHERE cf.status = '1' AND cf.custom_field_id = '" . (int)$custom_field_id . "' AND cfd.language_id = '" . (int)$this->config->get('config_language_id') . "'");

		return $query->row;
	}

	public function getCustomFields($customer_group_id = 0) {
		$custom_field_data = array();

		if (!$customer_group_id) {
			$custom_field_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "custom_field` cf LEFT JOIN `" . DB_PREFIX . "custom_field_description` cfd ON (cf.custom_field_id = cfd.custom_field_id) WHERE cf.status = '1' AND cfd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND cf.status = '1' ORDER BY cf.sort_order ASC");
		} else {
			$custom_field_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "custom_field_customer_group` cfcg LEFT JOIN `" . DB_PREFIX . "custom_field` cf ON (cfcg.custom_field_id = cf.custom_field_id) LEFT JOIN `" . DB_PREFIX . "custom_field_description` cfd ON (cf.custom_field_id = cfd.custom_field_id) WHERE cf.status = '1' AND cfd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND cfcg.customer_group_id = '" . (int)$customer_group_id . "' ORDER BY cf.sort_order ASC");
		}

		foreach ($custom_field_query->rows as $custom_field) {
			$custom_field_value_data = array();

			if ($custom_field['type'] == 'select' || $custom_field['type'] == 'radio' || $custom_field['type'] == 'checkbox') {
				$custom_field_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "custom_field_value cfv LEFT JOIN " . DB_PREFIX . "custom_field_value_description cfvd ON (cfv.custom_field_value_id = cfvd.custom_field_value_id) WHERE cfv.custom_field_id = '" . (int)$custom_field['custom_field_id'] . "' AND cfvd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY cfv.sort_order ASC");

				foreach ($custom_field_value_query->rows as $custom_field_value) {
					$custom_field_value_data[] = array(
						'custom_field_value_id' => $custom_field_value['custom_field_value_id'],
						'name'                  => $custom_field_value['name']
					);
				}
			}

			$custom_field_data[] = array(
				'custom_field_id'    => $custom_field['custom_field_id'],
				'custom_field_value' => $custom_field_value_data,
				'name'               => $custom_field['name'],
				'type'               => $custom_field['type'],
				'value'              => $custom_field['value'],
				'validation'         => $custom_field['validation'],
				'location'           => $custom_field['location'],
				'required'           => empty($custom_field['required']) || $custom_field['required'] == 0 ? false : true,
				'sort_order'         => $custom_field['sort_order']
			);
		}

		return $custom_field_data;
	}
}


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxDolLanguagesQuery extends BxDolDb implements iBxDolSingleton
{
    protected function __construct()
    {
        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
            trigger_error ('Multiple instances are not allowed for the class: ' . get_class($this), E_USER_ERROR);

        parent::__construct();
    }

    /**
     * Prevent cloning the instance
     */
    public function __clone()
    {
        if (isset($GLOBALS['bxDolClasses'][get_class($this)]))
            trigger_error('Clone is not allowed for the class: ' . get_class($this), E_USER_ERROR);
    }

    /**
     * Get singleton instance of the class
     */
    static function getInstance()
    {
        if(!isset($GLOBALS['bxDolClasses'][__CLASS__]))
            $GLOBALS['bxDolClasses'][__CLASS__] = new BxDolLanguagesQuery();

        return $GLOBALS['bxDolClasses'][__CLASS__];
    }

    function getLanguageId($sName, $bFromCache = true)
    {
        return (int)$this->getLanguageField($sName, 'ID', $bFromCache);
    }

    function getLanguageName($iId, $bFromCache = true)
    {
        return $this->getLanguageFieldById($iId, 'Name', $bFromCache);
    }

    function getLanguageTitle($iId, $bFromCache = true)
    {
        return $this->getLanguageFieldById($iId, 'Title', $bFromCache);
    }

    function getLanguageFlag($sName, $bFromCache = true)
    {
        return $this->getLanguageField($sName, 'Flag', $bFromCache);
    }

    function getLanguageDirection($sName, $bFromCache = true)
    {
        return $this->getLanguageField($sName, 'Direction', $bFromCache);
    }

    function getLangCountryCode($sName, $bFromCache = true)
    {
        return $this->getLanguageField($sName, 'LanguageCountry', $bFromCache);
    }

    protected function getLanguageField($sName, $sField, $bFromCache = true)
    {
        $sSql = $this->prepare("SELECT `" . $sField . "` FROM `sys_localization_languages` WHERE `Name`=? AND `Enabled`='1' LIMIT 1", $sName);

        if($bFromCache)
            return $this->fromCache('checkLangExists_' . $sName . '_' . $sField, 'getOne', $sSql);
        else
            return $this->getOne($sSql);
    }

    protected function getLanguageFieldById($iId, $sField, $bFromCache = true)
    {
        $sSql = $this->prepare("SELECT `" . $sField . "` FROM `sys_localization_languages` WHERE `ID`=? AND `Enabled`='1' LIMIT 1", $iId);

        if($bFromCache)
            return $this->fromCache('checkLangExists_' . $iId . '_' . $sField, 'getOne', $sSql);
        else
            return $this->getOne($sSql);
    }

    function getLanguages($bIdAsKey = false, $bActiveOnly = false)
    {
        return $this->getLanguagesWithKey($bIdAsKey ? 'ID' : 'Name', $bActiveOnly);
    }

    function getLanguagesWithKey($sKey = 'Name', $bActiveOnly = false)
    {
        $sSql = "SELECT * FROM `sys_localization_languages` WHERE 1 " . ($bActiveOnly ? " AND `Enabled`='1'" : "") . " ORDER BY `Title` ASC";
        return $this->getPairs($sSql, $sKey, 'Title');
    }

    function getLanguagesBy($aParams, &$aItems, $bReturnCount = true)
    {
        $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
        $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";

        if(!isset($aParams['order']) || empty($aParams['order']))
           $sOrderClause = " `tl`.`ID` ASC ";

        switch($aParams['type']) {
            case 'by_id':
                $aMethod['name'] = 'getRow';
                $aMethod['params'][1] = array(
                	'id' => $aParams['value']
                );

                $sWhereClause .= " AND `tl`.`ID`=:id";
                break;

            case 'by_name':
                $aMethod['name'] = 'getRow';
                $aMethod['params'][1] = array(
                	'name' => $aParams['value']
                );

                $sWhereClause .= " AND `tl`.`Name`=:name";
                break;

            case 'default':
                $aMethod['name'] = 'getRow';
                $aMethod['params'][1] = array(
                	'name' => getParam('lang_default')
                );

                $sWhereClause .= " AND `tl`.`Name`=:name";
                break;

            case 'active':
                $sWhereClause = " AND `tl`.`Enabled`='1'";
                break;

            case 'all':
                $sOrderClause = " `tl`.`Name` ASC ";
                break;

            case 'all_by_id':
            	$aMethod['params'][1] = array(
                    'id' => $aParams['value']
                );

                $sWhereClause .= " AND `tl`.`ID`=:id";
                $sOrderClause = " `tl`.`Name` ASC ";
                break;

            case 'all_by_name':
                $aMethod['params'][1] = array(
                    'name' => $aParams['value']
                );

                $sWhereClause .= " AND `tl`.`Name`=:name";
                $sOrderClause = " `tl`.`Name` ASC ";
                break;

            case 'all_key_id':
                $aMethod['name'] = 'getAllWithKey';
                $aMethod['params'][1] = 'id';
                $aMethod['params'][2] = array();

                if(!empty($aParams['language'])) {
                    $aMethod['params'][2]['id'] = $aParams['language'];

                    $sWhereClause .= " AND `tl`.`ID`=:id";
                }

                if(isset($aParams['enabled'])) {
                    $aMethod['params'][2]['enabled'] = (int)$aParams['enabled'];

                    $sWhereClause .= " AND `tl`.`Enabled`=:enabled";
                }
                break;

            case 'all_key_name':
                $aMethod['name'] = 'getAllWithKey';
                $aMethod['params'][1] = 'name';
                $aMethod['params'][2] = array();

                if(!empty($aParams['language'])) {
                    $aMethod['params'][2]['name'] = $aParams['language'];

                    $sWhereClause .= " AND `tl`.`Name`=:name";
                }

                if(isset($aParams['enabled'])) {
                    $aMethod['params'][2]['enabled'] = (int)$aParams['enabled'];

                    $sWhereClause .= " AND `tl`.`Enabled`=:enabled";
                }
                break;
        }

        $aMethod['params'][0] = "SELECT SQL_CALC_FOUND_ROWS
                `tl`.`ID` AS `id`,
                `tl`.`Name` AS `name`,
                `tl`.`Flag` AS `flag`,
                `tl`.`Title` AS `title`,
                `tl`.`Enabled` AS `enabled`" . $sSelectClause . "
            FROM `sys_localization_languages` AS `tl`" . $sJoinClause . "
            WHERE 1" . $sWhereClause . "
            ORDER BY" . $sOrderClause . $sLimitClause;
        $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);

        if(!$bReturnCount)
            return count($aItems) > 0;

        return (int)$this->getOne("SELECT FOUND_ROWS()");
    }

    function getKeys()
    {
        $sSql = "SELECT `ID`, `IDCategory`, `Key` FROM `sys_localization_keys`";
        return $this->getAllWithKey($sSql, 'ID');
    }

    function getKeysBy($aParams, &$aItems)
    {
        $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
        $sSelectClause = $sJoinClause = $sWhereClause = $sGroupClause = $sOrderClause = $sLimitClause = "";

        $sSelectClause = "`tk`.`ID` AS `id`, `tk`.`IDCategory` AS `category_id`, `tk`.`Key` AS `key`";

        if(!isset($aParams['order']) || empty($aParams['order']))
           $sOrderClause = " `tk`.`Key` ASC ";

        switch($aParams['type']) {
            case 'by_ids':
                $sSelectClause .= ", `tc`.`Name` AS `category_name`, `ts`.`IDLanguage` AS `language_id`, `tl`.`Name` AS `language_name`, `tl`.`Title` AS `language_title`, `ts`.`String` AS `string`";
                $sJoinClause = " LEFT JOIN `sys_localization_categories` AS `tc` ON `tk`.`IDCategory`=`tc`.`ID` LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` LEFT JOIN `sys_localization_languages` AS `tl` ON `ts`.`IDLanguage`=`tl`.`ID` ";
                $sWhereClause .= " AND `tk`.`ID` IN ('" . implode("','", $aParams['value']) . "')";

                if(isset($aParams['language']) && (int)$aParams['language'] != 0) {
                	$aMethod['params'][1] = array(
	                	'id' => $aParams['language']
	                );

                    $sWhereClause .= " AND `tl`.`ID`=:id";
                }
                break;

            case 'by_name':
                $aMethod['name'] = 'getRow';
                $aMethod['params'][1] = array(
                    'key' => $aParams['value']
                );

                $sWhereClause = " AND `tk`.`Key`=:key ";
                break;

            case 'by_language_name_key_key':
            	$aMethod['name'] = 'getAllWithKey';
            	$aMethod['params'][1] = 'key';
            	$aMethod['params'][2] = array(
                    'name' => $aParams['value']
                );

                $sSelectClause .= ", `ts`.`String` AS `string` ";
                $sJoinClause = " LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` LEFT JOIN `sys_localization_languages` AS `tl` ON `ts`.`IDLanguage`=`tl`.`ID` ";
                $sWhereClause = " AND `tl`.`Name`=:name ";
                break;

            case 'by_language_id_key_key':
            	$aMethod['name'] = 'getAllWithKey';
            	$aMethod['params'][1] = 'key';
            	$aMethod['params'][2] = array(
                    'language_id' => (int)$aParams['value']
                );

                $sSelectClause .= ", `ts`.`String` AS `string` ";
                $sJoinClause = " LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` ";
                $sWhereClause = " AND `ts`.`IDLanguage`=:language_id ";
                break;

            case 'autogenerated':
                $sWhereClause = " AND `tk`.`Key` REGEXP '.+_[0-9]{8,10}$' ";

                if(isset($aParams['empty']) && $aParams['empty'] === true) {
                    $aMethod['params'][1] = array(
                        'language_id' => (int)$aParams['language_id']
                    );

                    $sJoinClause = " LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` AND `ts`.`IDLanguage`=:language_id ";
                    $sWhereClause .= " AND ISNULL(`ts`.`String`)";
                }
                break;

            case 'search':
                $aMethod['name'] = 'getColumn';
                $aMethod['params'][1] = array();

                $sSelectClause = "DISTINCT `tk`.`ID` AS `id`";
                $sJoinClause = " LEFT JOIN `sys_localization_categories` AS `tc` ON `tk`.`IDCategory`=`tc`.`ID` LEFT JOIN `sys_localization_strings` AS `ts` ON `tk`.`ID`=`ts`.`IDKey` LEFT JOIN `sys_localization_languages` AS `tl` ON `ts`.`IDLanguage`=`tl`.`ID` ";

                if(isset($aParams['category']) && (int)$aParams['category'] != 0) {
                    $aMethod['params'][1]['category_id'] = $aParams['category'];

                    $sWhereClause .= " AND `tc`.`ID`=:category_id";
                }

                if(isset($aParams['language']) && (int)$aParams['language'] != 0) {
                    $aMethod['params'][1]['language_id'] = $aParams['language'];

                    $sWhereClause .= " AND `tl`.`ID`=:language_id";
                }

                if(isset($aParams['keyword']) && $aParams['keyword'] != '' && $aParams['keyword'] != _t('_adm_pgt_txt_keyword')) {
                    $aMethod['params'][1]['key'] = '%' . $aParams['keyword'] . '%';
                    $aMethod['params'][1]['string'] = '%' . $aParams['keyword'] . '%';

                    $sWhereClause .= " AND (`tk`.`Key` LIKE :key OR `ts`.`String` LIKE :string)";
                }

                $iStart = 0;
                if(isset($aParams['start']) && (int)$aParams['start'] != 0)
                    $iStart = $aParams['start'];

                $iLength = 20;
                if(isset($aParams['length']) && (int)$aParams['length'] != 0)
                    $iLength = $aParams['length'];

                $aMethod['params'][1]['start'] = $iStart;
                $aMethod['params'][1]['length'] = $iLength;
                $sLimitClause .= " LIMIT :start, :length";
                break;

            case 'counter_by_category':
                $aMethod['name'] = 'getPairs';
                $aMethod['params'][1] = 'category_id';
                $aMethod['params'][2] = 'counter';
                $sSelectClause .= ", COUNT(*) AS `counter`";
                $sGroupClause = "GROUP BY `tk`.`IDCategory`";
                break;
        }

        $aMethod['params'][0] = "SELECT " . $sSelectClause . "
            FROM `sys_localization_keys` AS `tk`" . $sJoinClause . "
            WHERE 1" . $sWhereClause . " " . $sGroupClause . "
            ORDER BY" . $sOrderClause . $sLimitClause;
        $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);

        return $aItems !== false;
    }

    function getCategories()
    {
        $sSql = "SELECT `ID`, `Name` FROM `sys_localization_categories` ORDER BY `Name`";
        return $this->getPairs($sSql, 'ID', 'Name');
    }

    function getCategoriesBy($aParams, &$aItems, $bReturnCount = true)
    {
        $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
        $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";

        $sSelectClause = "`tc`.`ID` AS `id`, `tc`.`Name` AS `name`";

        if(!isset($aParams['order']) || empty($aParams['order']))
           $sOrderClause = " `tc`.`ID` ASC ";

        switch($aParams['type']) {
            case 'id_by_name':
                $aMethod['name'] = 'getOne';
                $aMethod['params'][1] = array(
                	'name' => $aParams['value']
                );

                $sSelectClause = "`tc`.`ID` AS `id`";
                $sWhereClause = " AND `tc`.`Name`=:name";
                break;
            case 'by_name':
                $aMethod['name'] = 'getRow';
                $aMethod['params'][1] = array(
                	'name' => $aParams['value']
                );

                $sWhereClause = " AND `tc`.`Name`=:name";
                break;

            case 'all':
                $sOrderClause = " `tc`.`Name` ASC ";
                break;
        }

        $aMethod['params'][0] = "SELECT " . ($bReturnCount ? "SQL_CALC_FOUND_ROWS" : "") . "
                " . $sSelectClause . "
            FROM `sys_localization_categories` AS `tc`" . $sJoinClause . "
            WHERE 1" . $sWhereClause . "
            ORDER BY" . $sOrderClause . $sLimitClause;
        $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);

        if(!$bReturnCount)
            return !empty($aItems);

        return (int)$this->getOne("SELECT FOUND_ROWS()");
    }

    function getStringsBy($aParams, &$aItems, $bReturnCount = true)
    {
        $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query'));
        $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";

        if(!isset($aParams['order']) || empty($aParams['order']))
           $sOrderClause = "`ts`.`IDKey` ASC";

        switch($aParams['type']) {
            case 'by_key_language_id':
                $aMethod['name'] = 'getRow';
                $aMethod['params'][1] = array(
                	'key' => $aParams['key'],
                	'language_id' => $aParams['language_id']
                );

                $sJoinClause = "LEFT JOIN `sys_localization_keys` AS `tk` ON `ts`.`IDKey`=`tk`.`ID`";
                $sWhereClause .= "AND `tk`.`Key`=:key AND `ts`.`IDLanguage`=:language_id";
                break;

            case 'all_by_key_key_language_id':
                $aMethod['name'] = 'getAllWithKey';
                $aMethod['params'][1] = 'language_id';
                $aMethod['params'][2] = array(
                	'key' => $aParams['value']
                );

                $sJoinClause = "LEFT JOIN `sys_localization_keys` AS `tk` ON `ts`.`IDKey`=`tk`.`ID`";
                $sWhereClause .= "AND `tk`.`Key`=:key";
                break;
        }

        $aMethod['params'][0] = "SELECT SQL_CALC_FOUND_ROWS
                `ts`.`IDKey` AS `key_id`,
                `ts`.`IDLanguage` AS `language_id`,
                `ts`.`String` AS `string` " . $sSelectClause . "
            FROM `sys_localization_strings` AS `ts` " . $sJoinClause . "
            WHERE 1 " . $sWhereClause . "
            ORDER BY " . $sOrderClause . " " . $sLimitClause;
        $aItems = call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);

        if(!$bReturnCount)
            return count($aItems) > 0;

        return (int)$this->getOne("SELECT FOUND_ROWS()");
    }
}

/** @} */


text:
var promix = require('./index');

function pending() {
	var promise = promix.promise();

	return {
		promise: promise,
		resolve: promise.fulfill,
		reject: promise.reject
	};
}

module.exports = {
	pending: pending,
	deferred: pending
};


text:
Deescription
===========

This cookbook will install and configure a Cassandra ring.
More info about Cassandra can be found at http://cassandra.apache.org

Attributes
==========

* cassandra/version                 Version of Cassandra to install.
* cassandra/cluster_name            The name of the Cassandra cluster to connect to.
* cassandra/seeds                   Comma separated list of Cassandra hosts which will act as seeds.
* cassandra/num_tokens              Number of tokens assigned to this node.
* cassandra/data_file_directories   Directories where Cassandra data files should reside on disk.
* cassandra/commitlog_directory     Directory where commit logs will be written to.
* cassandra/saved_caches_directory  Directory where the saved caches will be written to.
* cassandra/log4j_directory         Directory where logfiles will be written to.

* Many more which are not optional with pre-configured defaults.

Usage
=====

This cookbook will install the new 1.2 series of Cassandra. Initial token values are no longer needed. This cookbook uses [virtual nodes](http://www.datastax.com/docs/1.2/cluster_architecture/data_distribution#distribution) and [Murmur3Partitioner](http://www.datastax.com/docs/1.2/cluster_architecture/partitioners#m3ppartitioner) for faster hashing. Calculating an initial token per node is no longer necessary.

The easiest way to configure Cassandra seed hosts is to use Elastic IP's (if on AWS). Allocate the number of EIP's you'd like to use for seed hosts, and populate
a comma separated list of the ***public*** DNS EIP values as the cassandra/seeds input.


text:
package org.elasticsearch.xpack.sql.plan.logical;

import org.elasticsearch.xpack.ql.plan.logical.LogicalPlan;
import org.elasticsearch.xpack.ql.plan.logical.UnaryPlan;
import org.elasticsearch.xpack.ql.tree.NodeInfo;
import org.elasticsearch.xpack.ql.tree.Source;

import java.util.Map;
import java.util.Objects;

public class With extends UnaryPlan {
    private final Map<String, SubQueryAlias> subQueries;

    public With(Source source, LogicalPlan child, Map<String, SubQueryAlias> subQueries) {
        super(source, child);
        this.subQueries = subQueries;
    }

    @Override
    protected NodeInfo<With> info() {
        return NodeInfo.create(this, With::new, child(), subQueries);
    }

    @Override
    protected With replaceChild(LogicalPlan newChild) {
        return new With(source(), newChild, subQueries);
    }

    public Map<String, SubQueryAlias> subQueries() {
        return subQueries;
    }

    @Override
    public boolean expressionsResolved() {
        return true;
    }

    @Override
    public int hashCode() {
        return Objects.hash(child(), subQueries);
    }

    @Override
    public boolean equals(Object obj) {
        if (super.equals(obj) == false) {
            return false;
        }

        With other = (With) obj;
        return Objects.equals(subQueries, other.subQueries);
    }
}


text:
As the marshmallow reaches to grab the fork and rope
 - vital to your survival -
 you notice something strange.
The hand is moving slower than normal,
 as if it was in slo-mo.
You merely walk over it and grab
 your rope and fork before the
marshmallow can achieve your doom.
The marshmallow exclaims,
"I've never seen someone move with
 such lightning-quick reflexes...
 I didn't think the legends were true."
At this point, you're in a state of confusion,
 and you're sick of the sweet smell
 in the marshmallow's belly.
You wonder how you're ever going to get out,
and as you look at the ceiling, you notice yourself
start levitating ever so slowly.
Before the marshmallow realizes,
you've blown a hole through its
belly and see the outside world.
It's dark and fluffy.
While you don't believe that you might be the One,
 it's only up to you to save the world.

[You crawl through the hole you just made and...] (matrix2/matrix2.md)

[There is no darkness - or fluffiness - without the Light.] (matrix2inception/matrix2inception.md)


text:
from functools import wraps

def uses_django_db(f):
    """Ensures Django discards any broken database connections

    Django normally cleans up connections once a web request has
    been processed. However, here we are not serving web requests
    and are outside of Django's request handling logic. We therefore
    need to make sure we cleanup any broken database connections.
    """
    # TODO: Move this into middleware
    #       (Tracked in: https://github.com/adamcharnock/lightbus/issues/6)

    # Import Django locally as it is not a dependency of Lightbus.
    # This will only get run on startup anyway, and we will assume that
    # if someone uses this decorator then they have Django installed.
    from django.db import reset_queries, close_old_connections

    @wraps(f)
    def wrapped(*args, **kwargs):
        reset_queries()
        close_old_connections()

        try:
            return f(*args, **kwargs)
        finally:
            close_old_connections()

    return wrapped


text:
function AutoAcquire( event )
    local unit = event.target

    if IsValidEntity(unit) and unit:IsIdle() then
        local target = FindAttackableEnemies(unit)
        if target then
            --print(unit:GetUnitName()," now attacking -> ",target:GetUnitName(),"Team: ",target:GetTeamNumber())
            ExecuteOrderFromTable({ UnitIndex = unit:GetEntityIndex(),
                                OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET, -- DOTA_UNIT_ORDER_MOVE_TO_TARGET
                                TargetIndex = target:GetEntityIndex(),
                                Queue = false
                            })
            --unit:MoveToTargetToAttack(target)
        end
    end
end

function FindAttackableEnemies( unit )
    local radius = unit.AcquisitionRange
    local enemies = FindEnemiesInRadius( unit, radius )
    local player = unit:GetPlayerOwner()
    local hero = player and player:GetAssignedHero() or nil

    for _,target in pairs(enemies) do
        if UnitCanAttackTarget(unit, target) then --and
          --((hero and GameMode:IsWithinHeroBounds(hero, target:GetAbsOrigin())) or hero == nil) then -- uncommented for now, since it's unnescessary
            return target
        end
    end
    return nil
end


text:
class CProcesser
{
private:
	CProcesser& operator=( const CProcesser& cp ){}
	CProcesser( const CProcesser& cp ){}

	CPcm2Wav m_pcm2wav;		//pcm ת wav´¦Àí
	CAudioTimeSandPitchS	m_audioTimeScalingS;
public:
	CProcesser();

	int Pcm2Wav( const Pcm2WavInfo& info );
	int Pcm2Wav( const float* buffer, unsigned long bufferSize,const Pcm2WavInfo& info );
	float* TimeScalingAndPitchShifting(int shift, float scale,float* dataIn,unsigned int bufferSize,int channels = 1,int winSize=1024,int hop=256);
	float* TimeScaling( float scale,float* buffer, unsigned long bufferSize, int channels = 1, int winSize=1024,
		int hop = 256
		);
	float* PitchShiftingFile( int shift, float* buffer, unsigned long bufferSize, int channels = 1, int winSize=1024,
		int hop = 256  );
	float* PitchShifting( int shift, float* buffer, unsigned long bufferSize, int channels = 1, int winSize=1024,
		int hop = 256  );
	float* PitchShiftingFile( int shift, const char* filename );
	unsigned long GetAfterScaleSize(){ return m_audioTimeScalingS.GetSize(); }
	unsigned long GetAfterPitchSize(){ return m_audioTimeScalingS.GetResampleSize(); }
	float GetAfterPitchShitingSampleRate(){ return m_audioTimeScalingS.GetSampleRateScale(); }

};

#endif