text:
package com.google.cloud.container.v1;

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

@javax.annotation.Generated("by GAPIC")
public class SampleApp {
  public static void main(String args[]) {
    Logger.getLogger("").setLevel(Level.WARNING);
    try {
      executeNoCatch();
      System.out.println("OK");
    } catch (Exception e) {
      System.err.println("Failed with exception:");
      e.printStackTrace(System.err);
      System.exit(1);
    }
  }

  public static void executeNoCatch() throws Exception {
    try (ClusterManagerClient client = ClusterManagerClient.create()) {
      // Add your method call here.
    }
  }
}


text:
declare interface ConstructorWithTypeParameterConstructor
{
	new <T>(param1: T)
}

declare interface ConstructorWithTypeParameter
{

}

declare var ConstructorWithTypeParameter: ConstructorWithTypeParameterConstructor;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.poi.hssf.model;

import org.apache.poi.hssf.record.formula.Ptg;
import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.FormulaParseException;
import org.apache.poi.ss.formula.FormulaParser;
import org.apache.poi.ss.formula.FormulaParsingWorkbook;
import org.apache.poi.ss.formula.FormulaRenderer;
import org.apache.poi.ss.formula.FormulaType;

/**
 * HSSF wrapper for the {@link FormulaParser} and {@link FormulaRenderer}
 *
 * @author Josh Micich
 */
public final class HSSFFormulaParser {

	private static FormulaParsingWorkbook createParsingWorkbook(HSSFWorkbook book) {
		return HSSFEvaluationWorkbook.create(book);
	}

	private HSSFFormulaParser() {
		// no instances of this class
	}

	/**
	 * Convenience method for parsing cell formulas. see {@link #parse(String, HSSFWorkbook, int, int)}
	 */
	public static Ptg[] parse(String formula, HSSFWorkbook workbook) throws FormulaParseException {
		return parse(formula, workbook, FormulaType.CELL);
	}

	/**
	 * @param formulaType a constant from {@link FormulaType}
	 * @return the parsed formula tokens
     * @throws FormulaParseException if the formula has incorrect syntax or is otherwise invalid
	 */
	public static Ptg[] parse(String formula, HSSFWorkbook workbook, int formulaType) throws FormulaParseException {
		return parse(formula, workbook, formulaType, -1);
	}

	/**
	 * @param formula     the formula to parse
	 * @param workbook    the parent workbook
	 * @param formulaType a constant from {@link FormulaType}
	 * @param sheetIndex  the 0-based index of the sheet this formula belongs to.
	 * The sheet index is required to resolve sheet-level names. -1 means that
	 * the scope of the name will be ignored and  the parser will match named ranges only by name
	 *
	 * @return the parsed formula tokens
     * @throws FormulaParseException if the formula has incorrect syntax or is otherwise invalid
	 */
	public static Ptg[] parse(String formula, HSSFWorkbook workbook, int formulaType, int sheetIndex) throws FormulaParseException {
		return FormulaParser.parse(formula, createParsingWorkbook(workbook), formulaType, sheetIndex);
	}

	/**
	 * Static method to convert an array of {@link Ptg}s in RPN order
	 * to a human readable string format in infix mode.
	 * @param book  used for defined names and 3D references
	 * @param ptgs  must not be null
	 * @return a human readable String
	 */
	public static String toFormulaString(HSSFWorkbook book, Ptg[] ptgs) {
		return FormulaRenderer.toFormulaString(HSSFEvaluationWorkbook.create(book), ptgs);
	}
}


text:
A nice and easy way to get a Minecraft server up and running using docker on a Raspberry Pi. For help on getting started with docker see the [official getting started guide][0].
For more information on Minecraft and check out it's [website][1].

## Building rpi-minecraft

Running this will build you a docker image with the latest version of both
rpi-minecraft and Minecraft itself.

    git clone https://github.com/kroonwijk/rpi-minecraft
    cd rpi-minecraft
    sudo docker build -t kroonwijk/rpi-minecraft .

## Running rpi-minecraft

Running the first time will set your port to a static port of your choice so
that you can easily map a proxy to. If this is the only thing running on your
system you can map the port to 25565 and no proxy is needed. i.e.
`-p=25565:25565` . If you want to enable the query protocol you need
to add another -p=25565:25565/udp to forward the UDP protocol on the
same port as well.
Also be sure your mounted directory on your host machine is
already created before running `mkdir -p /mnt/minecraft`.

    sudo docker run -d=true -p=25565:25565 -v=/mnt/minecraft:/data kroonwijk/rpi-minecraft /start

From now on when you start/stop rpi-minecraft you should use the container id
with the following commands. To get your container id, after you initial run
type `sudo docker ps` and it will show up on the left side followed by the
image name which is `kroonwijk/rpi-minecraft:latest`.

    sudo docker start <container_id>
    sudo docker stop <container_id>

### Notes on the run command

 + `-v` is the volume you are mounting `-v=host_dir:docker_dir`
 + `kroonwijk/rpi-minecraft` is simply what I called my docker build of this image
 + `-d=true` allows this to run cleanly as a daemon, remove for debugging
 + `-p` is the port it connects to, `-p=host_port:docker_port`

### Credits

Image based on [overshard/docker-minecraft][2]

[0]: http://www.docker.io/gettingstarted/
[1]: http://minecraft.net/
[2]: https://github.com/overshard/docker-minecraft/


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 23: 145 (1939)

#### Original name
Haplographium coccorum Petch

### Remarks
null


text:
package fsm

import (
	"k8s.io/test-infra/mungegithub/github"
)

const (
	labelPreReview     = "state/prereview"
	labelNeedsReview   = "state/needs-review"
	labelChangesNeeded = "state/needs-changes"
	labelNeedsApproval = "state/needs-approval"
)

// ComputeState can be used to compute the state of each PR.
func ComputeState(obj *github.MungeObject) error {
	if !obj.IsPR() {
		return nil
	}

	// Every PR starts in the pre-review state.
	var currentState State = &PreReview{}
	for currentState.Name() != endState {
		var err error
		currentState, err = currentState.Process(obj)
		if err != nil {
			return err
		}
	}
	return nil
}

// State is the interface implemented by all states.
type State interface {
	Process(obj *github.MungeObject) (State, error)
	Name() string
}


text:
namespace mshtml
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;

    [ComImport, Guid("3050F211-98B5-11CF-BB82-00AA00BDCE0B"), TypeLibType((short)0x1040)]
    public interface IHTMLOptionElement
    {
        [DispId(0x3e9)]
        bool selected {[param: In] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3e9)] set;[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3e9)] get; }
        [DispId(0x3ea)]
        string value {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ea)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ea)] get; }
        [DispId(0x3eb)]
        bool defaultSelected {[param: In] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3eb)] set;[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3eb)] get; }
        [DispId(0x3ed)]
        int index {[param: In] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ed)] set;[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ed)] get; }
        [DispId(0x3ec)]
        string text {[param: In, MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ec)] set;[return: MarshalAs(UnmanagedType.BStr)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ec)] get; }
        [DispId(0x3ee)]
        IHTMLFormElement form {[return: MarshalAs(UnmanagedType.Interface)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(0x3ee)] get; }
    }
}


text:
<?php

namespace Core\Services\Contracts;

/**
 * The Request class represents an HTTP request.
 */
interface Request
{
    /**
     * Get the full URL for the request.
     *
     * URL structure: scheme://username:password@domain:port/basepath/path?query_string#fragment_id
     *
     * Example: http://localhost/myapp/public/path?a=4
     *
     * Notes:
     * - This function does not include username:password from a full URL or the fragment (hash).
     * - The host is lowercase as per RFC 952/2181.
     * - It will not show the default port 80 for HTTP and port 443 for HTTPS.
     * - The #fragment_id is not sent to the server by the client (browser) and will not be added to the full URL.
     *
     * @return string
     */
    public function fullUrl();

    /**
     * Get the URL for the request (without query string).
     *
     * Example: http://localhost/myapp/public/path
     *
     * @return string
     */
    public function url();

    /**
     * Get the root URL for the application.
     *
     * Example: http://localhost/myapp/public
     *
     * Notes:
     * - This function does not include username:password from a full URL or the fragment (hash).
     * - The host is lowercase as per RFC 952/2181.
     * - It will not show the default port 80 for HTTP and port 443 for HTTPS.
     *
     * @return string
     */
    public function baseUrl();

    /**
     * Get the path for the request (without query string).
     *
     * Example: fullUrl = "http://localhost/myapp/public/test?a=4" --> path = "test"
     *
     * @return string
     */
    public function path();

    /**
     * Get a segment from the path (zero based index).
     *
     * Example: path = "foo/bar/baz" --> segment(1) = "bar"
     *
     * @param int $index
     * @param string|null $default
     * @return string|null
     */
    public function segment($index, $default = null);

    /**
     * Retrieve an input item from the request ($_GET and $_POST).
     *
     * @param string|null $key
     * @param string|null $default
     * @return string|array
     */
    public function input($key = null, $default = null);

    /**
     * Retrieve a cookie from the request.
     *
     * @param string|null $key
     * @param string|null $default
     * @return string|array
     */
    public function cookie($key = null, $default = null);

    /**
     * Get an uploaded file by given key.
     *
     * If multiple files have been uploaded under the key, an array of the uploaded files is returned.
     * If the key does not exist in $_FILES, null is returned.
     *
     * @param string $key The key of $_FILES, using "dot" notation.
     * @return UploadedFile|array|null
     */
    public function file($key);

//    /**
//     * Get a HTTP header item.
//     *
//     * @param string|null $key
//     * @param string|null $default
//     * @return string|array
//     */
//    public function header($key = null, $default = null);

    /**
     * Gets the raw HTTP request body of the request.
     *
     * @return string
     */
    public function body();

    /**
     * Gets the request method.
     *
     * If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the
     * "real" intended HTTP method. The method is always an uppercase string.
     *
     * @return string ('GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE' or 'OPTIONS')
     */
    public function method();

    /**
     * Returns the client IP address.
     *
     * @return string
     */
    public function ip();

    /**
     * Checks whether the request is secure or not.
     *
     * @return bool
     */
    public function isSecure();

    /**
     * Determine if the request is the result of an AJAX call.
     *
     * It works if your JavaScript library sets an X-Requested-With HTTP header.
     * It is known to work with common JavaScript frameworks:
     *
     * @link http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
     *
     * @return bool
     */
    public function isAjax();

    /**
     * Determine if the request is sending JSON.
     *
     * @return bool
     */
    public function isJson();

    /**
     * Determine if the current request is asking for JSON in return.
     *
     * @return bool
     */
    public function wantsJson();
}


text:
@protocol DownLoaderDelegate <NSObject>

- (void)downLoaderDidFinishDownloadingImage:(UIImage *)image;

@end

typedef void(^BLOCK)(UIImage *image);

@interface ImageDownLoader : NSObject

//代理
@property (nonatomic,assign) id<DownLoaderDelegate> delegate;
//block
@property (nonatomic,copy) BLOCK block;

//静态方法
//封装同步
+ (UIImage *)sychronousDownLoader:(NSString *)imgUrl;

//封装异步,使用代理
+ (void)asynchronousDownLoader:(NSString *)imgUrl
                   andDelegate:(id<DownLoaderDelegate>)delegate;
//封装异步,使用block块
+ (void)asynchronousDownLoader:(NSString *)imgUrl
                   andBlock :(BLOCK)block;
//动态方法
-(void)delegateAsychronousdownLoader: (NSString *)imgUrl;
-(void)blockAsychronousdownLoader:(NSString *)imgUrl;

@end


text:
/* -*- mode:C++; -*- */
/* MIT License -- MyThOS: The Many-Threads Operating System
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * Copyright 2016 Randolf Rotta, Robert Kuban, and contributors, BTU Cottbus-Senftenberg
 */

#pragma once

#include "mythos/protocol/common.hh"
#include "mythos/protocol/KernelMemory.hh"

namespace mythos {
  namespace protocol {

    struct PageMap
    {
      constexpr static uint8_t proto = PAGEMAP;

      enum Methods : uint8_t {
        MAP,
        REMAP,
        PROTECT,
        UNMAP,
        INSTALLMAP,
        REMOVEMAP,
        RESULT
      };

      BITFIELD_DEF(CapRequest, PageMapReq)
      BoolField<value_t,base_t,0> configurable;
      PageMapReq() : value(0) {}
      BITFIELD_END

      BITFIELD_DEF(uint8_t, MapFlags)
      BoolField<value_t,base_t,0> writable;
      BoolField<value_t,base_t,1> executable;
      BoolField<value_t,base_t,2> cache_disabled;
      BoolField<value_t,base_t,3> write_through;
      BoolField<value_t,base_t,4> configurable;
      MapFlags() : value(0) {}
      BITFIELD_END

      struct InstallMap : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + INSTALLMAP;
        InstallMap(CapPtr pagemap, uintptr_t vaddr, size_t level, MapFlags flags)
        : InvocationBase(label, getLength(this)), vaddr(vaddr), level(level), flags(flags)
        {
          addExtraCap(pagemap);
        }
        CapPtr pagemap() const { return capPtrs[0]; }
        uintptr_t vaddr;
        size_t level;
        MapFlags flags;
      };

      struct RemoveMap : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + REMOVEMAP;
        RemoveMap(uintptr_t vaddr, size_t level)
        : InvocationBase(label, getLength(this)), vaddr(vaddr), level(level)
        {}
        uintptr_t vaddr;
        size_t level;
      };

      struct Mmap : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + MAP;
        Mmap(CapPtr frame, uintptr_t vaddr, size_t size, MapFlags flags, size_t offset)
        : InvocationBase(label, getLength(this)), vaddr(vaddr), size(size), flags(flags), offset(offset)
        {
          addExtraCap(frame);
        }
        CapPtr tgtFrame() const { return capPtrs[0]; }
        uintptr_t vaddr;
        size_t size;
        MapFlags flags;
        size_t offset;
      };

      struct Remap : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + REMAP;
        Remap(uintptr_t sourceAddr, uintptr_t destAddr, size_t size)
	  : InvocationBase(label, getLength(this)), sourceAddr(sourceAddr),
	    destAddr(destAddr), size(size)
	{}
	uintptr_t sourceAddr;
	uintptr_t destAddr;
	size_t size;
      };

      struct Mprotect : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + PROTECT;
        Mprotect(uintptr_t vaddr, size_t size, MapFlags flags)
	  : InvocationBase(label, getLength(this)), vaddr(vaddr), size(size), flags(flags)
	{}
        uintptr_t vaddr;
	size_t size;
	MapFlags flags;
      };

      struct Munmap : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + UNMAP;
        Munmap(uintptr_t vaddr, size_t size)
	  : InvocationBase(label, getLength(this)), vaddr(vaddr), size(size)
	{}
        uintptr_t vaddr;
	size_t size;
      };

      struct Create : public KernelMemory::CreateBase {
        Create(CapPtr dst, CapPtr factory, size_t level)
          : CreateBase(dst, factory, getLength(this), 0), level(level)
        {}
        size_t level;
      };

      struct Result : public InvocationBase {
        constexpr static uint16_t label = (proto << 8) + RESULT;
        Result(uintptr_t vaddr, size_t level)
          : InvocationBase(label, getLength(this)), vaddr(vaddr), level(level)
        {}
        uintptr_t vaddr;
        size_t level;
      };

      template<class IMPL, class... ARGS>
      static Error dispatchRequest(IMPL* obj, uint8_t m, ARGS const&...args) {
	switch(Methods(m)) {
	case MAP: return obj->invokeMmap(args...);
	case REMAP: return obj->invokeRemap(args...);
	case UNMAP: return obj->invokeMunmap(args...);
	case PROTECT: return obj->invokeMprotect(args...);
        case INSTALLMAP: return obj->invokeInstallMap(args...);
        case REMOVEMAP: return obj->invokeRemoveMap(args...);
	default: return Error::NOT_IMPLEMENTED;
	}
      }
    };

  } // namespace protocol
} // namespace mythos


text:
package com.neusoft.knowledge.common.cache.ehcache;

/**
 * @Title:AbstractCache.
 * @Content:com.neusoft.knowledge.common.cache.ehcache.AbstractCache
 * @Description:
 * @Author:Marklin
 * @DateTime:2017-09-30 16:08
 * @Version:1.0version
 */
public abstract class AbstractCache implements InterfaceCache {
    public boolean put(Object key, Object value) {
        return getCacheHelper().put(key, value);
    }

    public Object get(Object key) {
        return getCacheHelper().get(key);
    }

    public <T> T get(Object key, Class<T> clazz) {
        return get(key, clazz);
    }

    public boolean exists(Object key) {
        return getCacheHelper().exists(key);
    }

    public boolean remove(Object key) {
        return getCacheHelper().remove(key);
    }
}


text: require("core-js/modules/es6.object.set-prototype-of");


text:
var name = "gilles";
console.log(name);
function sayHello(){
  return "Hello";
}
var sayHello= function () {
  return "Hello";
}

var o={};
o.age =42;
o.ditBonjour = function(msg)
{
  return 'bonjour'+msg;
};
console.log(o.age);
console.log(o.ditBonjour("Techno"));
console.log(process.argv);


text:
def primes_upto(n):
    # Our well known sieve...
    multiples = set()
    yield 2
    # Optimization: Add the even numbers
    multiples.update(range(4, n, 2))

    for p in range(3,n,2):
        if p not in multiples:
            # Found a prime!
            yield p
            multiples.update(range(p*2, n, p))


text:
namespace blink {

TextBufferBase::TextBufferBase()
{
    m_buffer.reserveCapacity(1024);
    m_buffer.resize(capacity());
}

void TextBufferBase::shiftData(size_t)
{
}

void TextBufferBase::pushCharacters(UChar ch, size_t length)
{
    if (length == 0)
        return;
    std::fill_n(ensureDestination(length), length, ch);
}

UChar* TextBufferBase::ensureDestination(size_t length)
{
    if (m_size + length > capacity())
        grow(m_size + length);
    UChar* ans = calcDestination(length);
    m_size += length;
    return ans;
}

void TextBufferBase::grow(size_t demand)
{
    size_t oldCapacity = capacity();
    m_buffer.resize(demand);
    m_buffer.resize(capacity());
    shiftData(oldCapacity);
}

} // namespace blink


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

namespace HuffmanEncoding
{
    public abstract class HuffmanTree<TSymbol>
    {
        public abstract int Frequency
        {
            get;
        }

        public abstract EncodingTree<TSymbol> ToEncodingTree();

        public static HuffmanTree<TSymbol> Create(IEnumerable<TSymbol> source, IEqualityComparer<TSymbol> comparer = null)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (!source.Any())
                throw new InvalidOperationException("Source sequence has no elements.");

            IEqualityComparer<TSymbol> comp = comparer ?? EqualityComparer<TSymbol>.Default;

            Dictionary<TSymbol, int> freq = new Dictionary<TSymbol, int>(comp);

            foreach (TSymbol item in source)
            {
                int f = 1;
                if (freq.ContainsKey(item))
                    f = freq[item] + 1;
                freq[item] = f;
            }

            PriorityQueue<HuffmanTree<TSymbol>> pq = new PriorityQueue<HuffmanTree<TSymbol>>(
                freq.Select(kvp => Tuple.Create((HuffmanTree<TSymbol>)new HuffmanTreeLeaf<TSymbol>(kvp.Key, kvp.Value), kvp.Value)));

            while (pq.Size >= 2)
            {
                var a = pq.Pop();
                var b = pq.Pop();

                var newNode = new HuffmanTreeInternalNode<TSymbol>(a, b);

                pq.Push(newNode, newNode.Frequency);
            }

            return pq.Pop();
        }
    }

    public class HuffmanTreeInternalNode<TSymbol> : HuffmanTree<TSymbol>
    {
        private HuffmanTree<TSymbol> left, right;

        public override int Frequency
        {
            get { return left.Frequency + right.Frequency; }
        }

        public override EncodingTree<TSymbol> ToEncodingTree()
        {
            return new EncodingTreeNode<TSymbol>(left.ToEncodingTree(), right.ToEncodingTree());
        }

        public HuffmanTreeInternalNode(HuffmanTree<TSymbol> left, HuffmanTree<TSymbol> right)
        {
            if (left == null)
                throw new ArgumentNullException("left");

            if (right == null)
                throw new ArgumentNullException("right");

            this.left = left;
            this.right = right;
        }
    }

    public class HuffmanTreeLeaf<TSymbol> : HuffmanTree<TSymbol>
    {
        private TSymbol symbol;
        private int frequency;

        public override int Frequency
        {
            get { return frequency; }
        }

        public TSymbol Symbol
        {
            get { return symbol; }
        }

        public override EncodingTree<TSymbol> ToEncodingTree()
        {
            return new EncodingTreeLeaf<TSymbol>(symbol);
        }

        public HuffmanTreeLeaf(TSymbol symbol, int frequency)
        {
            if (frequency < 0)
                throw new ArgumentOutOfRangeException("frequency");

            this.symbol = symbol;
            this.frequency = frequency;
        }
    }
}


text:
package org.conqat.engine.code_clones.core;

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

import org.conqat.lib.commons.assertion.CCSMAssert;
import org.conqat.lib.commons.collections.CollectionUtils;
import org.conqat.lib.commons.collections.UnmodifiableList;
import org.conqat.lib.commons.reflect.ReflectionUtils;
import org.conqat.lib.commons.reflect.TypeConversionException;

/**
 * Base class that implements a lazily instantiated associative key-value
 * mechanism. Lazy instantiation saves memory in case the store is not used.
 *
 * @author $Author: hummelb $
 * @version $Rev: 35940 $
 * @ConQAT.Rating GREEN Hash: AD653342941409AEA04D6C1670520DFE
 */
public abstract class KeyValueStoreBase {

	/**
	 * Integer that identifies this value store. The scope of the id depends on
	 * the id provider used.
	 */
	private final long id;

	/** Map that stores key-value pairs */
	private Map<String, Object> values;

	/** Map that stores transient flags */
	private Map<String, Boolean> transientFlags;

	/** Construct store with set id */
	protected KeyValueStoreBase(long id) {
		this.id = id;
	}

	/** Return the id of the store */
	public long getId() {
		return id;
	}

	/** Stores a value in the {@link CloneClass} by using a keyword. */
	public void setValue(String key, Object value) {
		ensureValuesMapInitialized();
		values.put(key, value);
	}

	/** Set value using reflection to resolve types */
	public void setValue(String key, String valueString, String typeString)
			throws ClassNotFoundException, TypeConversionException {

		// Type of the value: we need to specify the classloader, since else
		// types cannot be resolved that have been loaded by the bundle class
		// loader.
		Class<?> type = ReflectionUtils.resolveType(typeString, getClass()
				.getClassLoader());

		// Make sure we really got the right type
		CCSMAssert.isTrue(type.getName().equals(typeString),
				"Type was not converted correctly.");

		// Convert value string to actual value
		Object value = ReflectionUtils.convertString(valueString, type);

		// Make sure we really got the right type
		CCSMAssert.isTrue(type.isInstance(value),
				"Value was not converted correctly.");

		setValue(key, value);
	}

	/** Gets a value */
	public Object getValue(String key) {
		if (values == null) {
			return null;
		}
		return values.get(key);
	}

	/** Checks whether a value is stored under this key */
	public boolean containsValue(String key) {
		if (values == null) {
			return false;
		}
		return values.containsKey(key);
	}

	/**
	 * Get a sorted list of the keys stored. Each key is guaranteed to only
	 * appear once. Keys are sorted in lexical order.
	 */
	public UnmodifiableList<String> getKeyList() {
		if (values == null) {
			return CollectionUtils.emptyList();
		}
		return CollectionUtils.asSortedUnmodifiableList(values.keySet());
	}

	/** Gets an int value */
	public int getInt(String key) {
		return (Integer) getValue(key);
	}

	/** Return stored long */
	public long getLong(String key) {
		return (Long) getValue(key);
	}

	/** Return stored long */
	public double getDouble(String key) {
		return (Double) getValue(key);
	}

	/** Gets a string value */
	public String getString(String key) {
		return (String) getValue(key);
	}

	/** Ensures that the values map is initialized */
	private void ensureValuesMapInitialized() {
		if (values == null) {
			values = new HashMap<String, Object>();
		}
	}

	/** Ensures that the values map is initialized */
	private void ensureTransientFlagsMapInitialized() {
		if (transientFlags == null) {
			transientFlags = new HashMap<String, Boolean>();
		}
	}

	/** Determines whether a value is transient. Default value is false. */
	public boolean getTransient(String key) {
		if (transientFlags == null || !transientFlags.containsKey(key)) {
			return false;
		}
		return transientFlags.get(key);
	}

	/** Stores the transient flag for a key */
	public void setTransient(String key, boolean value) {
		ensureTransientFlagsMapInitialized();
		transientFlags.put(key, value);
	}
}


text:
import ShowBannerView from "sample_app/show_banner_view.js"

$(() => {
  return new ShowBannerView({
    el: $("[data-id=show-banner]")
  });
});


text:
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <canvas id="canvas" width="600" height="400"></canvas>
</body>
<script>
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');

    ctx.fillStyle = "blue";
    ctx.fillRect(100, 100, 200, 200);
    // ctx.globalCompositeOperation = "source-over";
    // ctx.globalCompositeOperation = "destination-over";
    // ctx.globalCompositeOperation = "destination-in";
    ctx.globalCompositeOperation = "destination-atop";
    // ctx.globalCompositeOperation = "source-in";
    ctx.fillStyle = "red";
    ctx.beginPath();
    ctx.arc(300, 300, 100, 0, 2 * Math.PI, false);
    ctx.closePath();
    ctx.fill();
</script>

</html>


text:
@main(Messages("playauthenticate.verify.account.title")) {

@Messages("playauthenticate.verify.account.title")

	@Messages("playauthenticate.verify.account.before") @Messages("playauthenticate.verify.account.first").

}


text:
package org.panda_lang.pandomium.settings.categories;

public class LoaderSettings {

    private boolean loadAsync;

    public void setLoadAsync(boolean loadAsync) {
        this.loadAsync = loadAsync;
    }

    public boolean isLoadAsync() {
        return loadAsync;
    }

}


text:
import { isLosslessNumber } from './LosslessNumber.js'
import type { GenericObject, Reviver } from './types'

/**
 * Revive a json object.
 * Applies the reviver function recursively on all values in the JSON object.
 * @param json   A JSON Object, Array, or value
 * @param reviver
 *              A reviver function invoked with arguments `key` and `value`,
 *              which must return a replacement value. The function context
 *              (`this`) is the Object or Array that contains the currently
 *              handled value.
 */
export function revive(json: unknown, reviver: Reviver): unknown {
  return reviveValue({ '': json }, '', json, reviver)
}

/**
 * Revive a value
 */
function reviveValue(
  context: GenericObject<unknown> | Array<unknown>,
  key: string,
  value: unknown,
  reviver: Reviver
): unknown {
  if (Array.isArray(value)) {
    return reviver.call(context, key, reviveArray(value, reviver))
  } else if (value && typeof value === 'object' && !isLosslessNumber(value)) {
    // note the special case for LosslessNumber,
    // we don't want to iterate over the internals of a LosslessNumber
    return reviver.call(
      context,
      key,
      reviveObject(value as unknown as GenericObject<unknown>, reviver)
    )
  } else {
    return reviver.call(context, key, value)
  }
}

/**
 * Revive the properties of an object
 */
function reviveObject(object: GenericObject<unknown>, reviver: Reviver) {
  Object.keys(object).forEach((key) => {
    const value = reviveValue(object, key, object[key], reviver)
    if (value !== undefined) {
      object[key] = value
    } else {
      delete object[key]
    }
  })

  return object
}

/**
 * Revive the properties of an Array
 */
function reviveArray(array: Array<unknown>, reviver: Reviver): Array<unknown> {
  for (let i = 0; i < array.length; i++) {
    array[i] = reviveValue(array, i + '', array[i], reviver)
  }

  return array
}


text:
<?php

namespace Enqueue\Client\ConsumptionExtension;

use Enqueue\Client\DriverInterface;
use Enqueue\Consumption\Context\Start;
use Enqueue\Consumption\StartExtensionInterface;

class SetupBrokerExtension implements StartExtensionInterface
{
    /**
     * @var DriverInterface
     */
    private $driver;

    /**
     * @var bool
     */
    private $isDone;

    /**
     * @param DriverInterface $driver
     */
    public function __construct(DriverInterface $driver)
    {
        $this->driver = $driver;
        $this->isDone = false;
    }

    public function onStart(Start $context): void
    {
        if (false == $this->isDone) {
            $this->isDone = true;
            $this->driver->setupBroker($context->getLogger());
        }
    }
}


text:
apishore.directive('pwCheck', [function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var firstPassword = '#' + attrs.pwCheck;
            elem.add(firstPassword).on('keyup', function () {
                scope.$apply(function () {
                    ctrl.$setValidity('pwmatch', elem.val() === $(firstPassword).val());
                });
            });
        }
    }
}]);


text:
Handling date input with the DatePicker
=======================================

Using the [[yii\jui\DatePicker|DatePicker]] widget, collecting date input from users can be done in a very convenient way.
In the following example we will use a `Task` model which has a `deadline` attribute, which should be set by a user using
an [ActiveForm](https://github.com/yiisoft/yii2/blob/master/docs/guide/input-forms.md). The attribute value will be stored as a unix timestamp in the database.

In this situation there are 3 components that play together:

- The [[yii\jui\DatePicker|DatePicker]] widget, which is used in the form to display the input field for the model's attribute.
- The [formatter](https://github.com/yiisoft/yii2/blob/master/docs/guide/output-formatting.md) application component which is responsible for the date format that is displayed to the user.
- The [DateValidator](https://github.com/yiisoft/yii2/blob/master/docs/guide/tutorial-core-validators.md#date) which will validate the user input and convert it to a unix timestamp.

First, we add the date picker input field to the form by using the [[yii\widgets\ActiveField::widget()|widget()]] method of the form field:

```php
<?= $form->field($model, 'deadline')->widget(\yii\jui\DatePicker::className(), [
    // if you are using bootstrap, the following line will set the correct style of the input field
    'options' => ['class' => 'form-control'],
    // ... you can configure more DatePicker properties here
]) ?>
```

The second step is to configure the date validator in the [model's rules() method](https://github.com/yiisoft/yii2/blob/master/docs/guide/input-validation.md#declaring-rules):

```php
public function rules()
{
    return [
        // ...

        // ensure empty values are stored as NULL in the database
        ['deadline', 'default', 'value' => null],

        // validate the date and overwrite `deadline` with the unix timestamp
        ['deadline', 'date', 'timestampAttribute' => 'deadline'],
    ];
}
```

We have also added a [default value filter](https://github.com/yiisoft/yii2/blob/master/docs/guide/input-validation.md#handling-empty-inputs) to ensure empty values are stored as `NULL` in the database.
You may skip this step if your date value is [required](https://github.com/yiisoft/yii2/blob/master/docs/guide/tutorial-core-validators.md#required).

The default format of both, date picker and date validator is the value of `Yii::$app->formatter->dateFormat` so you can use this
property to configure the format of the date for the whole application.
To change the date format you have to configure [[yii\validators\DateValidator::format]] and [[yii\jui\DatePicker::dateFormat]].


text:
package org.apache.accumulo.core.iterators.system;

import java.util.HashSet;
import java.util.TreeMap;

import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.SortedMapIterator;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class TimeSettingIteratorTest {

  @Test
  public void test1() throws Exception {
    TreeMap<Key,Value> tm1 = new TreeMap<>();

    tm1.put(new Key("r0", "cf1", "cq1", 9l), new Value("v0".getBytes()));
    tm1.put(new Key("r1", "cf1", "cq1", Long.MAX_VALUE), new Value("v1".getBytes()));
    tm1.put(new Key("r1", "cf1", "cq1", 90l), new Value("v2".getBytes()));
    tm1.put(new Key("r1", "cf1", "cq1", 0l), new Value("v3".getBytes()));
    tm1.put(new Key("r2", "cf1", "cq1", 6l), new Value("v4".getBytes()));

    TimeSettingIterator tsi = new TimeSettingIterator(new SortedMapIterator(tm1), 50);

    tsi.seek(new Range(new Key("r1", "cf1", "cq1", 50l), true, new Key("r1", "cf1", "cq1", 50l), true), new HashSet<ByteSequence>(), false);

    assertTrue(tsi.hasTop());
    assertEquals(new Key("r1", "cf1", "cq1", 50l), tsi.getTopKey());
    assertEquals("v1", tsi.getTopValue().toString());
    tsi.next();

    assertTrue(tsi.hasTop());
    assertEquals(new Key("r1", "cf1", "cq1", 50l), tsi.getTopKey());
    assertEquals("v2", tsi.getTopValue().toString());
    tsi.next();

    assertTrue(tsi.hasTop());
    assertEquals(new Key("r1", "cf1", "cq1", 50l), tsi.getTopKey());
    assertEquals("v3", tsi.getTopValue().toString());
    tsi.next();

    assertFalse(tsi.hasTop());

    tsi.seek(new Range(new Key("r1", "cf1", "cq1", 50l), false, null, true), new HashSet<ByteSequence>(), false);

    assertTrue(tsi.hasTop());
    assertEquals(new Key("r2", "cf1", "cq1", 50l), tsi.getTopKey());
    assertEquals("v4", tsi.getTopValue().toString());
    tsi.next();

    assertFalse(tsi.hasTop());

    tsi.seek(new Range(null, true, new Key("r1", "cf1", "cq1", 50l), false), new HashSet<ByteSequence>(), false);

    assertTrue(tsi.hasTop());
    assertEquals(new Key("r0", "cf1", "cq1", 50l), tsi.getTopKey());
    assertEquals("v0", tsi.getTopValue().toString());
    tsi.next();

    assertFalse(tsi.hasTop());

    tsi.seek(new Range(new Key("r1", "cf1", "cq1", 51l), true, new Key("r1", "cf1", "cq1", 50l), false), new HashSet<ByteSequence>(), false);
    assertFalse(tsi.hasTop());
  }

  @Test
  public void testAvoidKeyCopy() throws Exception {
    TreeMap<Key,Value> tm1 = new TreeMap<>();
    final Key k = new Key("r0", "cf1", "cq1", 9l);

    tm1.put(k, new Value("v0".getBytes()));

    TimeSettingIterator tsi = new TimeSettingIterator(new SortedMapIterator(tm1), 50);

    tsi.seek(new Range(), new HashSet<ByteSequence>(), false);

    assertTrue(tsi.hasTop());
    final Key topKey = tsi.getTopKey();
    assertTrue("Expected the topKey to be the same object", k == topKey);
    assertEquals(new Key("r0", "cf1", "cq1", 50l), topKey);
    assertEquals("v0", tsi.getTopValue().toString());
    tsi.next();

    assertFalse(tsi.hasTop());
  }

}


text:
/**

 * Copyright (C) 2012 - 2013 Xeiam LLC http://xeiam.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.xeiam.xchange.huobi.service.polling;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.currency.CurrencyPair;
import com.xeiam.xchange.huobi.HuobiAdapters;
import com.xeiam.xchange.huobi.dto.marketdata.HuobiDepthWrapper;
import com.xeiam.xchange.dto.marketdata.OrderBook;
import com.xeiam.xchange.dto.marketdata.Ticker;
import com.xeiam.xchange.dto.marketdata.Trades;
import com.xeiam.xchange.dto.trade.LimitOrder;
import com.xeiam.xchange.huobi.dto.marketdata.HuobiFullTrade;
import com.xeiam.xchange.service.polling.marketdata.PollingMarketDataService;

public class HuobiMarketDataService extends HuobiMarketDataServiceRaw implements PollingMarketDataService {

    public HuobiMarketDataService(Exchange exchange) {

        super(exchange);
    }

    @Override
    public Ticker getTicker(CurrencyPair currencyPair, Object... args) throws IOException {

        return HuobiAdapters.adaptTicker(getHuobiTicker(currencyPair), currencyPair);
    }

    @Override
    public OrderBook getOrderBook(CurrencyPair currencyPair, Object... args) throws IOException {

        HuobiDepthWrapper huobiOrderBook = getHuobiOrderBook(currencyPair);

        List<LimitOrder> asks = HuobiAdapters.adaptDepths(huobiOrderBook.getAsks(), currencyPair, "ask");
        List<LimitOrder> bids = HuobiAdapters.adaptDepths(huobiOrderBook.getBids(), currencyPair, "bid");

        Date date = new Date();
        return new OrderBook(date, asks, bids);
    }

    @Override
    public Trades getTrades(CurrencyPair currencyPair, Object... args) throws IOException {

        Long since = null;
        try {
            since = (Long) args[0];
        } catch (ArrayIndexOutOfBoundsException e) {
            // ignore, can happen if no arg given.
        }

        HuobiFullTrade[] huobiTrades = getHuobiTrades(currencyPair, since);

        return HuobiAdapters.adaptTrades(huobiTrades, currencyPair);
    }

}


text:
import fsPath from 'fs-path';
import fs from 'fs';
import Path from 'path';

import Parse from './parse';

const hardCodedName = '<%= templateName %>';
let path, directive;

let fileLocation = 'template/angular/main';

const createWriteStream = (path, fileName) => {
    if(path) {
        return fs.createWriteStream(path + "/" + fileName);
    }
    return fs.createWriteStream(fileName);
};

const makeDirectory = (dirName) => {
    fsPath.mkdirSync(dirName, (err) => {
        if (err) {
            console.log(err);
        }
    });
};

const generateUrl = (url) => {
    if (url.slice(-1) !== '/') {
        return url + "/";
    }

    return url;
};

const scaffold = {
    run: function (argv) {
        let moduleName;

        if(argv.directive) {
            moduleName = argv.directive;
            directive = argv.directive;
            fileLocation =  "template/angular/directive";
        } else {
            moduleName = argv._.pop();
        }

        if (argv.location) {
            path = argv.location;
        }

        let parse = new Parse(moduleName);

        makeDirectory(path);

        fsPath.find(Path.join(__dirname + '/../' + fileLocation), (err, list) => {

            if (err) {
                console.log(err);
            }

            list.dirs.forEach((dirName) => {
                makeDirectory(path + "/" + dirName.split("/").pop());
            });

            list.files.forEach((file) => {
                let fileName = file.replace(Path.join(__dirname + "/../" + fileLocation.toString()) , "");

                if (fileName.indexOf('.gitkeep') >= 0) {
                    return;
                }

                if (fileName.indexOf('controllers') >= 0) {
                    fileName = fileName.replace("Controller", moduleName + "Controller");
                }

                if(argv.directive) {
                    fileName = fileName.replace('index', moduleName);

                    return parse.replace(file, hardCodedName)
                            .pipe(parse.replaceStream('<%= directiveTemplatePath %>', generateUrl(path) + directive + '.tpl.html'))
                            .pipe(createWriteStream(path, fileName));
                }

                return parse.replace( file, hardCodedName)
                    .pipe(createWriteStream(path, fileName));
            });

            console.log("Successfully scaffold your '" + moduleName + "' at '" + path + "'");
        });
    }
};

export default scaffold;


text:
package org.apache.falcon.service;

import org.apache.commons.lang.StringUtils;
import org.apache.falcon.FalconException;
import org.apache.falcon.entity.ClusterHelper;
import org.apache.falcon.entity.EntityUtil;
import org.apache.falcon.entity.v0.Entity;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.cluster.Cluster;
import org.apache.falcon.entity.v0.cluster.Interfacetype;
import org.apache.falcon.hadoop.HadoopClientFactory;
import org.apache.falcon.util.StartupProperties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
 * Host shared libraries in oozie shared lib dir upon creation or modification of cluster.
 */
public class SharedLibraryHostingService implements ConfigurationChangeListener {
    private static final Logger LOG = LoggerFactory.getLogger(SharedLibraryHostingService.class);

    private static final String[] LIBS = StartupProperties.get().getProperty("shared.libs").split(",");

    private static final FalconPathFilter NON_FALCON_JAR_FILTER = new FalconPathFilter() {
        @Override
        public boolean accept(Path path) {
            for (String jarName : LIBS) {
                if (path.getName().startsWith(jarName)) {
                    return true;
                }
            }
            return false;
        }

        @Override
        public String getJarName(Path path) {
            for (String jarName : LIBS) {
                if (path.getName().startsWith(jarName)) {
                    return jarName;
                }
            }
            throw new IllegalArgumentException(path + " is not accepted!");
        }
    };

    private void addLibsTo(Cluster cluster) throws FalconException {
        Path lib = new Path(ClusterHelper.getLocation(cluster, "working"), "lib");
        Path libext = new Path(ClusterHelper.getLocation(cluster, "working"), "libext");
        try {
            Properties properties = StartupProperties.get();
            pushLibsToHDFS(properties.getProperty("system.lib.location"), lib, cluster, NON_FALCON_JAR_FILTER);
            pushLibsToHDFS(properties.getProperty("libext.paths"), libext, cluster, null);
            pushLibsToHDFS(properties.getProperty("libext.feed.paths"),
                    new Path(libext, EntityType.FEED.name()) , cluster, null);
            pushLibsToHDFS(properties.getProperty("libext.feed.replication.paths"),
                    new Path(libext, EntityType.FEED.name() + "/replication"), cluster, null);
            pushLibsToHDFS(properties.getProperty("libext.feed.retention.paths"),
                    new Path(libext, EntityType.FEED.name() + "/retention"), cluster, null);
            pushLibsToHDFS(properties.getProperty("libext.process.paths"),
                    new Path(libext, EntityType.PROCESS.name()) , cluster, null);
        } catch (IOException e) {
            throw new FalconException("Failed to copy shared libs to cluster" + cluster.getName(), e);
        }
    }

    public static void pushLibsToHDFS(String src, Path target, Cluster cluster, FalconPathFilter pathFilter)
        throws IOException, FalconException {
        if (StringUtils.isEmpty(src)) {
            return;
        }

        LOG.debug("Copying libs from {}", src);
        FileSystem fs;
        try {
            fs = getFileSystem(cluster);
            fs.getConf().set("dfs.umaskmode", "022");  // drwxr-xr-x
        } catch (Exception e) {
            throw new FalconException("Unable to connect to HDFS: "
                    + ClusterHelper.getStorageUrl(cluster), e);
        }
        if (!fs.exists(target) && !fs.mkdirs(target)) {
            throw new FalconException("mkdir " + target + " failed");
        }

        for(String srcPaths : src.split(",")) {
            File srcFile = new File(srcPaths);
            File[] srcFiles = new File[] { srcFile };
            if (srcFile.isDirectory()) {
                srcFiles = srcFile.listFiles();
            }

            for (File file : srcFiles) {
                Path path = new Path(file.getAbsolutePath());
                String jarName = StringUtils.removeEnd(path.getName(), ".jar");
                if (pathFilter != null) {
                    if (!pathFilter.accept(path)) {
                        continue;
                    }
                    jarName = pathFilter.getJarName(path);
                }

                Path targetFile = new Path(target, jarName + ".jar");
                if (fs.exists(targetFile)) {
                    FileStatus fstat = fs.getFileStatus(targetFile);
                    if (fstat.getLen() == file.length()) {
                        continue;
                    }
                }
                fs.copyFromLocalFile(false, true, new Path(file.getAbsolutePath()), targetFile);
                LOG.info("Copied {} to {} in {}", file.getAbsolutePath(), targetFile.toString(), fs.getUri());
            }
        }
    }

    // the dir is owned by Falcon but world-readable
    private static FileSystem getFileSystem(Cluster cluster)
        throws FalconException, IOException {
        Configuration conf = ClusterHelper.getConfiguration(cluster);
        conf.setInt("ipc.client.connect.max.retries", 10);

        return HadoopClientFactory.get().createFileSystem(conf);
    }

    @Override
    public void onAdd(Entity entity) throws FalconException {
        if (entity.getEntityType() != EntityType.CLUSTER) {
            return;
        }

        Cluster cluster = (Cluster) entity;
        if (!EntityUtil.responsibleFor(cluster.getColo())) {
            return;
        }

        addLibsTo(cluster);
    }

    @Override
    public void onRemove(Entity entity) throws FalconException {
        // Do Nothing
    }

    @Override
    public void onChange(Entity oldEntity, Entity newEntity) throws FalconException {
        if (oldEntity.getEntityType() != EntityType.CLUSTER) {
            return;
        }
        Cluster oldCluster = (Cluster) oldEntity;
        Cluster newCluster = (Cluster) newEntity;
        if (!ClusterHelper.getInterface(oldCluster, Interfacetype.WRITE).getEndpoint()
                .equals(ClusterHelper.getInterface(newCluster, Interfacetype.WRITE).getEndpoint())
                || !ClusterHelper.getInterface(oldCluster, Interfacetype.WORKFLOW).getEndpoint()
                .equals(ClusterHelper.getInterface(newCluster, Interfacetype.WORKFLOW).getEndpoint())) {
            addLibsTo(newCluster);
        }
    }

    @Override
    public void onReload(Entity entity) throws FalconException {
        try {
            onAdd(entity);
        } catch (FalconException e) {
            throw new FalconException(e);
        }
    }
}


text:
copyright:
  years: 2016
lastupdated: "2016-11-03"

---

# Internet of Things
{: #internetofthings}

Use these services to rapidly build and extend applications that take advantage of data and analytics from your connected devices and sensors.
{: shortdesc}


text:
FROM debian:jessie-slim
MAINTAINER Anouar-Charif ZEKRI <anouarcharif@gmail.com>

ENV DEBIAN_FRONTEND noninteractive
ENV LC_ALL en_US.UTF-8
ENV LANGUAGE en_US:en

RUN \
 apt-get update &&\
 apt-get -y --no-install-recommends install locales apt-utils &&\
 echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen &&\
 locale-gen en_US.UTF-8 &&\
 /usr/sbin/update-locale LANG=en_US.UTF-8 &&\
 echo "mysql-server mysql-server/root_password password root" | debconf-set-selections &&\
 echo "mysql-server mysql-server/root_password_again password root" | debconf-set-selections &&\
 apt-get -y --no-install-recommends install ca-certificates git subversion php5-mysqlnd php5-cli php5-sqlite php5-mcrypt php5-curl php5-intl php-gettext php5-json php5-geoip php5-apcu php5-gd php5-imagick php5-xdebug php5-xhprof php5-xmlrpc imagemagick openssh-client curl software-properties-common gettext zip mysql-server mysql-client apt-transport-https ruby python python3 perl php5-memcached memcached &&\
 curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add - &&\
 echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list &&\
 curl -sSL https://deb.nodesource.com/setup_4.x | bash - &&\
 apt-get -y --no-install-recommends install nodejs yarn &&\
 apt-get autoclean && apt-get clean && apt-get autoremove

RUN \
 sed -ri -e "s/^variables_order.*/variables_order=\"EGPCS\"/g" /etc/php5/cli/php.ini &&\
 echo "xdebug.max_nesting_level=250" >> /etc/php5/mods-available/xdebug.ini

RUN \
 curl -sSL https://getcomposer.org/installer | php -- --filename=composer --install-dir=/usr/bin &&\
 curl -sSL https://phar.phpunit.de/phpunit-5.4.8.phar -o /usr/bin/phpunit  && chmod +x /usr/bin/phpunit  &&\
 curl -sSL http://codeception.com/codecept.phar -o /usr/bin/codecept && chmod +x /usr/bin/codecept &&\
 npm install --no-color --production --global gulp-cli webpack mocha grunt &&\
 rm -rf /root/.npm /root/.composer /tmp/* /var/lib/apt/lists/*


text:
/**
 * --------------------------------------------------------------------------
 * Figuration (v4.3.3): popover.js
 * Licensed under MIT (https://github.com/cast-org/figuration/blob/master/LICENSE)
 * --------------------------------------------------------------------------
 */

(function($) {
    'use strict';

    if (typeof $.fn.CFW_Tooltip === 'undefined') { throw new Error('CFW_Popover requires CFW_Tooltip'); }

    var CFW_Widget_Popover = function(element, options) {
        this.dragAdded = false;
        this.keyTimer = null;
        this.keyDelay = 750;

        this._init('popover', element, options);
    };

    CFW_Widget_Popover.DEFAULTS = $.extend({}, $.fn.CFW_Tooltip.Constructor.DEFAULTS, {
        placement   : 'top',        // Where to locate popover (top/bottom/reverse(left)/forward(right)/auto)
        trigger     : 'click',      // How popover is triggered (click/hover/focus/manual)
        content     : '',           // Content text/html to be inserted
        drag        : false,        // If the popover should be draggable
        dragtext    : '+', // Text for drag handle
        dragsrtext  : 'Drag',       // Screen reader text for drag handle
        dragstep     : 10,          // 'Drag' increment for keyboard
        template    : '

'
    });

    CFW_Widget_Popover.prototype = $.extend({}, $.fn.CFW_Tooltip.Constructor.prototype);

    CFW_Widget_Popover.prototype.constructor = CFW_Widget_Popover;

    CFW_Widget_Popover.prototype.getDefaults = function() {
        return CFW_Widget_Popover.DEFAULTS;
    };

    CFW_Widget_Popover.prototype.createTip = function() {
        var $tip = $(this.settings.template);
        return $tip;
    };

    CFW_Widget_Popover.prototype._hasContent = function() {
        return Boolean(this.getTitle() || this.getContent());
    };

    CFW_Widget_Popover.prototype.setContent = function() {
        var $tip = this.$target;
        var $title = $tip.find('.popover-header');
        var $content = $tip.find('.popover-body');

        if (this.dynamicTip) {
            var title = this.getTitle();
            var content = this.getContent();

            if (this.settings.html) {
                $title.html(title);
                if (typeof content === 'string') {
                    $content.html(content);
                } else {
                    $content.empty().append(content); // Use append for objects to keep js events
                }
            } else {
                $title.text(title);
                $content.text(content);
            }

            // Header gets hidden by :empty CSS rule
            // if (!title && $title) {
            //     $title.remove();
            // }
        }

        // Use '.popover-header' for labelledby
        if ($title.length) {
            var labelledby = $title.eq(0).CFW_getID('cfw-popover');
            this.$target.attr('aria-labelledby', labelledby);
        }

        if (this.settings.drag && !this.dragAdded) {
            if (this.$target.find('[data-cfw-drag="' + this.type + '"]').length <= 0) {
                var $drag = $('' + this.settings.dragtext + '');
                $drag.insertAfter(this.$target.find('.close').eq(0));
                this.dragAdded = true;
            }
        }

        if (this.$target.find('[data-cfw-drag="' + this.type + '"]').length) {
            this.$target.addClass('draggable');
            // Force settings
            if (this.settings.trigger !== 'manual') {
                this.settings.trigger = 'click';
            }
            this.settings.container = 'body';
            // Enable drag handlers
            this.enableDrag();
        }
    };

    CFW_Widget_Popover.prototype.getContent = function() {
        var content;
        var $e = this.$element;
        var s = this.settings;

        content = typeof s.content === 'function' ? s.content.call($e[0]) : s.content;

        return content;
    };

    CFW_Widget_Popover.prototype.enableDrag = function() {
        var $selfRef = this;
        var dragOpt = {
            handle: '[data-cfw-drag="' + this.type + '"]'
        };

        // Remove mutation handler and replace resize location handler
        this.$element.on('afterShow.cfw.' + this.type, function() {
            if ($selfRef.popper !== null) {
                $selfRef.popper.disableEventListeners();
            }

            $selfRef.$target
                .off('mutate.cfw.mutate')
                .removeAttr('data-cfw-mutate')
                .CFW_mutationIgnore();

            $(window)
                .off('resize.cfw.' + $selfRef.type + '.' + $selfRef.instance)
                .on('resize.cfw.' + $selfRef.type + '.' + $selfRef.instance, function() {
                    var offset = $selfRef.$target.offset();
                    if ($selfRef._isFixed()) {
                        var compStyle = window.getComputedStyle($selfRef.$target[0]);
                        offset.top = parseInt(compStyle.top, 10);
                        offset.left = parseInt(compStyle.left, 10);
                    }
                    $selfRef.locateDragTip(offset.top, offset.left);
                });
        });

        // Use top/left instead of transforms to position popover
        this.settings.gpuAcceleration = false;

        // Unset any previous drag events
        this.$target.off('.cfw.drag');

        this.$target
            .on('dragStart.cfw.drag', function(e) {
                if (e.namespace !== 'cfw.drag') { return; }
                $selfRef._updateZ();
                $selfRef.$element.CFW_trigger('dragStart.cfw.' + $selfRef.type);
            })
            .on('drag.cfw.drag', function(e) {
                if (e.namespace !== 'cfw.drag') { return; }
                $selfRef.locateDragTip(e.offsetY, e.offsetX);
            })
            .on('dragEnd.cfw.drag', function(e) {
                if (e.namespace !== 'cfw.drag') { return; }
                $selfRef.$element.CFW_trigger('dragEnd.cfw.' + $selfRef.type);
            })
            .on('keydown.cfw.drag', '[data-cfw-drag="' + this.type + '"]', function(e) {
                var KEYCODE_UP = 38;    // Arrow up
                var KEYCODE_RIGHT = 39; // Arrow right
                var KEYCODE_DOWN = 40;  // Arrow down
                var KEYCODE_LEFT = 37;  // Arrow left
                var REGEX_KEYS = new RegExp('^(' + KEYCODE_UP + '|' + KEYCODE_RIGHT + '|' + KEYCODE_DOWN + '|' + KEYCODE_LEFT + ')$');

                if (!REGEX_KEYS.test(e.which)) { return; }

                if (e) {
                    e.stopPropagation();
                    e.preventDefault();
                }

                if (!$selfRef.keyTimer) {
                    $selfRef.$element.CFW_trigger('dragStart.cfw.' + $selfRef.type);
                }

                clearTimeout($selfRef.keyTimer);

                // Mitigate most of 'slippage' by rounding offsets
                var nodeOffset = $selfRef.$target.offset();
                var offsetY = Math.round(nodeOffset.top);
                var offsetX = Math.round(nodeOffset.left);

                // If popover is 'fixed' position, use the current coords
                if ($selfRef._isFixed()) {
                    var compStyle = window.getComputedStyle($selfRef.$target[0]);
                    offsetY = parseInt(compStyle.top, 10);
                    offsetX = parseInt(compStyle.left, 10);
                }

                // Revise offset
                var step = $selfRef.settings.dragstep;
                switch (e.which) {
                    case KEYCODE_LEFT: { offsetX -= step; break; }
                    case KEYCODE_UP: { offsetY -= step; break; }
                    case KEYCODE_RIGHT: { offsetX += step; break; }
                    case KEYCODE_DOWN: { offsetY += step; break; }
                    default:
                }

                // Move it
                $selfRef.locateDragTip(offsetY, offsetX);

                $selfRef.keyTimer = setTimeout(function() {
                    $selfRef.$element.CFW_trigger('dragEnd.cfw.' + $selfRef.type);
                    $selfRef.keyTimer = null;
                }, $selfRef.keyDelay);
            });

        this.$target.CFW_Drag(dragOpt);
    };

    CFW_Widget_Popover.prototype.getParentNode = function(element) {
        if (element.nodeName === 'HTML') {
            return element;
        }
        return element.parentNode || element.host;
    };

    CFW_Widget_Popover.prototype.getScrollParent = function(element) {
        if (!element) { return document.body; }

        switch (element.nodeName) {
            case 'HTML':
            case 'BODY':
                return element.ownerDocument.body;
            case '#document':
                return element.body;
            default:
                // Nothing for default
        }

        var compStyle = window.getComputedStyle(element);
        if (/^(auto|scroll|overlay)$/.test(compStyle.overflow + compStyle.overflowX + compStyle.overflowY)) {
            return element;
        }

        return this.getScrollParent(this.getParentNode(element));
    };

    CFW_Widget_Popover.prototype.getOwnerBody = function(element) {
        var ownerDocument = element.ownerDocument;
        return ownerDocument ? ownerDocument.body : document.body;
    };

    CFW_Widget_Popover.prototype.viewportDragLimit = function() {
        var limit = {};
        var $viewport = this._getDragViewport();

        var scrollbarWidth = this.viewportScrollbarWidth($viewport);
        limit = $viewport.offset();

        // If popover is 'fixed' position
        if (this._isFixed()) {
            var rect = $viewport[0].getBoundingClientRect();
            limit.top = rect.top;
            limit.bottom = rect.bottom;

            // Use window and update limits if drag viewport is body
            if ($viewport.is('body')) {
                $viewport = $(window);
                limit.top = rect.top + window.pageYOffset;
                limit.left = rect.left + window.pageXOffset;
            }
        }

        limit.bottom = limit.top + $viewport.outerHeight();
        limit.right = limit.left + $viewport.outerWidth() - scrollbarWidth;

        // Allow dragging around entire window if body is smaller than window
        if ($viewport.is('body')) {
            if (document.body.clientHeight < window.innerHeight) {
                limit.bottom = window.innerHeight;
            }
            if (document.body.clientWidth < window.innerWidth) {
                limit.right = window.innerWidth - scrollbarWidth;
            }
        }
        return limit;
    };

    CFW_Widget_Popover.prototype.viewportScrollbarWidth = function($viewport) {
        // Check to see if a scrollbar is possible
        var compStyle = window.getComputedStyle($viewport[0]);
        var hasScrollY = /^(visible|auto|scroll)$/.test(compStyle.overflow) || /^(visible|auto|scroll)$/.test(compStyle.overflowY);
        var scrollHeight = $viewport[0].scrollHeight;

        // Return width of scrollbar if there seems to be one
        if ($viewport.is('body') && hasScrollY && scrollHeight > window.innerHeight) {
            return $.CFW_measureScrollbar();
        } else if (hasScrollY && scrollHeight > $viewport[0].clientHeight) {
            return $.CFW_measureScrollbar();
        }
        return 0;
    };

    CFW_Widget_Popover.prototype.locateDragTip = function(offsetY, offsetX) {
        var $tip = this.$target;
        var limit = this.viewportDragLimit();
        var viewportPadding = this.settings.padding;

        $tip.css({
            top: Math.min(limit.bottom - viewportPadding - $tip.outerHeight(), Math.max(limit.top + viewportPadding, offsetY)),
            left: Math.min(limit.right - viewportPadding - $tip.outerWidth(), Math.max(limit.left + viewportPadding, offsetX))
        });
    };

    CFW_Widget_Popover.prototype.hide = function(force) {
        // Fire key drag end if needed
        if (this.keyTimer) {
            this.$element.CFW_trigger('dragEnd.cfw.' + this.type);
            clearTimeout(this.keyTimer);
        }
        // Reset z-index
        this._resetZ(this.$target);
        // Call tooltip hide
        $.fn.CFW_Tooltip.Constructor.prototype.hide.call(this, force);
    };

    CFW_Widget_Popover.prototype._showExt = function() {
        if (this.$target.find('[data-cfw-drag="' + this.type + '"]').length && this._isFixed()) {
            this._handleFixedDragScroll();
        }
    };

    CFW_Widget_Popover.prototype._hideExt = function() {
        $(window)
            .off('resize.cfw.' + this.type + '.' + this.instance)
            .off('scroll.cfw.' + this.type + '.' + this.instance);
    };

    CFW_Widget_Popover.prototype._removeDynamicTipExt = function() {
        this.$target.detach();
        this.$target = null;
        this.dragAdded = false;
    };

    CFW_Widget_Popover.prototype._resetZ = function($item) {
        // Reset z-index if one is already stored
        var savedVal = $item.attr('data-cfw-zindex');
        if (typeof savedVal !== 'undefined') {
            $item.removeAttr('data-cfw-zindex');
            $item[0].style.removeProperty('z-index');
        }
    };

    CFW_Widget_Popover.prototype._updateZ = function() {
        var $selfRef = this;
        // Find highest z-indexed visible popover
        var zMax = 0;
        var $zObj = null;
        $('.popover:visible').each(function() {
            var $item = $(this);
            // Reset z-index
            $selfRef._resetZ($item);

            var zCurr = parseInt($item.css('z-index'), 10);
            if (isNaN(zCurr)) { zCurr = 0; }
            if (zCurr >= zMax) {
                zMax = zCurr;
                $zObj = $item;
            }
        });
        // Only increase if not highest
        if ($zObj && this.$target[0] !== $zObj[0]) {
            // Store
            var actualVal = this.$target.css('z-index');
            this.$target.attr('data-cfw-zindex', actualVal);
            // Update
            this.$target.css('z-index', parseInt(actualVal, 10) + 1);
        }
    };

    CFW_Widget_Popover.prototype._arrow = function() {
        if (!this.$arrow) {
            this.$arrow = this.$target.find('.arrow, .popover-arrow');
        }
        return this.$arrow;
    };

    CFW_Widget_Popover.prototype._unlinkCompleteExt = function() {
        this.dragAdded = null;
        this.keyTimer = null;
        this.keyDelay = null;
    };

    CFW_Widget_Popover.prototype._getDragViewport = function() {
        var viewport = this._getViewport();
        var $viewport = null;

        if (viewport === 'scrollParent') {
            viewport = this.getScrollParent(this.$target[0]);
        }
        if (viewport === 'window' || viewport === window) {
            viewport = this.getOwnerBody(this.$target[0]);
        }

        $viewport = $(viewport);
        if (!$viewport.length) {
            $viewport = $(document.body);
        }

        return $viewport;
    };

    CFW_Widget_Popover.prototype._isFixed = function() {
        var compStyle = window.getComputedStyle(this.$target[0]);
        return /^(fixed)$/.test(compStyle.position);
    };

    CFW_Widget_Popover.prototype._doFixedDragScroll = function() {
        var offset = {};
        var compStyle = window.getComputedStyle(this.$target[0]);
        offset.top = parseInt(compStyle.top, 10);
        offset.left = parseInt(compStyle.left, 10);
        this.locateDragTip(offset.top, offset.left);
    };

    CFW_Widget_Popover.prototype._handleFixedDragScroll = function() {
        var $viewport = this._getDragViewport();

        $(window).off('scroll.cfw.' + this.type + '.' + this.instance);

        if (!$viewport.is('body')) {
            $(window).on('scroll.cfw.' + this.type + '.' + this.instance, this._doFixedDragScroll.bind(this));
        }
    };

    var Plugin = function(option) {
        var args = [].splice.call(arguments, 1);
        return this.each(function() {
            var $this = $(this);
            var data = $this.data('cfw.popover');
            var options = typeof option === 'object' && option;

            if (!data && /unlink|dispose|hide/.test(option)) {
                return;
            }
            if (!data) {
                $this.data('cfw.popover', data = new CFW_Widget_Popover(this, options));
            }
            if (typeof option === 'string') {
                data[option].apply(data, args);
            }
        });
    };

    $.fn.CFW_Popover = Plugin;
    $.fn.CFW_Popover.Constructor = CFW_Widget_Popover;

    $.CFW_enableDismissControl('popover', 'dismiss');
}(jQuery));


text:
DROP INDEX pfRules_idx;
ALTER TABLE pfRules DROP CONSTRAINT pfRules_pk;
ALTER TABLE pfRules RENAME TO ofPfRules;
ALTER TABLE ofPfRules ADD CONSTRAINT ofPfRules_pk PRIMARY KEY (id);

UPDATE ofVersion set version=2 where name='packetfilter';


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

import com.facebook.presto.rcfile.ColumnData;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.block.BlockBuilderStatus;
import com.facebook.presto.spi.type.DecimalType;
import com.facebook.presto.spi.type.Type;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;

import java.math.BigInteger;

import static com.facebook.presto.rcfile.RcFileDecoderUtils.decodeVIntSize;
import static com.facebook.presto.rcfile.RcFileDecoderUtils.readVInt;
import static com.facebook.presto.spi.type.Decimals.encodeUnscaledValue;
import static com.facebook.presto.spi.type.Decimals.isShortDecimal;
import static com.facebook.presto.spi.type.Decimals.rescale;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.Math.toIntExact;

public class DecimalEncoding
        implements BinaryColumnEncoding
{
    private final DecimalType type;
    private final byte[] resultBytes = new byte[16];
    private final Slice resultSlice = Slices.wrappedBuffer(resultBytes);

    public DecimalEncoding(Type type)
    {
        this.type = (DecimalType) type;
    }

    @Override
    public Block decodeColumn(ColumnData columnData)
    {
        int size = columnData.rowCount();
        BlockBuilder builder = type.createBlockBuilder(new BlockBuilderStatus(), size);

        Slice slice = columnData.getSlice();
        for (int i = 0; i < size; i++) {
            int offset = columnData.getOffset(i);
            int length = columnData.getLength(i);
            if (length == 0) {
                builder.appendNull();
            }
            else if (isShortDecimal(type)) {
                type.writeLong(builder, parseLong(slice, offset));
            }
            else {
                type.writeSlice(builder, parseSlice(slice, offset));
            }
        }
        return builder.build();
    }

    @Override
    public int getValueOffset(Slice slice, int offset)
    {
        return 0;
    }

    @Override
    public int getValueLength(Slice slice, int offset)
    {
        // first vint is scale
        int scaleLength = decodeVIntSize(slice, offset);

        // second vint is data length
        int dataLengthLength = decodeVIntSize(slice, offset + scaleLength);
        int dataLength = toIntExact(readVInt(slice, offset + scaleLength));

        return scaleLength + dataLengthLength + dataLength;
    }

    @Override
    public void decodeValueInto(BlockBuilder builder, Slice slice, int offset, int length)
    {
        if (isShortDecimal(type)) {
            type.writeLong(builder, parseLong(slice, offset));
        }
        else {
            type.writeSlice(builder, parseSlice(slice, offset));
        }
    }

    private long parseLong(Slice slice, int offset)
    {
        // first vint is scale
        int scale = toIntExact(readVInt(slice, offset));
        offset += decodeVIntSize(slice, offset);

        // second vint is length
        int length = toIntExact(readVInt(slice, offset));
        offset += decodeVIntSize(slice, offset);

        checkState(length <= 8);

        // reset the results buffer
        if (slice.getByte(offset) >= 0) {
            resultSlice.setLong(0, 0L);
        }
        else {
            resultSlice.setLong(0, 0xFFFF_FFFF_FFFF_FFFFL);
        }

        resultSlice.setBytes(8 - length, slice, offset, length);

        long value = Long.reverseBytes(resultSlice.getLong(0));
        if (scale != type.getScale()) {
            return rescale(value, scale, type.getScale());
        }

        return value;
    }

    private Slice parseSlice(Slice slice, int offset)
    {
        // first vint is scale, which is ignored
        int scale = toIntExact(readVInt(slice, offset));
        offset += decodeVIntSize(slice, offset);

        // second vint is length
        int length = toIntExact(readVInt(slice, offset));
        offset += decodeVIntSize(slice, offset);

        checkState(length <= 16);

        // reset the results buffer
        if (slice.getByte(offset) >= 0) {
            resultSlice.setLong(0, 0L);
            resultSlice.setLong(8, 0L);
        }
        else {
            resultSlice.setLong(0, 0xFFFF_FFFF_FFFF_FFFFL);
            resultSlice.setLong(8, 0xFFFF_FFFF_FFFF_FFFFL);
        }

        resultSlice.setBytes(16 - length, slice, offset, length);

        if (scale != type.getScale()) {
            return encodeUnscaledValue(rescale(new BigInteger(resultBytes), scale, type.getScale()));
        }
        return resultSlice;
    }
}


text:
from setuptools import setup
from os import path

here = path.abspath(path.dirname(__file__))

setup(
    name='Sympal',
    packages=['Sympal'],
    version='0.5',
    description='Basic end user Sympa listserv management with Python requests',
    url='https://github.com/cacampbell/Sympal',
    download_url='https://github.com/cacampbell/Sympal/tarball/0.5',
    author='Chris Campbell',
    author_email='cacampbell@ucdavis.edu',
    license='MIT',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.4',
        'Programming Language :: Python :: 3.5',
    ],
    keywords='sympa listserv requests',
    install_requires=['DateTime', 'lxml', 'requests'],
)


text:
package com.googlecode.aluminumproject.templates;

import com.googlecode.aluminumproject.AluminumException;
import com.googlecode.aluminumproject.cache.Cache;
import com.googlecode.aluminumproject.configuration.Configuration;
import com.googlecode.aluminumproject.context.Context;
import com.googlecode.aluminumproject.context.ContextEnricher;
import com.googlecode.aluminumproject.parsers.Parser;
import com.googlecode.aluminumproject.utilities.Logger;
import com.googlecode.aluminumproject.writers.Writer;

import java.util.Map;

/**
 * Processes a single {@link Template template}.
 * <p>
 * All configured {@link ContextEnricher context enrichers} are given the opportunity to change the context before and
 * after the template is processed.
 */
public class TemplateProcessor {
	private Configuration configuration;

	private final Logger logger;

	/**
	 * Creates a template processor.
	 *
	 * @param configuration the configuration to use
	 */
	public TemplateProcessor(Configuration configuration) {
		this.configuration = configuration;

		logger = Logger.get(getClass());
	}

	/**
	 * Processes a template.
	 *
	 * @param name the name of the template to process
	 * @param parser the name of the parser to use
	 * @param context the context to use
	 * @param writer the writer to use
	 * @throws AluminumException when the template can't be processed
	 */
	public void processTemplate(String name, String parser, Context context, Writer writer) throws AluminumException {
		logger.debug("processing template '", name, "'");

		Template template = findTemplateInCache(name, parser);

		if (template == null) {
			template = parseTemplate(name, parser);

			storeTemplateInCache(name, parser, template);
		}

		TemplateInformation.from(context).setTemplate(template, parser);

		for (ContextEnricher contextEnricher: configuration.getContextEnrichers()) {
			contextEnricher.beforeTemplate(context);
		}

		for (TemplateElement templateElement: template.getChildren(null)) {
			templateElement.process(context, writer);
		}

		for (ContextEnricher contextEnricher: configuration.getContextEnrichers()) {
			contextEnricher.afterTemplate(context);
		}

		logger.debug("finished processing template '", name, "'");
	}

	private Template findTemplateInCache(String name, String parser) throws AluminumException {
		Template template;

		Cache cache = configuration.getCache();

		if (cache == null) {
			logger.debug("no cache configured, can't find template");

			template = null;
		} else {
			logger.debug("finding template in cache");

			template = cache.findTemplate(new Cache.Key(name, parser));
		}

		return template;
	}

	private void storeTemplateInCache(String name, String parser, Template template) throws AluminumException {
		Cache cache = configuration.getCache();

		if (cache == null) {
			logger.debug("no cache configured, can't store template");
		} else {
			logger.debug("storing template in cache");

			cache.storeTemplate(new Cache.Key(name, parser), template);
		}
	}

	private Template parseTemplate(String name, String parser) throws AluminumException {
		logger.debug("parsing template '", name, "' with parser '", parser, "'");

		Map<String, Parser> parsers = configuration.getParsers();

		if (parsers.containsKey(parser)) {
			return parsers.get(parser).parseTemplate(name);
		} else {
			throw new AluminumException("unknown parser: ", parser);
		}
	}
}


text:
package com.unifonic.sdk.resources.url;

public interface IMessageUrl {
	public static final String PATH_MESSAGE = "Messages/";

	public String urlSend();

	public String urlSendBulk();

	public String urlGetMessageIDStatus();

	public String urlGetMessageReport();

	public String urlGetMessageDetails();
}


text:
"""composite primary key port ip association

Revision ID: 3b467be51e43
Revises: 26e984b48a0d
Create Date: 2014-10-09 15:42:58.104964

"""

# revision identifiers, used by Alembic.
revision = '3b467be51e43'
down_revision = '26e984b48a0d'

import contextlib
import itertools

from alembic import op
import sqlalchemy as sa

def _drop_foreign_key(op, table, fk):
    op.drop_constraint(fk.name, table.name, type_="foreignkey")

def _create_foreign_key(op, table, fk):
    ref_tbl_name = fk.column.table.name
    ref_tbl_col = fk.column.name
    op.create_foreign_key(fk.name, table.name, ref_tbl_name,
                          [fk.parent.name], [ref_tbl_col])

def _alter_foreign_keys(op, table, action, fk_constraints):
    actions = {
        "drop": _drop_foreign_key,
        "create": _create_foreign_key
    }
    # NOTE(thomasem): Flatten list of ForeignKeys we want to work on from the
    # ForeignKeyConstraint objects that may contain multiple ForeignKey
    # objects.
    [actions[action](op, table, fk) for fk
     in itertools.chain.from_iterable([c.elements for c in fk_constraints])]

@contextlib.contextmanager
def _foreign_keys_dropped(op, table):
    fk_constraints = [c for c in table.constraints
                      if isinstance(c, sa.schema.ForeignKeyConstraint)]
    _alter_foreign_keys(op, table, "drop", fk_constraints)
    yield
    _alter_foreign_keys(op, table, "create", fk_constraints)

def upgrade():
    metadata = sa.MetaData(bind=op.get_bind())
    table = sa.Table('quark_port_ip_address_associations', metadata,
                     autoload=True)
    with _foreign_keys_dropped(op, table):
        op.alter_column('quark_port_ip_address_associations', 'ip_address_id',
                        existing_type=sa.String(36), nullable=False)
        op.alter_column('quark_port_ip_address_associations', 'port_id',
                        existing_type=sa.String(36), nullable=False)
        op.create_primary_key("pk_quark_port_ip_address_associations",
                              "quark_port_ip_address_associations",
                              ['port_id', 'ip_address_id'])

def downgrade():
    metadata = sa.MetaData(bind=op.get_bind())
    table = sa.Table('quark_port_ip_address_associations', metadata,
                     autoload=True)
    # NOTE(thomasem): Unfortunately we cannot remove primary keys for columns
    # that have a ForeignKeyConstraint defined. So, we can temporarily remove
    # them and add them back as soon as the PrimaryKeyConstraint is removed.
    with _foreign_keys_dropped(op, table):
        op.drop_constraint("pk_quark_port_ip_address_associations",
                           "quark_port_ip_address_associations",
                           type_="primary")
        op.alter_column('quark_port_ip_address_associations', 'port_id',
                        existing_type=sa.String(36), nullable=True)
        op.alter_column('quark_port_ip_address_associations', 'ip_address_id',
                        existing_type=sa.String(36), nullable=True)


text:
<?php

global $_MODULE;
$_MODULE = array();
$_MODULE['<{statslive}cars>statslive_fa55230e9791f2b71322869318a5f00f'] = 'Visitors online';
$_MODULE['<{statslive}cars>statslive_abf306fd198ab007d480ed610a6690fb'] = 'Adds a list of customers and visitors who are currently online to the Stats dashboard.';
$_MODULE['<{statslive}cars>statslive_85f955e33756b8f40ce35e5b277de5bc'] = 'You must activate the \"Save page views for each customer\" option in the \"Data mining for statistics\" (StatsData) module in order to see the pages that your visitors are currently viewing.';
$_MODULE['<{statslive}cars>statslive_f5ee3b50dba1fb98f1342a584e46cd30'] = 'Current online customers';
$_MODULE['<{statslive}cars>statslive_66c4c5112f455a19afde47829df363fa'] = 'Total:';
$_MODULE['<{statslive}cars>statslive_d37c2bf1bd3143847fca087b354f920e'] = 'Customer ID';
$_MODULE['<{statslive}cars>statslive_49ee3087348e8d44e1feda1917443987'] = 'Name';
$_MODULE['<{statslive}cars>statslive_13aa8652e950bb7c4b9b213e6d8d0dc5'] = 'Current page';
$_MODULE['<{statslive}cars>statslive_9dd3bc54879dc9425d44de81f3d7dfdc'] = 'View customer profile';
$_MODULE['<{statslive}cars>statslive_08448d43d8e4b39ad5126d4b06e2f3cc'] = 'There are no active customers online right now.';
$_MODULE['<{statslive}cars>statslive_cf6377279146be659952cea754c558b1'] = 'Current online visitors';
$_MODULE['<{statslive}cars>statslive_f8cf0a1a6b03d2b01602992ea273134c'] = 'Guest ID';
$_MODULE['<{statslive}cars>statslive_a12a3079e14ced46e69ba52b8a90b21a'] = 'IP';
$_MODULE['<{statslive}cars>statslive_bc5188ca43d423ba3730e4c030609d6e'] = 'Last activity';
$_MODULE['<{statslive}cars>statslive_b6f05e5ddde1ec63d992d61144452dfa'] = 'Referrer';
$_MODULE['<{statslive}cars>statslive_ec0fc0100c4fc1ce4eea230c3dc10360'] = 'Undefined';
$_MODULE['<{statslive}cars>statslive_6adf97f83acf6453d4a6a4b1070f3754'] = 'None';
$_MODULE['<{statslive}cars>statslive_a55533db46597bee3cd16899c007257e'] = 'There are no visitors online.';
$_MODULE['<{statslive}cars>statslive_24efa7ee4511563b16144f39706d594f'] = 'Notice';
$_MODULE['<{statslive}cars>statslive_e5900cd9ae26ca607f7cd497f114b9f9'] = 'Maintenance IPs are excluded from the online visitors.';
$_MODULE['<{statslive}cars>statslive_05b564d49dbd9049f0df80a45cfe7d1c'] = 'Add or remove an IP address.';


text:
class CreateAdvancedSearchConfigurations < ActiveRecord::Migration[5.2]
  def change
    create_table :advanced_search_configurations do |t|
      t.belongs_to :item_type, index: true, foreign_key: true
      t.belongs_to :catalog, index: true, foreign_key: true
      t.integer :creator_id
      t.jsonb :title_translations
      t.jsonb :description
      t.string :slug, index: true
      t.string :search_type, default: "default"
      t.jsonb :fields, default: {}

      t.timestamps null: false
    end
  end
end


text:
'use strict'

const createNode = require('./create-node')

async function main () {
  const ipfs = await createNode()

  console.log('\nStart of the example:')

  const myData = {
    name: 'David',
    likes: ['js-ipfs', 'icecream', 'steak']
  }

  const cid = await ipfs.dag.put(myData, { format: 'dag-cbor', hashAlg: 'sha2-256' })
  const result = await ipfs.dag.get(cid)

  console.log(JSON.stringify(result.value))
}

main()


text:
import { DirectiveOptions } from 'vue';
import { Screen } from '../screen/screen-service';

export const AppFocusWhen: DirectiveOptions = {
	bind: (el: HTMLElement, binding) => {
		if (Screen.isMobile) {
			return;
		}

		if (
			(binding.value && binding.value !== binding.oldValue) ||
			(typeof binding.value === 'undefined' && el.dataset.appFocusWhen !== 'focused')
		) {
			setTimeout(() => {
				el.focus();
				el.dataset.appFocusWhen = 'focused';
			});
		}
	},
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>Hex</title>

  <link rel="stylesheet" type="text/css" href="/assets/css/style.css" />


text:
Php mapping is Php provided by the domain object itself:
```php
class Keyboard
{
    public static function loadMapping()
    {
        return [
            'fields' => [
                'brand' => [
                    'readConverter' => 'readBrand',
                    'writeConverter' => 'writeBrand',
                ],
                'color', //this field hasn't got specific configuration but we want the mapper manage it
                'createdDate' => [
                    'name' => 'created_date',
                    'type' => 'date',
                    'readDateConverter' => 'Y-m-d H:i:s',
                    'writeDateConverter' => 'Y-m-d H:i:s',
                ],
                'waterProof' => [
                    'readConverter' => 'hydrateBool',
                    'writeConverter' => 'extractBool',
                    'getter' => ['prefix' => 'is'], //Type of getter. "get" for getter (default value), "is" for isser, "has" for hasser.
                ],
                'stopWatch' => [
                    'readConverter' => 'hydrateBoolFromSymbol',
                    'writeConverter' => 'extractBoolToSymbol',
                    'mappingExtensionClass' => 'WatchCallbacks',
                ],
                'customizable' => [
                    'readConverter': 'hydrateBool',
                    'writeConverter': 'extractBool',
                    'getter': 'canBeCustomized', //Getter name for property customizable.
                ],
            ],
            'processors' => [
                'preHydrate' => [
                    ['class'=> 'SomeClass', 'method' => 'onBeforeHydrate'],
                ],
                'postHydrate' => [
                    ['class' => 'SomeClass', 'method' => 'onAfterHydrate', 'args' => ['foo', 123]],
                ]
                'preExtract' => [
                    ['class' => 'SomeClassA', 'method' => 'onBeforeExtract'],
                    ['class' => 'SomeClassB', 'method' => 'onBeforeExtract', 'args' => ['foo', 123]],
                ],
                'postExtract' => [
                    ['class' => 'SomeClass', 'method' => 'onAfterExtractA'],
                    ['class' => 'SomeClass', 'method' => 'onAfterExtractB', 'args' => ['foo', 123]],
                ],
            ],
        ],
    }
}

//Fields sealDate and noSealDate don't appear in the field section because we don't want the mapper manage them.

```

"loadMapping" is the default provider method name but it can be changed:

Api configuration usage:
```php
$configuration->setDefaultClassMetadataProviderMethod('someMappingLoaderMethod');//<= for all domain objects

//or

$configuration->addClassMetadataProviderMethod('Kassko\Sample\Watch', 'myLoadMapping');//<= only for Watch objects
```

[see Php mapping reference documentation](https://github.com/kassko/data-mapper/blob/master/Resources/doc/php_file_mapping.md) for more details on Php mapping.


text:
All commands must use `class: "chat"`.

**Events**

Many commands generate events that the client can subscribe to. See description for each command.

### User Commands

Use subclass `user`.

#### create

Use command `create`. Supported fields are

Field|Desc
---|---
`login`|Login to use (email-like)
`name`|Name of the user
`surname`|Surname
`password`|Password

The sever will return the newly created `user_id`.

Example:

```javascript
{
    class: "chat",
    subclass: "user",
    cmd: "create",
    data: {
        login: "user@domain.com",
        name: "Name",
        surname: "Surname",
        password: "1234"
    },
    tid: 1
}

-->

{
    result: "ok",
    data: {
        user_id: "59c03l30ddlekvd93"
    },
    tid: 1
}
```

It generates the following **event**:

Field|Value
---|---
subclass|`user`
type|`created`
obj_id|The user's id

#### get

Use command `get` and field `user_id`

#### delete

Use command `delete` to remove and user. Must use the field `user_id`.

**Event**

Field|Value
---|---
subclass|`user`
type|`deleted`
obj_id|The user's id

#### search

Use command `search` to find users. The following fields are available:

Field|Desc
---|---
`fields`|List of fields to include in the response. Use `"_all"` to get _all_ fields
`filter`|Filter to apply to the response (for example, `{field1:"value1", field2:"value2"}`
`size`|Numer of objects to return
`from`|Position to start returning objects (starts at 0)
`sort_by`|List of fields to sort on
`sort_order`|Sort order (`"asc"` or `"desc"`)

### Conversation Commands

Use subclass `conversation`

#### create

Use command `create` to create a new conversation. Supported fields are:

Field|Desc
---|---
`name`|Short name for the conversation
`description`|Description
`user_ids`|initial list of users

The sever will return the newly created `conversation_id`.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`created`
obj_id|The conversation's id

#### get

Use command `get` and field `conversation_id`

#### delete

Use command `delete`, and field `conversation_id`.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`deleted`
obj_id|The conversation's id

#### add_members

Use command `add_members` to add users to a conversation. Must set the `conversation_id` field and the list of users in the field `user_ids`.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`added_memebers`
obj_id|The conversation's id
body|Includes field `user_ids`

#### remove_members

Use command `remove_members` to remove users from a conversation. Must set the `conversation_id` field and the list of users in the field `user_ids`.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`removed_memebers`
obj_id|The conversation's id
body|Includes field `user_ids`

#### get_members

Use command `get_members` to get the list of users from a conversation. Must set the field `conversation_id`.

#### search

Use command `search` to find conversations. Use the same fields as for [user search](#search).

### Message Commands

Use subclass `message`

#### create

Use command `create` to create a new message. Supported fields are:

Field|Desc
---|---
`conversation_id`|Id of the conversation
`user_id`|User creating the message
`message`|Text of the message

The sever will return the newly created `message_id`.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`created_message`
obj_id|The conversation's id
body|Includes field `message_id`

#### get

Use command `get` and field `message_id`.

#### delete

Use command `delete`, and fields `conversation_id` and `message_id`.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`deleted_message`
obj_id|The conversation's id
body|Includes field `message_id`

#### update

Use command `update`, and fields `conversation_id`, `message_id` and `message` to update message's content.

**Event**

Field|Value
---|---
subclass|`conversation`
type|`updated_message`
obj_id|The conversation's id
body|Includes field `message_id`

#### search

Use command `search` to find messages. Use the same fields as for [user search](#search).


text:
<?php

/* This plugin makes call to master node, get the jmx-json document
 * It checks the rpc wait time in the queue, RpcQueueTime_avg_time
 * check_rpcq_latency -h hostaddress -p port -t ServiceName -w 1 -c 1
 * Warning and Critical values are in seconds
 * Service Name = JobTracker, NameNode, JobHistoryServer
 */

  include "hdp_nagios_init.php";

  $options = getopt ("h:p:w:c:n:e:k:r:t:s:");
  if (!array_key_exists('h', $options) || !array_key_exists('p', $options) || !array_key_exists('w', $options)
      || !array_key_exists('c', $options) || !array_key_exists('n', $options)) {
    usage();
    exit(3);
  }

  $host=$options['h'];
  $port=$options['p'];
  $master=$options['n'];
  $warn=$options['w'];
  $crit=$options['c'];
  $keytab_path=$options['k'];
  $principal_name=$options['r'];
  $kinit_path_local=$options['t'];
  $security_enabled=$options['s'];
  $ssl_enabled=$options['e'];

  /* Kinit if security enabled */
  $status = kinit_if_needed($security_enabled, $kinit_path_local, $keytab_path, $principal_name);
  $retcode = $status[0];
  $output = $status[1];

  if ($output != 0) {
    echo "CRITICAL: Error doing kinit for nagios. $output";
    exit (2);
  }

  $protocol = ($ssl_enabled == "true" ? "https" : "http");

  /* Get the json document */
  $ch = curl_init();
  $username = rtrim(`id -un`, "\n");
  curl_setopt_array($ch, array( CURLOPT_URL => $protocol."://".$host.":".$port."/jmx?qry=Hadoop:service=".$master.",name=RpcActivityForPort*",
                                CURLOPT_RETURNTRANSFER => true,
                                CURLOPT_HTTPAUTH => CURLAUTH_ANY,
                                CURLOPT_USERPWD => "$username:",
                                CURLOPT_SSL_VERIFYPEER => FALSE ));
  $json_string = curl_exec($ch);
  $info = curl_getinfo($ch);
  if (intval($info['http_code']) == 401){
    logout();
    $json_string = curl_exec($ch);
  }
  $info = curl_getinfo($ch);
  curl_close($ch);
  $json_array = json_decode($json_string, true);
  $object = $json_array['beans'][0];
  if (count($object) == 0) {
    echo "CRITICAL: Data inaccessible, Status code = ". $info['http_code'] ."\n";
    exit(2);
  }
  $RpcQueueTime_avg_time = round($object['RpcQueueTime_avg_time'], 2);
  $RpcProcessingTime_avg_time = round($object['RpcProcessingTime_avg_time'], 2);

  $out_msg = "RpcQueueTime_avg_time:<" . $RpcQueueTime_avg_time .
             "> Secs, RpcProcessingTime_avg_time:<" . $RpcProcessingTime_avg_time .
             "> Secs";

  if ($RpcQueueTime_avg_time >= $crit) {
    echo "CRITICAL: " . $out_msg . "\n";
    exit (2);
  }
  if ($RpcQueueTime_avg_time >= $warn) {
    echo "WARNING: " . $out_msg . "\n";
    exit (1);
  }
  echo "OK: " . $out_msg . "\n";
  exit(0);

  /* print usage */
  function usage () {
    echo "Usage: $0 -h <host> -p port -n <JobTracker/NameNode/JobHistoryServer> -w <warn_in_sec> -c <crit_in_sec> -k keytab path -r principal name -t kinit path -s security enabled -e ssl enabled\n";
  }
?>