text:
package appium.tutorial.ios.page;

import io.appium.java_client.MobileBy;

import static appium.tutorial.ios.util.Helpers.element;

/** Page object for the buttons page **/
public abstract class ButtonsPage {

    /** Verify the buttons page has loaded **/
    public static void loaded() {
        element(MobileBy.AccessibilityId("Buttons"));
    }
}


text:
#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

#include "libtorrent/aux_/disable_warnings_push.hpp"

#ifdef TORRENT_PRODUCTION_ASSERTS
#include <boost/atomic.hpp>
#endif

#if TORRENT_USE_ASSERTS \
	|| defined TORRENT_ASIO_DEBUGGING \
	|| defined TORRENT_PROFILE_CALLS \
	|| defined TORRENT_DEBUG_BUFFERS

#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif

#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdarg>
#include <cstdio> // for snprintf
#include <boost/array.hpp>

#include "libtorrent/aux_/disable_warnings_pop.hpp"

// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
	&& !defined __UCLIBCXX_MAJOR__

#include <cxxabi.h>

std::string demangle(char const* name)
{
// in case this string comes
	// this is needed on linux
	char const* start = strchr(name, '(');
	if (start != NULL)
	{
		++start;
	}
	else
	{
		// this is needed on macos x
		start = strstr(name, "0x");
		if (start != NULL)
		{
			start = strchr(start, ' ');
			if (start != NULL) ++start;
			else start = name;
		}
		else start = name;
	}

	char const* end = strchr(start, '+');
	if (end) while (*(end-1) == ' ') --end;

	std::string in;
	if (end == NULL) in.assign(start);
	else in.assign(start, end);

	size_t len;
	int status;
	char* unmangled = ::abi::__cxa_demangle(in.c_str(), NULL, &len, &status);
	if (unmangled == NULL) return in;
	std::string ret(unmangled);
	free(unmangled);
	return ret;
}
#elif defined _WIN32

#include "windows.h"
#include "dbghelp.h"

std::string demangle(char const* name)
{
	char demangled_name[256];
	if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0)
		demangled_name[0] = 0;
	return demangled_name;
}

#else
std::string demangle(char const* name) { return name; }
#endif

#include <cstdlib>
#include <cstdio>
#include <csignal>
#include "libtorrent/version.hpp"

#if TORRENT_USE_EXECINFO
#include <execinfo.h>

TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth, void*)
{
	void* stack[50];
	int size = backtrace(stack, 50);
	char** symbols = backtrace_symbols(stack, size);

	for (int i = 1; i < size && len > 0; ++i)
	{
		int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
		out += ret;
		len -= ret;
		if (i - 1 == max_depth && max_depth > 0) break;
	}

	free(symbols);
}

#elif defined _WIN32

#include "windows.h"
#include "libtorrent/utf8.hpp"
#include "libtorrent/thread.hpp"

#include "winbase.h"
#include "dbghelp.h"

TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth
	, void* ctx)
{
	// all calls to DbgHlp.dll are thread-unsafe. i.e. they all need to be
	// synchronized and not called concurrently. This mutex serializes access
	static libtorrent::mutex dbghlp_mutex;
	libtorrent::mutex::scoped_lock l(dbghlp_mutex);

	CONTEXT context_record;
	if (ctx)
	{
		context_record = *static_cast<CONTEXT*>(ctx);
	}
	else
	{
		// use the current thread's context
		RtlCaptureContext(&context_record);
	}

	int size = 0;
	boost::array<void*, 50> stack;

	STACKFRAME64 stack_frame;
	memset(&stack_frame, 0, sizeof(stack_frame));
#if defined(_WIN64)
	int const machine_type = IMAGE_FILE_MACHINE_AMD64;
	stack_frame.AddrPC.Offset = context_record.Rip;
	stack_frame.AddrFrame.Offset = context_record.Rbp;
	stack_frame.AddrStack.Offset = context_record.Rsp;
#else
	int const machine_type = IMAGE_FILE_MACHINE_I386;
	stack_frame.AddrPC.Offset = context_record.Eip;
	stack_frame.AddrFrame.Offset = context_record.Ebp;
	stack_frame.AddrStack.Offset = context_record.Esp;
#endif
	stack_frame.AddrPC.Mode = AddrModeFlat;
	stack_frame.AddrFrame.Mode = AddrModeFlat;
	stack_frame.AddrStack.Mode = AddrModeFlat;
	while (StackWalk64(machine_type,
		GetCurrentProcess(),
		GetCurrentThread(),
		&stack_frame,
		&context_record,
		NULL,
		&SymFunctionTableAccess64,
		&SymGetModuleBase64,
		NULL) && size < stack.size())
	{
		stack[size++] = reinterpret_cast<void*>(stack_frame.AddrPC.Offset);
	}

	struct symbol_bundle : SYMBOL_INFO
	{
		wchar_t name[MAX_SYM_NAME];
	};

	HANDLE p = GetCurrentProcess();
	static bool sym_initialized = false;
	if (!sym_initialized)
	{
		sym_initialized = true;
		SymInitialize(p, NULL, true);
	}
	SymRefreshModuleList(p);
	for (int i = 0; i < size && len > 0; ++i)
	{
		DWORD_PTR frame_ptr = reinterpret_cast<DWORD_PTR>(stack[i]);

		DWORD64 displacement = 0;
		symbol_bundle symbol;
		symbol.MaxNameLen = MAX_SYM_NAME;
		symbol.SizeOfStruct = sizeof(SYMBOL_INFO);
		BOOL const has_symbol = SymFromAddr(p, frame_ptr, &displacement, &symbol);

		DWORD line_displacement = 0;
		IMAGEHLP_LINE64 line = {};
		line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
		BOOL const has_line = SymGetLineFromAddr64(GetCurrentProcess(), frame_ptr,
			&line_displacement, &line);

		int ret = snprintf(out, len, "%2d: %p", i, stack[i]);
		out += ret; len -= ret; if (len <= 0) break;

		if (has_symbol)
		{
			ret = snprintf(out, len, " %s +%-4" PRId64
				, demangle(symbol.Name).c_str(), displacement);
			out += ret; len -= ret; if (len <= 0) break;
		}

		if (has_line)
		{
			ret = snprintf(out, len, " %s:%d"
				, line.FileName, line.LineNumber);
			out += ret; len -= ret; if (len <= 0) break;
		}

		ret = snprintf(out, len, "\n");
		out += ret;
		len -= ret;

		if (i == max_depth && max_depth > 0) break;
	}
}

#else

TORRENT_EXPORT void print_backtrace(char* out, int len, int /*max_depth*/, void* /* ctx */)
{
	out[0] = 0;
	strncat(out, "<not supported>", len);
}

#endif

#endif

#if TORRENT_USE_ASSERTS || defined TORRENT_ASIO_DEBUGGING

#ifdef TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
namespace {
// the number of asserts we've printed to the log
boost::atomic<int> assert_counter(0);
}
#endif

TORRENT_FORMAT(1,2)
TORRENT_EXPORT void assert_print(char const* fmt, ...)
{
#ifdef TORRENT_PRODUCTION_ASSERTS
	if (assert_counter > 500) return;

	FILE* out = fopen(libtorrent_assert_log, "a+");
	if (out == 0) out = stderr;
#else
	FILE* out = stderr;
#endif
	va_list va;
	va_start(va, fmt);
	vfprintf(out, fmt, va);
	va_end(va);

#ifdef TORRENT_PRODUCTION_ASSERTS
	if (out != stderr) fclose(out);
#endif
}

// we deliberately don't want asserts to be marked as no-return, since that
// would trigger warnings in debug builds of any code coming after the assert
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#endif

TORRENT_EXPORT void assert_fail(char const* expr, int line
	, char const* file, char const* function, char const* value, int kind)
{
#ifdef TORRENT_PRODUCTION_ASSERTS
	// no need to flood the assert log with infinite number of asserts
	if (assert_counter.fetch_add(1) + 1 > 500) return;
#endif

	char stack[8192];
	stack[0] = '\0';
	print_backtrace(stack, sizeof(stack), 0);

	char const* message = "assertion failed. Please file a bugreport at "
		"https://github.com/arvidn/libtorrent/issues\n"
		"Please include the following information:\n\n"
		"version: " LIBTORRENT_VERSION "-" LIBTORRENT_REVISION "\n";

	switch (kind)
	{
		case 1:
			message = "A precondition of a libtorrent function has been violated.\n"
				"This indicates a bug in the client application using libtorrent\n";
	}

	assert_print("%s\n"
#ifdef TORRENT_PRODUCTION_ASSERTS
		"#: %d\n"
#endif
		"file: '%s'\n"
		"line: %d\n"
		"function: %s\n"
		"expression: %s\n"
		"%s%s\n"
		"stack:\n"
		"%s\n"
		, message
#ifdef TORRENT_PRODUCTION_ASSERTS
		, assert_counter.load()
#endif
		, file, line, function, expr
		, value ? value : "", value ? "\n" : ""
		, stack);

	// if production asserts are defined, don't abort, just print the error
#ifndef TORRENT_PRODUCTION_ASSERTS
	// send SIGINT to the current process
	// to break into the debugger
	raise(SIGABRT);
	abort();
#endif
}

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#elif !TORRENT_USE_ASSERTS

// these are just here to make it possible for a client that built with debug
// enable to be able to link against a release build (just possible, not
// necessarily supported)
TORRENT_FORMAT(1,2)
TORRENT_EXPORT void assert_print(char const*, ...) {}
TORRENT_EXPORT void assert_fail(char const*, int, char const*
	, char const*, char const*, int) {}

#endif

redpajama_set_name: RedPajamaGithub


text:
echo "AWS Lambda Update"
zip -9r ZipFiles/upload.zip passwd.txt lambda_function.py requests/* requests-2.11.1.dist-info/*
aws lambda update-function-code --function-name arn:aws:lambda:eu-west-1:834695880484:function:jarvistest --zip-file fileb://ZipFiles/upload.zip --region eu-west-1
rm ZipFiles/upload.zip
echo "Done!!"


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.
 */

(function() {
  'use strict';

  describe("cinderExtensions", function() {
    var factory, q, cinderAPI;

    beforeEach(module('horizon.app.core.openstack-service-api'));

    beforeEach(module(function($provide) {
      cinderAPI = {getExtensions: function() {return {then: angular.noop};}};
      q = {defer: function() { return {resolve: angular.noop}; }};
      $provide.value('$cacheFactory', function() {return "cache";});
      $provide.value('$q', q);
      $provide.value('horizon.app.core.openstack-service-api.cinder', cinderAPI);
    }));

    beforeEach(inject(function($injector) {
      factory = $injector.get('horizon.app.core.openstack-service-api.cinderExtensions');
    }));

    it("is defined", function() {
      expect(factory).toBeDefined();
    });

    it("defines .cache", function() {
      expect(factory.cache).toBeDefined();
    });

    it("defines .get", function() {
      expect(factory.get).toBeDefined();
      var postAction = {then: angular.noop};
      spyOn(cinderAPI, 'getExtensions').and.returnValue(postAction);
      spyOn(postAction, 'then');
      factory.get();
      expect(cinderAPI.getExtensions).toHaveBeenCalledWith({cache: factory.cache});
      expect(postAction.then).toHaveBeenCalled();
      var func = postAction.then.calls.argsFor(0)[0];
      var testData = {data: {items: [1, 2, 3]}};
      expect(func(testData)).toEqual([1, 2, 3]);
    });

    it("defines .ifNameEnabled", function() {
      expect(factory.ifNameEnabled).toBeDefined();
      var postAction = {then: angular.noop};
      var deferred = {reject: angular.noop, resolve: angular.noop};
      spyOn(q, 'defer').and.returnValue(deferred);
      spyOn(factory, 'get').and.returnValue(postAction);
      spyOn(postAction, 'then');
      factory.ifNameEnabled("desired");
      expect(factory.get).toHaveBeenCalled();
      var func1 = postAction.then.calls.argsFor(0)[0];
      var func2 = postAction.then.calls.argsFor(0)[1];
      spyOn(deferred, 'reject');
      func1();
      expect(deferred.reject).toHaveBeenCalled();

      spyOn(deferred, 'resolve');
      var extensions = [{name: "desired"}];
      func1(extensions);
      expect(deferred.resolve).toHaveBeenCalled();

      deferred.reject.calls.reset();
      func2();
      expect(deferred.reject).toHaveBeenCalledWith('Cannot get the extension list.');
    });

  });

})();


text:
<?php

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property string $AddressLine1
 * @property string $AddressLine2
 * @property \DTS\eBaySDK\Trading\Enums\AddressTypeCodeType $AddressType
 * @property string $City
 * @property integer $Latitude
 * @property integer $Longitude
 * @property string $State
 * @property string $ZipCode
 */
class NonProfitAddressType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = array(
        'AddressLine1' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'AddressLine1'
        ),
        'AddressLine2' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'AddressLine2'
        ),
        'AddressType' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'AddressType'
        ),
        'City' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'City'
        ),
        'Latitude' => array(
            'type' => 'integer',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'Latitude'
        ),
        'Longitude' => array(
            'type' => 'integer',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'Longitude'
        ),
        'State' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'State'
        ),
        'ZipCode' => array(
            'type' => 'string',
            'unbound' => false,
            'attribute' => false,
            'elementName' => 'ZipCode'
        )
    );

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = array())
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'urn:ebay:apis:eBLBaseComponents';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
//========================================================================
//Copyright 2007-2008 David Yu dyuproject@gmail.com
//------------------------------------------------------------------------
//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.dyuproject.demos.todolist.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jra.Get;
import org.codehaus.jra.HttpResource;
import org.codehaus.jra.Post;

import com.dyuproject.demos.todolist.Constants;
import com.dyuproject.demos.todolist.Feedback;
import com.dyuproject.demos.todolist.dao.CredentialDao;
import com.dyuproject.demos.todolist.dao.TodoDao;
import com.dyuproject.demos.todolist.model.Credential;
import com.dyuproject.demos.todolist.model.User;
import com.dyuproject.web.CookieSession;
import com.dyuproject.web.rest.RequestContext;
import com.dyuproject.web.rest.WebContext;
import com.dyuproject.web.rest.service.AbstractService;

/**
 * @author David Yu
 * @created Dec 6, 2008
 */

public class MainService extends AbstractService
{

    private TodoDao _todoDao;
    private CredentialDao _credentialDao;

    @Override
    protected void init()
    {
        _todoDao = (TodoDao)getWebContext().getAttribute("todoDao");
        _credentialDao = (CredentialDao)getWebContext().getAttribute("credentialDao");
    }

    @HttpResource(location="/")
    @Get
    public void root(RequestContext rc) throws IOException, ServletException
    {
        rc.getResponse().setContentType(Constants.TEXT_HTML);
        getWebContext().getJSPDispatcher().dispatch("index.jsp", rc.getRequest(), rc.getResponse());
    }

    @HttpResource(location="/auth")
    @Post
    public void auth(RequestContext rc) throws IOException, ServletException
    {
        HttpServletRequest request = rc.getRequest();
        HttpServletResponse response = rc.getResponse();

        String username = request.getParameter(Constants.USERNAME);
        String password = request.getParameter(Constants.PASSWORD);

        if(username==null || password==null)
        {
            request.setAttribute(Constants.MSG, Feedback.AUTH_REQUIRED.getMsg());
            response.setContentType(Constants.TEXT_HTML);
            getWebContext().getJSPDispatcher().dispatch("login/index.jsp", request, response);
            return;
        }
        Credential credential = _credentialDao.get(username, password);
        if(credential==null)
        {
            request.setAttribute(Constants.MSG, Feedback.USER_NOT_FOUND.getMsg());
            dispatchToLogin(rc, getWebContext());
            return;
        }
        User user = credential.getUser();
        saveUser(user, rc, getWebContext());
        redirectToOverview(rc, getWebContext());
    }

    @HttpResource(location="/login")
    @Get
    public void login(RequestContext rc) throws IOException, ServletException
    {
        if(getUser(rc, getWebContext())!=null)
            rc.getResponse().sendRedirect(rc.getRequest().getContextPath() + "/overview");
        else
            dispatchToLogin(rc, getWebContext());
    }

    @HttpResource(location="/logout")
    @Get
    public void logout(RequestContext rc) throws IOException
    {
        getWebContext().invalidateSession(rc.getResponse());
        redirectToOverview(rc, getWebContext());
    }

    @HttpResource(location="/overview")
    @Get
    public void overview(RequestContext rc) throws IOException, ServletException
    {
        HttpServletRequest request = rc.getRequest();

        User user = getUser(rc, getWebContext());
        request.setAttribute(Constants.USER, user);
        request.setAttribute(Constants.TODOS, _todoDao.getByUser(user.getId()));
        dispatchToOverview(rc, getWebContext());
    }

    /* ============================================================================= */

    static void dispatchToLogin(RequestContext rc, WebContext wc)
    throws ServletException, IOException
    {
        rc.getResponse().setContentType(Constants.TEXT_HTML);
        wc.getJSPDispatcher().dispatch("login/index.jsp", rc.getRequest(), rc.getResponse());
    }

    static void dispatchToOverview(RequestContext rc, WebContext wc)
    throws ServletException, IOException
    {
        rc.getResponse().setContentType(Constants.TEXT_HTML);
        wc.getJSPDispatcher().dispatch("overview/index.jsp", rc.getRequest(), rc.getResponse());
    }

    static void redirectToOverview(RequestContext rc, WebContext wc) throws IOException
    {
        rc.getResponse().sendRedirect(rc.getRequest().getContextPath() + "/overview");
    }

    static void redirectToLogin(RequestContext rc) throws IOException
    {
        rc.getResponse().sendRedirect(rc.getRequest().getContextPath() + "/login");
    }

    static User getUser(RequestContext rc, WebContext wc)
    {
        CookieSession session = wc.getSession(rc.getRequest());
        return session==null ? null : (User)session.getAttribute(Constants.USER);
    }

    static void saveUser(User user, RequestContext rc, WebContext wc) throws IOException
    {
        HttpServletRequest request = rc.getRequest();
        CookieSession session = wc.getSession(request, true);
        session.setAttribute(Constants.USER, user);
        wc.persistSession(session, request, rc.getResponse());
    }

}


text:
module.exports = function (grunt) {
    "use strict";

    var stringEscape = require('jsesc');

    grunt.registerMultiTask('json_html_template', 'create an object of all templates', function () {
        var src = this.data.src,
            templates = grunt.file.expand(this.data.templates),
            dest = this.data.dest,
            done = this.async(),
            file = grunt.file.read(src),
            js;
        grunt.jsTemplate = {};

        templates.forEach(function (f) {
            if(/\./.test(file)){
                var afiles = f.split('/');
                grunt.log.write('✔ '.green + 'Adding property: '+afiles[afiles.length - 1].split('.')[0]+' with the value of '+f+'\n');
                grunt.jsTemplate[afiles[afiles.length - 1].split('.')[0]] = stringEscape(grunt.file.read(f), {json:true});
            }
        });
        js = grunt.template.process(file);
        grunt.log.write('✔ '.green + 'Successfully templated '+src+'\n');
        grunt.file.write(dest, js);
        grunt.log.write('✔ '.green + 'Successfully wrote '+dest+'\n');
        done(true);
    });
};


text:
package com.helger.pd.indexer.index;

import java.time.LocalDateTime;

import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.datetime.PDTFactory;
import com.helger.commons.hashcode.HashCodeGenerator;
import com.helger.commons.id.factory.GlobalIDFactory;
import com.helger.commons.string.ToStringGenerator;
import com.helger.commons.type.ObjectType;
import com.helger.peppolid.IParticipantIdentifier;
import com.helger.peppolid.simple.participant.SimpleParticipantIdentifier;

/**
 * This class represents a single work item for the indexer. This is the default
 * implementation of {@link IIndexerWorkItem}.
 *
 * @author Philip Helger
 */
@Immutable
public final class IndexerWorkItem implements IIndexerWorkItem
{
  public static final ObjectType OT = new ObjectType ("IndexerWorkItem");

  private final String m_sID;
  private final LocalDateTime m_aCreationDT;
  private final IParticipantIdentifier m_aParticipantID;
  private final EIndexerWorkItemType m_eType;
  private final String m_sOwnerID;
  private final String m_sRequestingHost;

  public IndexerWorkItem (@Nonnull final IParticipantIdentifier aParticpantID,
                          @Nonnull final EIndexerWorkItemType eType,
                          @Nonnull @Nonempty final String sOwnerID,
                          @Nonnull @Nonempty final String sRequestingHost)
  {
    this (GlobalIDFactory.getNewPersistentStringID (),
          PDTFactory.getCurrentLocalDateTime (),
          aParticpantID,
          eType,
          sOwnerID,
          sRequestingHost);
  }

  IndexerWorkItem (@Nonnull @Nonempty final String sID,
                   @Nonnull final LocalDateTime aCreationDT,
                   @Nonnull final IParticipantIdentifier aParticpantID,
                   @Nonnull final EIndexerWorkItemType eType,
                   @Nonnull @Nonempty final String sOwnerID,
                   @Nonnull @Nonempty final String sRequestingHost)
  {
    ValueEnforcer.notNull (sID, "ID");
    ValueEnforcer.notNull (aCreationDT, "CreationDT");
    ValueEnforcer.notNull (aParticpantID, "ParticpantID");
    ValueEnforcer.notNull (eType, "Type");
    ValueEnforcer.notNull (sOwnerID, "OwnerID");
    ValueEnforcer.notNull (sRequestingHost, "RequestingHost");

    m_sID = sID;
    m_aCreationDT = aCreationDT;
    // Ensure all objects have the same type
    // No need to use the IIdentifierFactory here, since the participant is
    // already structured
    m_aParticipantID = new SimpleParticipantIdentifier (aParticpantID);
    m_eType = eType;
    m_sOwnerID = sOwnerID;
    m_sRequestingHost = sRequestingHost;
  }

  @Nonnull
  public ObjectType getObjectType ()
  {
    return OT;
  }

  @Nonnull
  @Nonempty
  public String getID ()
  {
    return m_sID;
  }

  @Nonnull
  public LocalDateTime getCreationDateTime ()
  {
    return m_aCreationDT;
  }

  @Nonnull
  public IParticipantIdentifier getParticipantID ()
  {
    return m_aParticipantID;
  }

  @Nonnull
  public EIndexerWorkItemType getType ()
  {
    return m_eType;
  }

  @Nonnull
  @Nonempty
  public String getOwnerID ()
  {
    return m_sOwnerID;
  }

  @Nonnull
  public String getRequestingHost ()
  {
    return m_sRequestingHost;
  }

  @Override
  public boolean equals (final Object o)
  {
    if (o == this)
      return true;
    if (o == null || !getClass ().equals (o.getClass ()))
      return false;
    final IndexerWorkItem rhs = (IndexerWorkItem) o;
    return m_aParticipantID.equals (rhs.m_aParticipantID) && m_eType.equals (rhs.m_eType);
  }

  @Override
  public int hashCode ()
  {
    return new HashCodeGenerator (this).append (m_aParticipantID).append (m_eType).getHashCode ();
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("ID", m_sID)
                                       .append ("CreationDT", m_aCreationDT)
                                       .append ("ParticipantID", m_aParticipantID)
                                       .append ("Type", m_eType)
                                       .append ("OwnerID", m_sOwnerID)
                                       .append ("RequestingHost", m_sRequestingHost)
                                       .getToString ();
  }
}


text:
namespace google {
namespace cloud {
namespace monitoring_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

class AlertPolicyServiceConnectionImpl
    : public monitoring::AlertPolicyServiceConnection {
 public:
  ~AlertPolicyServiceConnectionImpl() override = default;

  AlertPolicyServiceConnectionImpl(
      std::unique_ptr<google::cloud::BackgroundThreads> background,
      std::shared_ptr<monitoring_internal::AlertPolicyServiceStub> stub,
      Options options);

  Options options() override { return options_; }

  StreamRange<google::monitoring::v3::AlertPolicy> ListAlertPolicies(
      google::monitoring::v3::ListAlertPoliciesRequest request) override;

  StatusOr<google::monitoring::v3::AlertPolicy> GetAlertPolicy(
      google::monitoring::v3::GetAlertPolicyRequest const& request) override;

  StatusOr<google::monitoring::v3::AlertPolicy> CreateAlertPolicy(
      google::monitoring::v3::CreateAlertPolicyRequest const& request) override;

  Status DeleteAlertPolicy(
      google::monitoring::v3::DeleteAlertPolicyRequest const& request) override;

  StatusOr<google::monitoring::v3::AlertPolicy> UpdateAlertPolicy(
      google::monitoring::v3::UpdateAlertPolicyRequest const& request) override;

 private:
  std::unique_ptr<monitoring::AlertPolicyServiceRetryPolicy> retry_policy() {
    auto const& options = internal::CurrentOptions();
    if (options.has<monitoring::AlertPolicyServiceRetryPolicyOption>()) {
      return options.get<monitoring::AlertPolicyServiceRetryPolicyOption>()
          ->clone();
    }
    return options_.get<monitoring::AlertPolicyServiceRetryPolicyOption>()
        ->clone();
  }

  std::unique_ptr<BackoffPolicy> backoff_policy() {
    auto const& options = internal::CurrentOptions();
    if (options.has<monitoring::AlertPolicyServiceBackoffPolicyOption>()) {
      return options.get<monitoring::AlertPolicyServiceBackoffPolicyOption>()
          ->clone();
    }
    return options_.get<monitoring::AlertPolicyServiceBackoffPolicyOption>()
        ->clone();
  }

  std::unique_ptr<monitoring::AlertPolicyServiceConnectionIdempotencyPolicy>
  idempotency_policy() {
    auto const& options = internal::CurrentOptions();
    if (options
            .has<monitoring::
                     AlertPolicyServiceConnectionIdempotencyPolicyOption>()) {
      return options
          .get<
              monitoring::AlertPolicyServiceConnectionIdempotencyPolicyOption>()
          ->clone();
    }
    return options_
        .get<monitoring::AlertPolicyServiceConnectionIdempotencyPolicyOption>()
        ->clone();
  }

  std::unique_ptr<google::cloud::BackgroundThreads> background_;
  std::shared_ptr<monitoring_internal::AlertPolicyServiceStub> stub_;
  Options options_;
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace monitoring_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_MONITORING_INTERNAL_ALERT_POLICY_CONNECTION_IMPL_H


text:
/**
 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v12.0.2
 * @link http://www.ag-grid.com/
 * @license MIT
 */
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../context/context");
var column_1 = require("../entities/column");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var utils_1 = require("../utils");
var AutoGroupColService = (function () {
    function AutoGroupColService() {
    }
    AutoGroupColService_1 = AutoGroupColService;
    AutoGroupColService.prototype.createAutoGroupColumns = function (rowGroupColumns) {
        var _this = this;
        var groupAutoColumns = [];
        // if doing groupMultiAutoColumn, then we call the method multiple times, once
        // for each column we are grouping by
        if (this.gridOptionsWrapper.isGroupMultiAutoColumn()) {
            rowGroupColumns.forEach(function (rowGroupCol, index) {
                groupAutoColumns.push(_this.createOneAutoGroupColumn(rowGroupCol, index));
            });
        }
        else {
            groupAutoColumns.push(this.createOneAutoGroupColumn(null));
        }
        return groupAutoColumns;
    };
    // rowGroupCol and index are missing if groupMultiAutoColumn=false
    AutoGroupColService.prototype.createOneAutoGroupColumn = function (rowGroupCol, index) {
        // if one provided by user, use it, otherwise create one
        var defaultAutoColDef = this.generateDefaultColDef(rowGroupCol, index);
        var userAutoColDef = this.gridOptionsWrapper.getAutoGroupColumnDef();
        // if doing multi, set the field
        var colId;
        if (rowGroupCol) {
            colId = AutoGroupColService_1.GROUP_AUTO_COLUMN_ID + "-" + rowGroupCol.getId();
        }
        else {
            colId = AutoGroupColService_1.GROUP_AUTO_COLUMN_BUNDLE_ID;
        }
        utils_1._.mergeDeep(defaultAutoColDef, userAutoColDef);
        defaultAutoColDef.colId = colId;
        //If the user is not telling us his preference with regards wether the filtering
        //should be suppressed, we suppress it if there are no leaf nodes
        if (userAutoColDef == null || userAutoColDef.suppressFilter == null) {
            var produceLeafNodeValues = defaultAutoColDef.field != null || defaultAutoColDef.valueGetter != null;
            defaultAutoColDef.suppressFilter = !produceLeafNodeValues;
        }
        // if showing many cols, we don't want to show more than one with a checkbox for selection
        if (index > 0) {
            defaultAutoColDef.headerCheckboxSelection = false;
        }
        var newCol = new column_1.Column(defaultAutoColDef, colId, true);
        this.context.wireBean(newCol);
        return newCol;
    };
    AutoGroupColService.prototype.generateDefaultColDef = function (rowGroupCol, index) {
        var localeTextFunc = this.gridOptionsWrapper.getLocaleTextFunc();
        var defaultAutoColDef = {
            headerName: localeTextFunc('group', 'Group'),
            cellRenderer: 'group'
        };
        // we never allow moving the group column
        defaultAutoColDef.suppressMovable = true;
        if (rowGroupCol) {
            var rowGroupColDef = rowGroupCol.getColDef();
            utils_1._.assign(defaultAutoColDef, {
                // cellRendererParams.groupKey: colDefToCopy.field;
                headerName: rowGroupColDef.headerName,
                headerValueGetter: rowGroupColDef.headerValueGetter
            });
            defaultAutoColDef.showRowGroup = rowGroupCol.getColId();
        }
        else {
            defaultAutoColDef.showRowGroup = true;
        }
        return defaultAutoColDef;
    };
    AutoGroupColService.GROUP_AUTO_COLUMN_ID = 'ag-Grid-AutoColumn';
    AutoGroupColService.GROUP_AUTO_COLUMN_BUNDLE_ID = AutoGroupColService_1.GROUP_AUTO_COLUMN_ID;
    __decorate([
        context_1.Autowired('gridOptionsWrapper'),
        __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
    ], AutoGroupColService.prototype, "gridOptionsWrapper", void 0);
    __decorate([
        context_1.Autowired('context'),
        __metadata("design:type", context_1.Context)
    ], AutoGroupColService.prototype, "context", void 0);
    AutoGroupColService = AutoGroupColService_1 = __decorate([
        context_1.Bean('autoGroupColService')
    ], AutoGroupColService);
    return AutoGroupColService;
    var AutoGroupColService_1;
}());
exports.AutoGroupColService = AutoGroupColService;


text:
(function() {
  'use strict';
  angular.module('hansei.services')
    .factory('eventerFactory', ['api', function(api) {
      return function(events) {  // {event: callback, ...}
        events = events || {};
        return {
          getEvents: function() {
            return Object.keys(events);
          },
          event: function(ev, fn) {
            events[ev] = fn;
            return this;
          },
          events: function(objOrFn) {
            events = objOrFn;
            return this;
          },
          hook: function(scope) {
            var _eventer = this;

            _eventer.register(scope);
            scope.$on('$destroy', function() { _eventer.unregister(); });
          },
          register: function(scope) {
            if (typeof events === 'function') {
              events = events();
            }

            api.subscribe(this.getEvents());

            // This hooks the actual code to the future inbound message. When the
            // scope $destroys, the event is automatically unhooked.
            for (var ev in events) { api.hook(ev, scope, events[ev]); }

            return this;
          },
          unregister: function() {
            api.unsubscribe(this.getEvents());

            return this;
          },
        };
      };
    }])
})();


text:
package org.apache.hadoop.hbase.master.procedure;

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

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseClassTestRule;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.StartMiniClusterOption;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.master.HMaster;
import org.apache.hadoop.hbase.procedure2.Procedure;
import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
import org.apache.hadoop.hbase.procedure2.ProcedureTestingUtility.TestProcedure;
import org.apache.hadoop.hbase.procedure2.store.ProcedureStore;
import org.apache.hadoop.hbase.procedure2.store.wal.WALProcedureStore;
import org.apache.hadoop.hbase.testclassification.LargeTests;
import org.apache.hadoop.hbase.testclassification.MasterTests;
import org.apache.hadoop.hbase.util.ModifyRegionUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TestName;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Category({MasterTests.class, LargeTests.class})
@Ignore
public class TestMasterProcedureWalLease {

  @ClassRule
  public static final HBaseClassTestRule CLASS_RULE =
      HBaseClassTestRule.forClass(TestMasterProcedureWalLease.class);

  private static final Logger LOG = LoggerFactory.getLogger(TestMasterProcedureWalLease.class);

  @Rule
  public TestName name = new TestName();

  protected static final HBaseTestingUtility UTIL = new HBaseTestingUtility();

  private static void setupConf(Configuration conf) {
    // don't waste time retrying with the roll, the test is already slow enough.
    conf.setInt(WALProcedureStore.MAX_RETRIES_BEFORE_ROLL_CONF_KEY, 1);
    conf.setInt(WALProcedureStore.WAIT_BEFORE_ROLL_CONF_KEY, 0);
    conf.setInt(WALProcedureStore.ROLL_RETRIES_CONF_KEY, 1);
    conf.setInt(WALProcedureStore.MAX_SYNC_FAILURE_ROLL_CONF_KEY, 1);
  }

  @Before
  public void setup() throws Exception {
    setupConf(UTIL.getConfiguration());
    StartMiniClusterOption option = StartMiniClusterOption.builder()
        .numMasters(2).numRegionServers(3).numDataNodes(3).build();
    UTIL.startMiniCluster(option);
  }

  @After
  public void tearDown() throws Exception {
    try {
      UTIL.shutdownMiniCluster();
    } catch (Exception e) {
      LOG.warn("failure shutting down cluster", e);
    }
  }

  @Test
  public void testWalRecoverLease() throws Exception {
    final ProcedureStore masterStore = getMasterProcedureExecutor().getStore();
    assertTrue("expected WALStore for this test", masterStore instanceof WALProcedureStore);

    HMaster firstMaster = UTIL.getHBaseCluster().getMaster();
    // Abort Latch for the master store
    final CountDownLatch masterStoreAbort = new CountDownLatch(1);
    masterStore.registerListener(new ProcedureStore.ProcedureStoreListener() {
      @Override
      public void postSync() {}

      @Override
      public void abortProcess() {
        LOG.debug("Abort store of Master");
        masterStoreAbort.countDown();
      }
    });

    // startup a fake master the new WAL store will take the lease
    // and the active master should abort.
    HMaster backupMaster3 = Mockito.mock(HMaster.class);
    Mockito.doReturn(firstMaster.getConfiguration()).when(backupMaster3).getConfiguration();
    Mockito.doReturn(true).when(backupMaster3).isActiveMaster();
    final WALProcedureStore backupStore3 = new WALProcedureStore(firstMaster.getConfiguration(),
        ((WALProcedureStore)masterStore).getWALDir(),
        null,
        new MasterProcedureEnv.WALStoreLeaseRecovery(backupMaster3));
    // Abort Latch for the test store
    final CountDownLatch backupStore3Abort = new CountDownLatch(1);
    backupStore3.registerListener(new ProcedureStore.ProcedureStoreListener() {
      @Override
      public void postSync() {}

      @Override
      public void abortProcess() {
        LOG.debug("Abort store of backupMaster3");
        backupStore3Abort.countDown();
        backupStore3.stop(true);
      }
    });
    backupStore3.start(1);
    backupStore3.recoverLease();

    // Try to trigger a command on the master (WAL lease expired on the active one)
    TableDescriptor htd = MasterProcedureTestingUtility.createHTD(TableName.valueOf(name.getMethodName()), "f");
    RegionInfo[] regions = ModifyRegionUtils.createRegionInfos(htd, null);
    LOG.debug("submit proc");
    try {
      getMasterProcedureExecutor().submitProcedure(
          new CreateTableProcedure(getMasterProcedureExecutor().getEnvironment(), htd, regions));
      fail("expected RuntimeException 'sync aborted'");
    } catch (RuntimeException e) {
      LOG.info("got " + e.getMessage());
    }
    LOG.debug("wait master store abort");
    masterStoreAbort.await();

    // Now the real backup master should start up
    LOG.debug("wait backup master to startup");
    MasterProcedureTestingUtility.waitBackupMaster(UTIL, firstMaster);
    assertEquals(true, firstMaster.isStopped());

    // wait the store in here to abort (the test will fail due to timeout if it doesn't)
    LOG.debug("wait the store to abort");
    backupStore3.getStoreTracker().setDeleted(1, false);
    try {
      backupStore3.delete(1);
      fail("expected RuntimeException 'sync aborted'");
    } catch (RuntimeException e) {
      LOG.info("got " + e.getMessage());
    }
    backupStore3Abort.await();
  }

  /**
   * Tests proper fencing in case the current WAL store is fenced
   */
  @Test
  public void testWALfencingWithoutWALRolling() throws IOException {
    testWALfencing(false);
  }

  /**
   * Tests proper fencing in case the current WAL store does not receive writes until after the
   * new WAL does a couple of WAL rolls.
   */
  @Test
  public void testWALfencingWithWALRolling() throws IOException {
    testWALfencing(true);
  }

  public void testWALfencing(boolean walRolls) throws IOException {
    final ProcedureStore procStore = getMasterProcedureExecutor().getStore();
    assertTrue("expected WALStore for this test", procStore instanceof WALProcedureStore);

    HMaster firstMaster = UTIL.getHBaseCluster().getMaster();

    // cause WAL rolling after a delete in WAL:
    firstMaster.getConfiguration().setLong(WALProcedureStore.ROLL_THRESHOLD_CONF_KEY, 1);

    HMaster backupMaster3 = Mockito.mock(HMaster.class);
    Mockito.doReturn(firstMaster.getConfiguration()).when(backupMaster3).getConfiguration();
    Mockito.doReturn(true).when(backupMaster3).isActiveMaster();
    final WALProcedureStore procStore2 = new WALProcedureStore(firstMaster.getConfiguration(),
        ((WALProcedureStore)procStore).getWALDir(),
        null,
        new MasterProcedureEnv.WALStoreLeaseRecovery(backupMaster3));

    // start a second store which should fence the first one out
    LOG.info("Starting new WALProcedureStore");
    procStore2.start(1);
    procStore2.recoverLease();

    // before writing back to the WAL store, optionally do a couple of WAL rolls (which causes
    // to delete the old WAL files).
    if (walRolls) {
      LOG.info("Inserting into second WALProcedureStore, causing WAL rolls");
      for (int i = 0; i < 512; i++) {
        // insert something to the second store then delete it, causing a WAL roll(s)
        Procedure proc2 = new TestProcedure(i);
        procStore2.insert(proc2, null);
        procStore2.delete(proc2.getProcId()); // delete the procedure so that the WAL is removed later
      }
    }

    // Now, insert something to the first store, should fail.
    // If the store does a WAL roll and continue with another logId without checking higher logIds
    // it will incorrectly succeed.
    LOG.info("Inserting into first WALProcedureStore");
    try {
      procStore.insert(new TestProcedure(11), null);
      fail("Inserting into Procedure Store should have failed");
    } catch (Exception ex) {
      LOG.info("Received expected exception", ex);
    }
  }

  // ==========================================================================
  //  Helpers
  // ==========================================================================
  private ProcedureExecutor<MasterProcedureEnv> getMasterProcedureExecutor() {
    return UTIL.getHBaseCluster().getMaster().getMasterProcedureExecutor();
  }
}


text:
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#

testinfo = "s, t 4.9, s, t 5.1, s, t 10.1, s, t 10.2, s, q"
tags = "sequence, MoveBy, Place"

import cocos
from cocos.director import director
from cocos.sprite import Sprite
from cocos.actions import Place, MoveBy

import pyglet

class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super( TestLayer, self ).__init__()

        x,y = director.get_window_size()

        self.sprite = Sprite( 'grossini.png', (0,y/2)  )
        self.add( self.sprite )
        self.sprite.do( MoveBy( (x/2, 0) ) + Place( (x/2, y/3) ) + MoveBy( (x/2, 0) ) )

def main():
    print "sprite moves from left border to midscreen,\nteleports down,\nmoves to right border"
    director.init()
    test_layer = TestLayer ()
    main_scene = cocos.scene.Scene (test_layer)
    director.run (main_scene)

if __name__ == '__main__':
    main()


text:
import datetime
from marshmallow import (
    Schema,
    fields,
    pre_load,
    post_load,
    validate,
    validates_schema,
    ValidationError)

from airy.database import db
from airy.models import Client, Project, Task, TimeEntry
from airy.utils.date import tz_now, is_day_beginning, is_day_end

class UserSerializer(Schema):

    name = fields.String()
    open_tasks = fields.Integer()
    total_today = fields.TimeDelta()
    total_week = fields.TimeDelta()

def validate_task_id(value):
    if not Task.query.get(value):
        raise ValidationError('Invalid task id.')

def validate_duration(value):
    if value.seconds % 60 != 0:
        raise ValidationError('Seconds are not allowed.')

class TimeEntrySerializer(Schema):

    id = fields.Integer()
    duration = fields.TimeDelta(
        required=True,
        validate=[
            validate.Range(
                min=datetime.timedelta(minutes=1),
                max=datetime.timedelta(hours=100)),
            validate_duration,
        ])
    comment = fields.String(validate=validate.Length(max=100),
                            allow_none=True)
    task_id = fields.Integer(required=True,
                             validate=validate_task_id)

    added_at = fields.DateTime(dump_only=True)

    task_total_time = fields.Method('get_task_total_time')

    @post_load
    def make_time_entry(self, data, **kwargs):
        if 'id' not in data:
            data['added_at'] = tz_now()
        return TimeEntry(**data)

    def get_task_total_time(self, time_entry):
        if time_entry.task.total_time:
            return time_entry.task.total_time.total_seconds()
        else:
            return 0

def validate_project_id(value):
    if not Project.query.get(value):
        raise ValidationError('Invalid project id.')

class TaskSerializer(Schema):

    id = fields.Integer()
    title = fields.String(required=True,
                          validate=validate.Length(min=3, max=100))
    url = fields.Url(required=False, allow_none=True)
    description = fields.String(validate=validate.Length(max=1000),
                                allow_none=True)
    project_id = fields.Integer(required=True,
                                validate=validate_project_id)

    created_at = fields.DateTime(dump_only=True)
    updated_at = fields.DateTime(dump_only=True)
    time_entries = fields.Nested(TimeEntrySerializer,
                                 exclude=['task_total_time'],
                                 many=True,
                                 dump_only=True)
    total_time = fields.TimeDelta(default=0,
                                  dump_only=True)
    is_closed = fields.Boolean(dump_only=True)

    @pre_load
    def clean_url(self, data, **kwargs):
        if not data.get('url'):
            data['url'] = None
        return data

    @post_load
    def make_task(self, data, **kwargs):
        if 'id' not in data:
            data['created_at'] = tz_now()
        data['updated_at'] = tz_now()
        return Task(**data)

def validate_client_id(value):
    if not Client.query.get(value):
        raise ValidationError('Invalid client id.')

class ProjectSerializer(Schema):

    id = fields.Integer()
    name = fields.String(required=True,
                         validate=validate.Length(min=3, max=100))
    description = fields.String(validate=validate.Length(max=700),
                                allow_none=True)
    client_id = fields.Integer(required=True,
                               validate=validate_client_id)

    tasks = fields.Nested(TaskSerializer,
                          many=True,
                          dump_only=True)
    last_task = fields.Nested(TaskSerializer,
                              only=['id', 'title'],
                              dump_only=True)
    client = fields.Nested('ClientSerializer',
                           only=['id', 'name'],
                           dump_only=True)

    def __init__(self, *args, **kwargs):
        task_status = kwargs.pop('task_status', None)
        super().__init__(*args, **kwargs)
        if task_status == 'open':
            self.fields['tasks'].attribute = 'open_tasks'
        elif task_status == 'closed':
            self.fields['tasks'].attribute = 'closed_tasks'

    @post_load
    def make_project(self, data, **kwargs):
        return Project(**data)

class ClientSerializer(Schema):

    id = fields.Integer()
    name = fields.String(required=True,
                         validate=validate.Length(min=3, max=100))
    contacts = fields.String(validate=validate.Length(max=700),
                             allow_none=True)

    projects = fields.Nested(ProjectSerializer,
                             only=['id', 'name', 'description',
                                   'client_id', 'last_task'],
                             many=True,
                             dump_only=True)

    @validates_schema
    def validate_unique_client_name(self, client, **kwargs):
        if client.get('name'):
            name_query = Client.query.filter(
                Client.name == client['name'],
                Client.id != client.get('id'))
            if db.session.query(name_query.exists()).scalar():
                raise ValidationError(
                    'Client {0} already exists'.format(client['name']),
                    'name')

    @post_load
    def make_client(self, data, **kwargs):
        return Client(**data)

def validate_range_beginning(value):
    if not is_day_beginning(value):
        raise ValidationError('Invalid beginning of the range')

def validate_range_end(value):
    if not is_day_end(value):
        raise ValidationError('Invalid end of the range')

class DateRangeSerializer(Schema):

    beg = fields.DateTime(required=True,
                          validate=validate_range_beginning)
    end = fields.DateTime(required=True,
                          validate=validate_range_end)

    @post_load
    def make_date_range(self, data, **kwargs):
        """
        Make tuple
        """
        return data.get('beg'), data.get('end')

class TimeSheetSerializer(Schema):

    client = fields.Nested(ClientSerializer, only=['id', 'name'])
    date_range = fields.Nested(DateRangeSerializer)
    projects = fields.Method('serialize_projects')
    totals = fields.Method('serialize_totals')

    def serialize_projects(self, obj):
        data = obj['projects'].copy()
        project_serializer = ProjectSerializer(only=['id', 'name'])
        for row in data:
            row['project'] = project_serializer.dump(row['project'])
            row['total'] = row['total'].total_seconds()
            for day_data in row['time']:
                day_data['total'] = day_data['total'].total_seconds()
                day_data['tasks'] = '\n'.join(day_data['tasks'])
        return data

    def serialize_totals(self, obj):
        totals = obj['totals'].copy()
        totals['time'] = [val.total_seconds() for val in totals['time']]
        totals['total'] = totals['total'].total_seconds()
        return totals

class TaskReportSerializer(Schema):

    client = fields.Nested(ClientSerializer, only=['id', 'name'])
    date_range = fields.Nested(DateRangeSerializer)
    projects = fields.Method('serialize_projects')
    total = fields.TimeDelta()

    def serialize_projects(self, obj):
        data = obj['projects'].copy()
        project_serializer = ProjectSerializer(only=['id', 'name'])
        for row in data:
            row['project'] = project_serializer.dump(row['project'])
            row['total'] = row['total'].total_seconds()
            for task_data in row['tasks']:
                task_data['total'] = task_data['total'].total_seconds()
        return data


text:
// -----------------------------------------------------------------------
// <copyright file="CompilePegGrammar.cs" company="(none)">
//   Copyright © 2014 John Gietzen.  All Rights Reserved.
//   This source is subject to the MIT license.
//   Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------

namespace Pegasus
{
    using System.CodeDom.Compiler;
    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;

    /// <summary>
    /// Provides compilation services for PEG grammars as an MSBuild task.
    /// </summary>
    public class CompilePegGrammar : Task
    {
        /// <summary>
        /// Gets or sets the filename of a file containing a grammar in PEG-format.
        /// </summary>
        [Required]
        public string InputFile { get; set; }

        /// <summary>
        /// Gets or sets the output filename that will contain the resulting code.
        /// </summary>
        /// <remarks>
        /// Set to null to use the default, which is the input filename with ".cs" appended.
        /// </remarks>
        public string OutputFile { get; set; }

        /// <summary>
        /// Reads and compiles the specified grammar.
        /// </summary>
        /// <returns>true, if the compilation was successful; false, otherwise.</returns>
        public override bool Execute()
        {
            CompileManager.CompileFile(this.InputFile, this.OutputFile, this.LogError);
            return !this.Log.HasLoggedErrors;
        }

        private void LogError(CompilerError error)
        {
            if (error.IsWarning)
            {
                this.Log.LogWarning(null, error.ErrorNumber, null, error.FileName, error.Line, error.Column, 0, 0, error.ErrorText);
            }
            else
            {
                this.Log.LogError(null, error.ErrorNumber, null, error.FileName, error.Line, error.Column, 0, 0, error.ErrorText);
            }
        }
    }
}


text:
package zzb.rest

import java.util.concurrent.TimeUnit

import com.typesafe.config.Config
import akka.actor.ActorRefFactory
import spray.util._

import scala.concurrent.duration.FiniteDuration

/**
 * Created by Simon on 2014/7/12
 */
case class RestSettings(verboseErrorMessages: Boolean,
                        users: Config,
                        renderVanityFooter: Boolean)

object RestSettings extends SettingsCompanion[RestSettings]("zzb.rest") {
  def fromSubConfig(c: Config) = apply(
    c getBoolean "verbose-error-messages",
    c getConfig "users",
    c getBoolean "render-vanity-footer")

  implicit def default(implicit refFactory: ActorRefFactory) =
    apply(actorSystem)
}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

using MediatR;

using Orleans;
using Orleans.Runtime;

using vivego.Collection.EventStore;
using vivego.Collection.EventStore.Delete;

namespace vivego.Collection.Orleans.EventStore.Delete
{
	internal class DeleteRequestPipelineBehavior : IPipelineBehavior<DeleteRequest, Unit>
	{
		private readonly IClusterClient _clusterClient;
		private readonly IEventStore _eventStore;

		public DeleteRequestPipelineBehavior(IClusterClient clusterClient, IEventStore eventStore)
		{
			_clusterClient = clusterClient ?? throw new ArgumentNullException(nameof(clusterClient));
			_eventStore = eventStore ?? throw new ArgumentNullException(nameof(eventStore));
		}

		public async Task<Unit> Handle(DeleteRequest request,
			CancellationToken cancellationToken,
			RequestHandlerDelegate<Unit> next)
		{
			if (request is null) throw new ArgumentNullException(nameof(request));
			if (next is null) throw new ArgumentNullException(nameof(next));

			if (RequestContext.Get(nameof(EventStoreGrain)) is bool inGrain && inGrain)
			{
				return await next().ConfigureAwait(false);
			}

			await _clusterClient
				.GetGrain<IEventStoreGrain>(request.StreamId)
				.Delete(_eventStore.Name)
				.ConfigureAwait(false);
			return Unit.Value;
		}
	}
}


text:
package org.aeonbits.owner;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Created by chengmingwang on 12/24/16.
 */
public class ConfigInheritanceTest {
    @Config.Sources(
            {"classpath:test.properties","classpath:org/aeonbits/owner/first.properties"}
    )
    interface MyConfig extends Config {
        @DefaultValue("favoriteColor")
        String favoriteColor();
    }

    interface TheConfig1 extends MyConfig {

    }

    @Config.Sources(
            {"classpath:org/aeonbits/owner/second.properties"}
    )
    interface TheConfig2 extends MyConfig {

    }

    @Config.Sources(
            {"classpath:org/aeonbits/owner/second.properties"}
    )
    @Config.LoadPolicy(Config.LoadType.MERGE)
    interface TheConfig3 extends MyConfig {

    }

    @Test
    public void testSourcesInheritance() {
        TheConfig1 theConfig1 = ConfigFactory.create(TheConfig1.class);
        assertEquals("pink", theConfig1.favoriteColor());

        TheConfig2 theConfig2 = ConfigFactory.create(TheConfig2.class);
        assertEquals("favoriteColor", theConfig2.favoriteColor());

        TheConfig3 theConfig3 = ConfigFactory.create(TheConfig3.class);
        assertEquals("pink", theConfig3.favoriteColor());
    }
}


text:
<?php
	/*-------------------------
	Autor: Obed Alvarado
	Web: obedalvarado.pw
	Mail: info@obedalvarado.pw
	---------------------------*/
	session_start();
	if (!isset($_SESSION['user_login_status']) AND $_SESSION['user_login_status'] != 1) {
        header("location: ../../login.php");
		exit;
    }
	/* Connect To Database*/
	include("../../config/db.php");
	include("../../config/conexion.php");
	//Archivo de funciones PHP
	include("../../funciones.php");
	$id_factura= intval($_GET['id_factura']);
	$sql_count=mysqli_query($con,"select * from facturas where id_factura='".$id_factura."'");
	$count=mysqli_num_rows($sql_count);
	if ($count==0)
	{
	echo "<script>alert('Factura no encontrada')</script>";
	echo "<script>window.close();</script>";
	exit;
	}
	$sql_factura=mysqli_query($con,"select * from facturas where id_factura='".$id_factura."'");
	$rw_factura=mysqli_fetch_array($sql_factura);
	$numero_factura=$rw_factura['numero_factura'];
	$id_cliente=$rw_factura['id_cliente'];
	$id_vendedor=$rw_factura['id_vendedor'];
	$fecha_factura=$rw_factura['fecha_factura'];
	$condiciones=$rw_factura['condiciones'];
	$moneda=$rw_factura['moneda'];
	if($moneda == 1){ $simbolo_moneda="$"; } else { $simbolo_moneda="¢"; }
	require_once(dirname(__FILE__).'/../html2pdf.class.php');
    // get the HTML
     ob_start();
     include(dirname('__FILE__').'/res/ver_factura_html.php');
    $content = ob_get_clean();

    try
    {
        // init HTML2PDF
        $html2pdf = new HTML2PDF('P', 'LETTER', 'es', true, 'UTF-8', array(0, 0, 0, 0));
        // display the full page
        $html2pdf->pdf->SetDisplayMode('fullpage');
        // convert
        $html2pdf->writeHTML($content, isset($_GET['vuehtml']));
        // send the PDF
        $html2pdf->Output('Factura-'.$numero_factura.'.pdf');
    }
    catch(HTML2PDF_exception $e) {
        echo $e;
        exit;
    }


text:
<?php

class CM_Usertext_Filter_StriptagsTest extends CMTest_TestCase {

    public function testProcess() {
        $text = "
foo

";

        $filter = new CM_Usertext_Filter_Striptags();
        $this->assertSame('foo', $filter->transform($text, new CM_Render()));

        $filter = new CM_Usertext_Filter_Striptags(array('p'));
        $this->assertSame('
foo
', $filter->transform($text, new CM_Render()));
    }
}


text:
function get_args_from_segment(line_array) {
    var args = [];
    var pieces = line_array;
    console.log('starting', pieces)
    while(pieces.length > 0) {
        var pce = pieces.shift();
        if (!pce.match(/(\")|(\')/)){
          console.log('added ', pce)
          args.push(pce)
        }
        else {
          pieces.unshift(pce)
          var stuff = ' '+pieces.join(' ')
          console.log('searching stuff', stuff)
          var finding_first_quot = true;
          var finding_second_quot = true;
          var first_quot = "";
          var i =1, j = 1;
          while(finding_first_quot) {
            var cur_char = stuff[i];
            var prev_char = stuff[i-1];
            if ( (cur_char == "'" || cur_char =='"') && prev_char !== "\\")
            {
              console.log('first quote found@',i)
              first_quot = cur_char;
              finding_first_quot = false;
              break;
            }
            i++;
            if (i >= stuff.length) break;
          }
          j = i + 1;
          while(finding_second_quot && !finding_first_quot) {
            var cur_char = stuff[j];
            var prev_char = stuff[j-1];
            if (cur_char == first_quot && prev_char !== "\\")
            {
              finding_second_quot = false;
              break;
            }
            j++;
            if (j >= stuff.length) break;
          }
          if (finding_first_quot || finding_second_quot) {
            pieces = stuff.split(' ');
            var arg = pieces.shift();
            while (!arg && pieces.length > 0)
              arg = pieces.shift();
            console.log('added', arg)
            args.push(arg);
          }
          else {
            var arg = stuff.substring(i, j+1);
            stuff = stuff.replace(arg,'').trim();
            console.log('added', arg)
            args.push(arg);
            pieces = stuff.split(' ')
          }
        }
      }
      console.log('args',args)
      return args;
  }

function execute(line) {
    line.replace('\\','\\\\')
    var child_process = require('child_process');
    var input_text = line;
    var segments = input_text.split('|');

    var processes = [];

    for (var i in segments) {
      var pieces = segments[i].split(/\s/g);

      var cmd = pieces.shift();
      while (!cmd) cmd = pieces.shift();

      pieces = get_args_from_segment(pieces);

      for (var i in pieces)
        if (!pieces[i]) pieces.splice(i, 1);

      pieces.push('');
      console.log(pieces)

    }
  }

execute('git commit -m "executing from my own cli"');


text:
module.exports = Buffers;

function Buffers (bufs) {
    if (!(this instanceof Buffers)) return new Buffers(bufs);
    this.buffers = bufs || [];
    this.length = this.buffers.reduce(function (size, buf) {
	return size + buf.length
    }, 0);
}

Buffers.prototype.push = function () {
    for (var i = 0; i < arguments.length; i++) {
	if (!Buffer.isBuffer(arguments[i])) {
	    throw new TypeError('Tried to push a non-buffer');
	}
    }

    for (var i = 0; i < arguments.length; i++) {
	var buf = arguments[i];
	this.buffers.push(buf);
	this.length += buf.length;
    }
    return this.length;
};

Buffers.prototype.unshift = function () {
    for (var i = 0; i < arguments.length; i++) {
	if (!Buffer.isBuffer(arguments[i])) {
	    throw new TypeError('Tried to unshift a non-buffer');
	}
    }

    for (var i = 0; i < arguments.length; i++) {
	var buf = arguments[i];
	this.buffers.unshift(buf);
	this.length += buf.length;
    }
    return this.length;
};

Buffers.prototype.copy = function (dst, dStart, start, end) {
    return this.slice(start, end).copy(dst, dStart, 0, end - start);
};

Buffers.prototype.splice = function (i, howMany) {
    var buffers = this.buffers;
    var index = i >= 0 ? i : this.length - i;
    var reps = [].slice.call(arguments, 2);

    if (howMany === undefined) {
	howMany = this.length - index;
    }
    else if (howMany > this.length - index) {
	howMany = this.length - index;
    }

    for (var i = 0; i < reps.length; i++) {
	this.length += reps[i].length;
    }

    var removed = new Buffers();
    var bytes = 0;

    var startBytes = 0;
    for (
	var ii = 0;
	ii < buffers.length && startBytes + buffers[ii].length < index;
	ii ++
    ) { startBytes += buffers[ii].length }

    if (index - startBytes > 0) {
	var start = index - startBytes;

	if (start + howMany < buffers[ii].length) {
	    removed.push(buffers[ii].slice(start, start + howMany));

	    var orig = buffers[ii];
	    //var buf = new Buffer(orig.length - howMany);
	    var buf0 = new Buffer(start);
	    for (var i = 0; i < start; i++) {
		buf0[i] = orig[i];
	    }

	    var buf1 = new Buffer(orig.length - start - howMany);
	    for (var i = start + howMany; i < orig.length; i++) {
		buf1[ i - howMany - start ] = orig[i]
	    }

	    if (reps.length > 0) {
		var reps_ = reps.slice();
		reps_.unshift(buf0);
		reps_.push(buf1);
		buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_));
		ii += reps_.length;
		reps = [];
	    }
	    else {
		buffers.splice(ii, 1, buf0, buf1);
		//buffers[ii] = buf;
		ii += 2;
	    }
	}
	else {
	    removed.push(buffers[ii].slice(start));
	    buffers[ii] = buffers[ii].slice(0, start);
	    ii ++;
	}
    }

    if (reps.length > 0) {
	buffers.splice.apply(buffers, [ ii, 0 ].concat(reps));
	ii += reps.length;
    }

    while (removed.length < howMany) {
	var buf = buffers[ii];
	var len = buf.length;
	var take = Math.min(len, howMany - removed.length);

	if (take === len) {
	    removed.push(buf);
	    buffers.splice(ii, 1);
	}
	else {
	    removed.push(buf.slice(0, take));
	    buffers[ii] = buffers[ii].slice(take);
	}
    }

    this.length -= removed.length;

    return removed;
};

Buffers.prototype.slice = function (i, j) {
    var buffers = this.buffers;
    if (j === undefined) j = this.length;
    if (i === undefined) i = 0;

    if (j > this.length) j = this.length;

    var startBytes = 0;
    for (
	var si = 0;
	si < buffers.length && startBytes + buffers[si].length <= i;
	si ++
    ) { startBytes += buffers[si].length }

    var target = new Buffer(j - i);

    var ti = 0;
    for (var ii = si; ti < j - i && ii < buffers.length; ii++) {
	var len = buffers[ii].length;

	var start = ti === 0 ? i - startBytes : 0;
	var end = ti + len >= j - i
	    ? Math.min(start + (j - i) - ti, len)
	    : len
	;

	buffers[ii].copy(target, ti, start, end);
	ti += end - start;
    }

    return target;
};

Buffers.prototype.pos = function (i) {
    if (i < 0 || i >= this.length) throw new Error('oob');
    var l = i, bi = 0, bu = null;
    for (;;) {
	bu = this.buffers[bi];
	if (l < bu.length) {
	    return {buf: bi, offset: l};
	} else {
	    l -= bu.length;
	}
	bi++;
    }
};

Buffers.prototype.get = function get (i) {
    var pos = this.pos(i);

    return this.buffers[pos.buf].get(pos.offset);
};

Buffers.prototype.set = function set (i, b) {
    var pos = this.pos(i);

    return this.buffers[pos.buf].set(pos.offset, b);
};

Buffers.prototype.indexOf = function (needle, offset) {
    if ("string" === typeof needle) {
	needle = new Buffer(needle);
    } else if (needle instanceof Buffer) {
	// already a buffer
    } else {
	throw new Error('Invalid type for a search string');
    }

    if (!needle.length) {
	return 0;
    }

    if (!this.length) {
	return -1;
    }

    var i = 0, j = 0, match = 0, mstart, pos = 0;

    // start search from a particular point in the virtual buffer
    if (offset) {
	var p = this.pos(offset);
	i = p.buf;
	j = p.offset;
	pos = offset;
    }

    // for each character in virtual buffer
    for (;;) {
	while (j >= this.buffers[i].length) {
	    j = 0;
	    i++;

	    if (i >= this.buffers.length) {
		// search string not found
		return -1;
	    }
	}

	var char = this.buffers[i][j];

	if (char == needle[match]) {
	    // keep track where match started
	    if (match == 0) {
		mstart = {
		    i: i,
		    j: j,
		    pos: pos
		};
	    }
	    match++;
	    if (match == needle.length) {
		// full match
		return mstart.pos;
	    }
	} else if (match != 0) {
	    // a partial match ended, go back to match starting position
	    // this will continue the search at the next character
	    i = mstart.i;
	    j = mstart.j;
	    pos = mstart.pos;
	    match = 0;
	}

	j++;
	pos++;
    }
};

Buffers.prototype.toBuffer = function() {
    return this.slice();
}

Buffers.prototype.toString = function(encoding, start, end) {
    return this.slice(start, end).toString(encoding);
}


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

import logging

LOG = logging.getLogger(__name__)

class Migration(SchemaMigration):

    def forwards(self, orm):
        try:
          from useradmin.models import get_default_user_group
          from desktop.lib.test_utils import revoke_permission

          # Revoke S3 access to default group by default
          if get_default_user_group():
              revoked = revoke_permission(get_default_user_group(), 'filebrowser', 's3_access')
              LOG.info('Revoked s3 permissions: %s' % revoked)
        except Exception as e:
          LOG.error(e)

    def backwards(self, orm):
        pass

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'useradmin.grouppermission': {
            'Meta': {'object_name': 'GroupPermission'},
            'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.Group']"}),
            'hue_permission': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['useradmin.HuePermission']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'useradmin.huepermission': {
            'Meta': {'object_name': 'HuePermission'},
            'action': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'app': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
            'description': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'through': u"orm['useradmin.GroupPermission']", 'symmetrical': 'False'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'useradmin.ldapgroup': {
            'Meta': {'object_name': 'LdapGroup'},
            'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'group'", 'to': u"orm['auth.Group']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
        },
        u'useradmin.userprofile': {
            'Meta': {'object_name': 'UserProfile'},
            'creation_method': ('django.db.models.fields.CharField', [], {'default': "'HUE'", 'max_length': '64'}),
            'first_login': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'home_directory': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'last_activity': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(1969, 12, 31, 0, 0)', 'db_index': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']", 'unique': 'True'})
        }
    }

    complete_apps = ['useradmin']


text:
/**
 * Models a resource as defined in https://developers.google.com/discovery/v1/reference/apis#resource
 */
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var util = require('util');
var log = require(path.dirname(__filename) + '/log');
var Constants = require(path.dirname(__filename) + '/constants');

module.exports = RestDescription;

function RestDescription(discoveryDocument) {
    var res = this;
    res.getDiscoveryDocument = getDiscoveryDocument;
    res.id = id;
    res.parameter = parameter;
    res.parameterNames = parameterNames;
    res.schema = schema;
    res.schemaNames = schemaNames;
    res.method = method;
    res.methodNames = methodNames;
    res.resource = resource;
    res.resourceNames = resourceNames;
    res.validate = validate;
    res.name = name;
    res.baseUrl = baseUrl;
    this.version = version;

    if (typeof (discoveryDocument) == 'undefined') {
        res.discovery = {kind: Constants.REST_DESCRIPTION_KIND};
    } else if (typeof(discoveryDocument) == 'object') {
        res.discovery = discoveryDocument;
    } else if (typeof(discoveryDocument) == 'string') {
        var jsonData = fs.readFileSync(discoveryDocument);
        res.discovery = JSON.parse(jsonData);
    } else {
        throw new Error('constructor arg must be object (discovery do) or string (filename of discovery.json)');
    }

    if (res.discovery.kind != Constants.REST_DESCRIPTION_KIND) {
        throw new Error('discoveryDocument.kind != ' + Constants.REST_DESCRIPTION_KIND + ' ("' + res.discovery.kind + '")');
    }
}
function baseUrl() {
    return this.discovery.baseUrl;
}

function name() {
    return this.discovery.name;
}

function validate() {
    if (!this.discovery) throw new Error('No discovery document');
    if (!this.discovery.protocol) throw new Error('No protocol');
    if (this.discovery.protocol != 'rest') {
        throw new Error('Unsupported protocol "' + this.discovery.protocol + '" supported protocols: (rest)');
    }
    if (!this.discovery.parameters) this.discovery.parameters = {};
    if (!this.discovery.schemas) this.discovery.schemas = {};
    if (!this.discovery.methods) this.discovery.methods = {};
    if (!this.discovery.resources) this.discovery.resources = {};
    return true;
}

function parameterNames() {
    return Object.keys(this.discovery.parameters);
}

function parameter(name) {
    return this.discovery.parameters[name];
}

function schemaNames() {
    return Object.keys(this.discovery.schemas);
}

function schema(name) {
    return this.discovery.schemas[name];
}

function methodNames() {
    return Object.keys(this.discovery.methods);
}

function method(name) {
    return this.discovery.methods[name];
}

function resourceNames() {
    return Object.keys(this.discovery.resources);
}

function resource(name) {
    return this.discovery.resources[name];
}

function getDiscoveryDocument() {
    return this.discovery;
}

function id() {
    return this.discovery.id;
}

function version() {
    return this.discovery.version;
}


text:
package api

import (
	"errors"
	"path"
	"strings"
)

type elementResult struct {
	Element    string `json:"ELEMENT"`
	W3CElement string `json:"element-6066-11e4-a52e-4f735466cecf"`
}

func (er elementResult) ID() string {
	if er.Element != "" {
		return er.Element
	}
	return er.W3CElement
}

type Element struct {
	ID      string
	Session *Session
}

func (e *Element) Send(method, endpoint string, body, result interface{}) error {
	return e.Session.Send(method, path.Join("element", e.ID, endpoint), body, result)
}

func (e *Element) GetID() string {
	return e.ID
}

func (e *Element) GetElement(selector Selector) (*Element, error) {
	var result elementResult

	if err := e.Send("POST", "element", selector, &result); err != nil {
		return nil, err
	}

	return &Element{result.ID(), e.Session}, nil
}

func (e *Element) GetElements(selector Selector) ([]*Element, error) {
	var results []elementResult

	if err := e.Send("POST", "elements", selector, &results); err != nil {
		return nil, err
	}

	elements := []*Element{}
	for _, result := range results {
		elements = append(elements, &Element{result.ID(), e.Session})
	}

	return elements, nil
}

func (e *Element) GetText() (string, error) {
	var text string
	if err := e.Send("GET", "text", nil, &text); err != nil {
		return "", err
	}
	return text, nil
}

func (e *Element) GetName() (string, error) {
	var name string
	if err := e.Send("GET", "name", nil, &name); err != nil {
		return "", err
	}
	return name, nil
}

func (e *Element) GetAttribute(attribute string) (string, error) {
	var value string
	if err := e.Send("GET", path.Join("attribute", attribute), nil, &value); err != nil {
		return "", err
	}
	return value, nil
}

func (e *Element) GetCSS(property string) (string, error) {
	var value string
	if err := e.Send("GET", path.Join("css", property), nil, &value); err != nil {
		return "", err
	}
	return value, nil
}

func (e *Element) Click() error {
	return e.Send("POST", "click", nil, nil)
}

func (e *Element) Clear() error {
	return e.Send("POST", "clear", nil, nil)
}

func (e *Element) Value(text string) error {
	splitText := strings.Split(text, "")
	request := struct {
		Value []string `json:"value"`
	}{splitText}
	return e.Send("POST", "value", request, nil)
}

func (e *Element) IsSelected() (bool, error) {
	var selected bool
	if err := e.Send("GET", "selected", nil, &selected); err != nil {
		return false, err
	}
	return selected, nil
}

func (e *Element) IsDisplayed() (bool, error) {
	var displayed bool
	if err := e.Send("GET", "displayed", nil, &displayed); err != nil {
		return false, err
	}
	return displayed, nil
}

func (e *Element) IsEnabled() (bool, error) {
	var enabled bool
	if err := e.Send("GET", "enabled", nil, &enabled); err != nil {
		return false, err
	}
	return enabled, nil
}

func (e *Element) Submit() error {
	return e.Send("POST", "submit", nil, nil)
}

func (e *Element) IsEqualTo(other *Element) (bool, error) {
	if other == nil {
		return false, errors.New("nil element is invalid")
	}
	var equal bool
	if err := e.Send("GET", path.Join("equals", other.ID), nil, &equal); err != nil {
		return false, err
	}
	return equal, nil
}

func (e *Element) GetLocation() (x, y int, err error) {
	var location struct {
		X float64 `json:"x"`
		Y float64 `json:"y"`
	}
	if err := e.Send("GET", "location", nil, &location); err != nil {
		return 0, 0, err
	}
	return round(location.X), round(location.Y), nil
}

func (e *Element) GetSize() (width, height int, err error) {
	var size struct {
		Width  float64 `json:"width"`
		Height float64 `json:"height"`
	}
	if err := e.Send("GET", "size", nil, &size); err != nil {
		return 0, 0, err
	}
	return round(size.Width), round(size.Height), nil
}

func round(number float64) int {
	return int(number + 0.5)
}


text:
using Lucene.Net.Codecs.Lucene41;

namespace Lucene.Net.Codecs.Pulsing
{

    ///
    /// Concrete pulsing implementation over <see cref="Lucene41PostingsFormat"/>.
    /// <para/>
    /// @lucene.experimental
    ///
    [PostingsFormatName("Pulsing41")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name
    public class Pulsing41PostingsFormat : PulsingPostingsFormat
    {
        /// Inlines docFreq=1 terms, otherwise uses the normal "Lucene41" format.
        public Pulsing41PostingsFormat()
            : this(1)
        {
        }

        /// Inlines docFreq=<paramref name="freqCutoff"/> terms, otherwise uses the normal "Lucene41" format.
        public Pulsing41PostingsFormat(int freqCutoff)
            : this(freqCutoff, BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE)
        {
        }

        /// Inlines docFreq=<paramref name="freqCutoff"/> terms, otherwise uses the normal "Lucene41" format.
        public Pulsing41PostingsFormat(int freqCutoff, int minBlockSize, int maxBlockSize)
            : base(new Lucene41PostingsBaseFormat(), freqCutoff, minBlockSize, maxBlockSize)
        {
        }
    }
}


text:
export default class httpService{
	constructor($http){
		this.http = $http;
	}
	getData(URL,params){
		let ajaxObject = {
			url : URL
		};
		if(params instanceof Object){
			ajaxObject.params = params;
		}
		return this.http(ajaxObject);
	}
	postData(URL,jsonData){
		return this.http({
			method : "post",
			url : URL,
			headers : {
				'Content-Type' : 'application/json'
			},
			data : jsonData,
		});
	}
	onError(){
		alert("操作数据失败!");
	};

	onSuccess(response) {
	if (response.data.success) {
		alert(response.data.msg);
	} else {
		onError(response);
	}
};
}

httpService.$inject = ['$http'];


text:
// Copyright 2009 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Initlialize namespaces.
var devtools = devtools || {};
devtools.profiler = devtools.profiler || {};

/**
 * Creates a CSV lines parser.
 */
devtools.profiler.CsvParser = function() {
};

/**
 * A regex for matching a CSV field.
 * @private
 */
devtools.profiler.CsvParser.CSV_FIELD_RE_ = /^"((?:[^"]|"")*)"|([^,]*)/;

/**
 * A regex for matching a double quote.
 * @private
 */
devtools.profiler.CsvParser.DOUBLE_QUOTE_RE_ = /""/g;

/**
 * Parses a line of CSV-encoded values. Returns an array of fields.
 *
 * @param {string} line Input line.
 */
devtools.profiler.CsvParser.prototype.parseLine = function(line) {
  var fieldRe = devtools.profiler.CsvParser.CSV_FIELD_RE_;
  var doubleQuoteRe = devtools.profiler.CsvParser.DOUBLE_QUOTE_RE_;
  var pos = 0;
  var endPos = line.length;
  var fields = [];
  if (endPos > 0) {
    do {
      var fieldMatch = fieldRe.exec(line.substr(pos));
      if (typeof fieldMatch[1] === "string") {
        var field = fieldMatch[1];
        pos += field.length + 3;  // Skip comma and quotes.
        fields.push(field.replace(doubleQuoteRe, '"'));
      } else {
        // The second field pattern will match anything, thus
        // in the worst case the match will be an empty string.
        var field = fieldMatch[2];
        pos += field.length + 1;  // Skip comma.
        fields.push(field);
      }
    } while (pos <= endPos);
  }
  return fields;
};


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file   CEC_ConsumerControl.h
 *
 *  $Id: CEC_ConsumerControl.h 14 2007-02-01 15:49:12Z mitza $
 *
 *  @author Carlos O'Ryan (coryan@cs.wustl.edu)More details can be found in:http://www.cs.wustl.edu/~coryan/EC/index.html
 */
//=============================================================================

#ifndef TAO_CEC_CONSUMERCONTROL_H
#define TAO_CEC_CONSUMERCONTROL_H

#include /**/ "ace/pre.h"

#include "orbsvcs/CosEvent/event_serv_export.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "tao/PortableServer/PortableServer.h"

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

class TAO_CEC_EventChannel;
class TAO_CEC_ProxyPushSupplier;
class TAO_CEC_ProxyPullSupplier;

namespace CORBA
{
  class SystemException;
}

/**
 * @class TAO_CEC_ConsumerControl
 *
 * @brief ConsumerControl
 *
 * Defines the interface for the consumer control strategy.
 * This strategy handles misbehaving or failing consumers.
 * = MEMORY MANAGMENT
 * = LOCKING
 * = TODO
 */
class TAO_Event_Serv_Export TAO_CEC_ConsumerControl
{
public:
  /// Constructor.  It does not assume ownership of the <event_channel>
  /// parameter.
  TAO_CEC_ConsumerControl (void);

  /// destructor...
  virtual ~TAO_CEC_ConsumerControl (void);

  /// Activate any internal threads or timers used to poll the state of
  /// the consumers
  virtual int activate (void);
  virtual int shutdown (void);

  /**
   * When pushing an event to the consumer a CORBA::OBJECT_NOT_EXIST
   * exception was raised. The only interpretation is that the object
   * has been destroyed.  The strategy has to (at the very least),
   * reclaim all the resources attached to that object.
   */
  virtual void consumer_not_exist (TAO_CEC_ProxyPushSupplier *proxy);

  /**
   * Invoked by helper classes when they detect that a consumer no
   * longer exists (i.e. _non_existent() returns true and/or the
   * CORBA::OBJECT_NOT_EXIST exception has been raised).
   */
  virtual void consumer_not_exist (TAO_CEC_ProxyPullSupplier *proxy);

  /// Some system exception was rasied while trying to push an event.
  virtual void system_exception (TAO_CEC_ProxyPushSupplier *proxy,
                                 CORBA::SystemException &);

  /// Do we need to disconnect this supplier?  The parameter type for
  /// proxy is PortableServer::ServantBase* due to the fact that this
  /// method will be used for TAO_CEC_ProxyPushSupplier's and
  /// TAO_CEC_ProxyPullSupplier's.
  virtual bool need_to_disconnect (PortableServer::ServantBase* proxy);

  /// Allow others to inform us when a send or receive was successful.
  virtual void successful_transmission (PortableServer::ServantBase* proxy);
};

TAO_END_VERSIONED_NAMESPACE_DECL

#include /**/ "ace/post.h"
#endif /* TAO_CEC_CONSUMERCONTROL_H */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to ObjectStyle LLC under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ObjectStyle LLC licenses
  this file to you 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>io.bootique.jdbc</groupId>
        <artifactId>bootique-jdbc-parent</artifactId>
        <version>3.0.M1-SNAPSHOT</version>
    </parent>

    <artifactId>bootique-jdbc-tomcat</artifactId>
    <packaging>jar</packaging>

    <name>bootique-jdbc-tomcat: Tomcat JDBC connection pool integration with Bootique</name>
    <description>Provides Tomcat JDBC connection pool integration with Bootique</description>

    <properties>
        <tomcat.version>8.0.30</tomcat.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>io.bootique.jdbc</groupId>
                <artifactId>bootique-jdbc</artifactId>
                <version>${project.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                <version>${tomcat.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- Compile dependencies -->
        <dependency>
            <groupId>io.bootique.jdbc</groupId>
            <artifactId>bootique-jdbc</artifactId>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
            <scope>compile</scope>
        </dependency>

        <!-- Unit test dependencies -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.bootique</groupId>
            <artifactId>bootique-junit5</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <!-- Optional profile used to sign artifacts -->
    <profiles>
        <profile>
            <id>gpg</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
        <profile>
            <id>rat</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.rat</groupId>
                        <artifactId>apache-rat-plugin</artifactId>
                        <configuration>
                            <excludes>
                              <exclude>derby.log</exclude>
                            </excludes>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>


text:
package org.flowcolab.account.service.client.services;

import org.flowcolab.account.service.client.dto.accountDetails.AccountDetailsResponse;
import org.flowcolab.account.service.client.errors.account.AccountNotFound.AccountNotFoundException;
import org.flowcolab.account.service.client.errors.person.PersonNotFound.PersonNotFoundException;

public interface AccountDetailsWebService {

    AccountDetailsResponse findByAccountId(long accountId) throws AccountNotFoundException, PersonNotFoundException;

    AccountDetailsResponse findByUsername(String username) throws AccountNotFoundException, PersonNotFoundException;
}


text:
package com.google.gerrit.common.data;

import com.google.gerrit.common.auth.SignInRequired;
import com.google.gerrit.reviewdb.AccountDiffPreference;
import com.google.gerrit.reviewdb.Change;
import com.google.gerrit.reviewdb.PatchSet;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwtjsonrpc.client.RemoteJsonService;
import com.google.gwtjsonrpc.client.RpcImpl;
import com.google.gwtjsonrpc.client.RpcImpl.Version;

@RpcImpl(version = Version.V2_0)
public interface ChangeDetailService extends RemoteJsonService {
  void changeDetail(Change.Id id, AsyncCallback<ChangeDetail> callback);

  void includedInDetail(Change.Id id, AsyncCallback<IncludedInDetail> callback);

  void patchSetDetail(PatchSet.Id key, AsyncCallback<PatchSetDetail> callback);

  void patchSetDetail2(PatchSet.Id baseId, PatchSet.Id key,
      AccountDiffPreference diffPrefs, AsyncCallback<PatchSetDetail> callback);

  @SignInRequired
  void patchSetPublishDetail(PatchSet.Id key,
      AsyncCallback<PatchSetPublishDetail> callback);
}


text:
package event;

import java.io.File;
import java.util.EventObject;

/**
 * Event for save as menu item
 *
 * @author RK Sanayaima Singh
 *
 */
public class SaveAsEvent extends EventObject {

	private static final long serialVersionUID = 1L;
	private File file;

	public SaveAsEvent(Object source) {
		super(source);
	}

	/**
	 * return the file to be saved
	 *
	 * @return
	 */
	public File getFile() {
		return file;
	}

	/**
	 * set the file to be saved
	 *
	 * @param file
	 */
	public void setFile(File file) {
		this.file = file;
	}

}


text:
angular.module('ODataResources').
factory('$odataBinaryOperation', ['$odataOperators','$odataProperty','$odataValue',function($odataOperators,ODataProperty,ODataValue) {

	var ODataBinaryOperation = function(a1,a2,a3){
		if(a1===undefined){
			throw "The property of a filter cannot be undefined";
		}

		if(a2 === undefined){
			throw "The value of a filter cannot be undefined";
		}

		if(a3 === undefined){
			//If strings are specified, we assume that the first one is the object property and the second one its value

			if(angular.isFunction(a1.execute)){
				this.operandA = a1;
			}else{
				this.operandA = new ODataProperty(a1);
			}
			if(angular.isFunction(a2.execute)){
				this.operandB = a2;
			}else{
				this.operandB = new ODataValue(a2);
			}

			this.filterOperator = 'eq';
		}
		else{
			if(angular.isFunction(a1.execute)){
				this.operandA = a1;
			}else{
				this.operandA = new ODataProperty(a1);
			}
			if(angular.isFunction(a3.execute)){
				this.operandB = a3;
			}else{
				this.operandB = new ODataValue(a3);
			}

			this.filterOperator = $odataOperators.convert(a2);
		}
	};

	ODataBinaryOperation.prototype.execute = function(isODatav4,noParenthesis){
		var result = this.operandA.execute(isODatav4)+" "+this.filterOperator+" " +this.operandB.execute(isODatav4);
		if(!noParenthesis)
			result = "("+result+")";

		return result;
	};

	ODataBinaryOperation.prototype.or = function(a1,a2,a3){
		var other;
		if(a2!==undefined){
			other = new ODataBinaryOperation(a1,a2,a3);
		}
		else if(angular.isFunction(a1.execute)){
			other = a1;
		}
		else{
			throw "The object " +a1 +" passed as a parameter of the or method is not valid";
		}
		return new ODataBinaryOperation(this,"or",other);
	};

	ODataBinaryOperation.prototype.and = function(a1,a2,a3){
		var other;
		if(a2!==undefined){
			other = new ODataBinaryOperation(a1,a2,a3);
		}
		else if(angular.isFunction(a1.execute)){
			other = a1;
		}
		else{
			throw "The object " +a1 +" passed as a parameter of the and method is not valid";
		}
		return new ODataBinaryOperation(this,"and",other);
	};

	return ODataBinaryOperation;
}

]);