text:
package com.thefinestartist.royal;

import android.content.Context;
import android.support.annotation.NonNull;

import com.orhanobut.logger.Logger;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.realm.Realm;
import io.realm.RealmConfiguration;

/**
 * Created by TheFinestArtist on 7/5/15.
 */
public class Royal {

    private static Context context;

    public static void joinWith(@NonNull Context context) {
        Royal.context = context.getApplicationContext();
        Logger.init("Royal");
    }

    public static Context getApplicationContext() {
        if (Royal.context == null)
            throw new NullPointerException("Please call Royal.joinWith(context) within your Application onCreate() method.");
        return Royal.context;
    }

    public static Map<Class<? extends RoyalDatabase>, RealmConfiguration> configurationMap = new ConcurrentHashMap<>();
    public static Map<Class<? extends RoyalDatabase>, RoyalDatabase> databaseMap = new ConcurrentHashMap<>();

    public static void addDatabase(@NonNull RoyalDatabase royalDatabase) {
        Context context = Royal.getApplicationContext();
        RealmConfiguration.Builder builder = new RealmConfiguration.Builder(context);
        builder.name(royalDatabase.getFileName() + ".realm");
        if (royalDatabase.forCache())
            builder.inMemory();
        if (royalDatabase.getEncryptionKey() != null)
            builder.encryptionKey(royalDatabase.getEncryptionKey());
        if (royalDatabase.shouldDeleteIfMigrationNeeded())
            builder.deleteRealmIfMigrationNeeded();

        List<Object> modules = royalDatabase.getModules();
        if (modules != null && modules.size() > 0) {
            Object baseModule;
            baseModule = modules.get(0);
            modules.remove(0);
            Object[] additionalModules = modules.toArray(new Object[modules.size()]);
            builder.setModules(baseModule, additionalModules);
        }

        builder.migration(royalDatabase);
        RealmConfiguration configuration = builder.build();
        configurationMap.put(royalDatabase.getClass(), configuration);
        databaseMap.put(royalDatabase.getClass(), royalDatabase);
    }

    public static RealmConfiguration getConfigurationOf(Class<? extends RoyalDatabase> clazz) {
        return configurationMap.get(clazz);
    }

    public static Realm getRealmOf(Class<? extends RoyalDatabase> clazz) {
        RealmConfiguration configuration = configurationMap.get(clazz);
        return Realm.getInstance(configuration);
    }

    public static RoyalDatabase getDatabaseOf(Class<? extends RoyalDatabase> clazz) {
        return databaseMap.get(clazz);
    }

//    public static Realm openRealm(Class<? extends RoyalDatabase> clazz) {
//        RealmConfiguration configuration = configurationMap.get(clazz);
//        return Realm.getInstance(configuration);
//    }
//
//    public static void closeRealm(Realm realm) {
//        realm.close();
//    }
}

//Realm is very fast database, but unfortunately there is some usability issues.
//
//        1. `Realm`, `RealmObject` can not be accessed by different thread other then which is was first created.
//        2. You have to `realm.getInstance()` and `realm.close()` every time you use Realm.
//        3. You have to call `realm.beginTransaction()` and `realm.commitTransaction()` every time you want to save data.
//        4. You have to loop for-loop backward `for(int i = results.size() - 1; i >= 0; i--)` to update data inside it.
//        5. Very hard to use Realm browser since Android device doesn't give you permission to pull the "name.realm" file unless you have rooted the phone.


text:
package io.subutai.core.environment.cli;

import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;

import com.google.common.base.Preconditions;

import io.subutai.common.environment.Environment;
import io.subutai.common.peer.ContainerHost;
import io.subutai.core.environment.api.EnvironmentManager;
import io.subutai.core.identity.rbac.cli.SubutaiShellCommandSupport;

/**
 * Destroys environment container
 */
@Command( scope = "environment", name = "destroy-container", description = "Command to destroy container" )
public class DestroyContainerCommand extends SubutaiShellCommandSupport
{
    @Argument( name = "conId", description = "Container id",
            index = 0, multiValued = false, required = true )
    /**
     * {@value containerIdStr} target environment container host to destroy
     * {@code required = true}
     */
            String containerIdStr;

    @Argument( name = "async", description = "asynchronous destruction",
            index = 1, multiValued = false, required = false )
    /**
     * {@value async} destroy environment asynchronously
     * <p> {@code required = false}, {@code default false} </p>
     */
            boolean async = false;

    private final EnvironmentManager environmentManager;

    public DestroyContainerCommand( final EnvironmentManager environmentManager )
    {
        Preconditions.checkNotNull( environmentManager );

        this.environmentManager = environmentManager;
    }

    @Override
    protected Object doExecute() throws Exception
    {

        for ( Environment environment : environmentManager.getEnvironments() )
        {
            for ( ContainerHost containerHost : environment.getContainerHosts() )
            {
                if ( containerHost.getId().equals( containerIdStr ) )
                {
                    environmentManager.destroyContainer( environment.getId(), containerHost.getId(), async );

                    System.out.println( "Container destroyed" );

                    return null;
                }
            }
        }

        System.out.println( "Container environment not found" );

        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.sf.jacclog.util.net;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class provides several methods to translate different representations of Internet Protocol addresses.
 *
 * @author André Rouél
 */
public class IpAddressTranslator {

	/**
	 * Pattern of an Internet Protocol version 4 (IPv4) address
	 */
	private static final Pattern IPV4_PATTERN = Pattern
			.compile("^0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.0*([1-9]?\\d|1\\d\\d|2[0-4]\\d|25[0-5])$");

	/**
	 * Translates an IPv4 address from its Four dimensions byte array representation to an Inet4Address.
	 *
	 * @param ipAddress
	 *            Four dimensions byte array representation of an IP address
	 * @return IP address as Inet4Address
	 * @throws IllegalArgumentException
	 *             If the given argument is null
	 * @throws IllegalArgumentException
	 *             If the given byte array does not have four entries
	 * @throws InvalidIpAddressException
	 *             If the IP address is not valid.
	 */
	public static Inet4Address toInet4Address(final byte[] ipAddress) {
		if (ipAddress == null) {
			throw new IllegalArgumentException("Argument 'ipAddress' can not be null.");
		}

		if (ipAddress.length != 4) {
			throw new IllegalArgumentException("An IP address as byte array needs 4 entries.");
		}

		try {
			return (Inet4Address) InetAddress.getByAddress(ipAddress);
		} catch (final UnknownHostException e) {
			throw new InvalidIpAddressException("The given IP address is not valid: " + e.getLocalizedMessage(), e);
		}
	}

	/**
	 * Translates an IPv4 address from its numeric representation to an Inet4Address.
	 *
	 * @param ipAddress
	 *            Numerical representation of an IP address as long
	 * @return IP address as Inet4Address
	 * @throws IllegalArgumentException
	 *             If the given argument is smaller than 0
	 * @throws IllegalArgumentException
	 *             If the given argument is greater than 4294967295
	 * @throws InvalidIpAddressException
	 *             Thrown to indicate that the IP address of a host could not be determined.
	 */
	public static Inet4Address toInet4Address(final long ipAddress) {
		if (ipAddress < 0L) {
			throw new IllegalArgumentException("Argument 'ipAddress' can not be smaller than 0.");
		}

		if (ipAddress > 4294967295L) {
			throw new IllegalArgumentException("Argument 'ipAddress' can not be greater than 4294967295.");
		}

		final byte[] bytes = new byte[] {

		(byte) ((ipAddress & 0xFF000000) >> 24),

		(byte) ((ipAddress & 0x00FF0000) >> 16),

		(byte) ((ipAddress & 0x0000FF00) >> 8),

		(byte) ((ipAddress & 0x000000FF) >> 0) };

		return toInet4Address(bytes);
	}

	/**
	 * Translates an IPv4 address from its textual representation to Inet4Address.
	 *
	 * @param ipAddress
	 *            IP address (IPv4) as String
	 * @return IP address as Inet4Address
	 * @throws IllegalArgumentException
	 *             If the given argument is null
	 * @throws IllegalArgumentException
	 *             If the given argument is not a valid IP address (IPv4)
	 * @throws InvalidIpAddressException
	 *             Thrown to indicate that the IP address of a host could not be determined.
	 */
	public static Inet4Address toInet4Address(final String ipAddress) {
		return toInet4Address(toLong(ipAddress));
	}

	/**
	 * Translates an IPv4 address from its textual to numeric representation.
	 *
	 * @param ipAddress
	 *            IP address (IPv4)
	 * @return Numerical representation of an IP address as long
	 * @throws IllegalArgumentException
	 *             If the given argument is null
	 * @throws IllegalArgumentException
	 *             If the given argument is not a valid IP address (IPv4)
	 */
	public static long toLong(final Inet4Address ipAddress) {
		if (ipAddress == null) {
			throw new IllegalArgumentException("Argument 'ipAddress' can not be null.");
		}

		return toLong(ipAddress.getHostAddress());
	}

	/**
	 * Multiplies an IP address, which consists of four numeric parts together into one numeric representation.
	 *
	 * @param partOne
	 *            First part of an IP address
	 * @param partTwo
	 *            Second part of an IP address
	 * @param partThree
	 *            Third part of an IP address
	 * @param partFour
	 *            Fourth part of an IP address
	 * @return Numerical representation of an IP address as long
	 * @throws IllegalArgumentException
	 *             If any given argument is smaller than 0
	 * @throws IllegalArgumentException
	 *             If any given argument is greater than 255
	 */
	public static long toLong(final long partOne, final long partTwo, final long partThree, final long partFour) {
		validateIpAddressPart(partOne, "partOne");
		validateIpAddressPart(partTwo, "partTwo");
		validateIpAddressPart(partThree, "partThree");
		validateIpAddressPart(partFour, "partFour");

		return 16777216L * partOne + 65536L * partTwo + 256L * partThree + partFour;
	}

	/**
	 * Translates an IPv4 address from its textual to numeric representation.
	 *
	 * @param ipAddress
	 *            IP address (IPv4) as String
	 * @return Numerical representation of an IP address as long
	 * @throws IllegalArgumentException
	 *             If the given argument is null
	 * @throws IllegalArgumentException
	 *             If the given argument is not a valid IP address (IPv4)
	 */
	public static long toLong(final String ipAddress) {
		if (ipAddress == null) {
			throw new IllegalArgumentException("Argument 'ipAddress' can not be null.");
		}

		final Matcher matcher = IPV4_PATTERN.matcher(ipAddress);
		if (!matcher.find()) {
			throw new IllegalArgumentException("Argument 'ipAddress' is not a valid IP address.");
		}

		final int w = Integer.parseInt(matcher.group(1));
		final int x = Integer.parseInt(matcher.group(2));
		final int y = Integer.parseInt(matcher.group(3));
		final int z = Integer.parseInt(matcher.group(4));
		return toLong(w, x, y, z);
	}

	/**
	 * Validates a part if it is not smaller than 0 and greater than 255. If the first
	 * argument is smaller than zero an IllegalArgumentException will be thrown. Otherwise the value of the
	 * first argument is valid.
	 *
	 * @param part
	 *            Value of an IP address part
	 * @param name
	 *            Name of the validating argument
	 */
	private static void validateIpAddressPart(final long part, final String name) {
		if (part < 0) {
			throw new IllegalArgumentException("Argument '" + name + "' can not be smaller than 0.");
		}

		if (part > 255) {
			throw new IllegalArgumentException("Argument '" + name + "' can not be greater than 255.");
		}
	}

	private IpAddressTranslator() {
		// stateless classes must not be instantiated
	}

}


text:
<?php

namespace Metabor\Statemachine\Filter;

use Metabor\Statemachine\StateCollection;
use Metabor\Statemachine\Util\SetupHelper;

/**
 * @author otischlinger
 */
class FilterStateByEventTest extends \PHPUnit_Framework_TestCase
{
    /**
     *
     */
    public function testFiltersStatesThatHaveEvent()
    {
        $eventName = 'event';
        $stateCollection = new StateCollection();
        $helper = new SetupHelper($stateCollection);
        $helper->findOrCreateTransition('foo', 'bar', $eventName);

        $filter = new FilterStateByEvent($stateCollection->getStates(), $eventName);
        $filteredStates = iterator_to_array($filter);

        $this->assertContains($stateCollection->getState('foo'), $filteredStates);
        $this->assertNotContains($stateCollection->getState('bar'), $filteredStates);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bidisha.ace">

    <uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light"
        android:name="com.example.bidisha.ace.StoreGlobal">
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />
        </provider>
        <meta-data
            android:name="com.google.android.gms.vision.DEPENDENCIES"
            android:value="barcode" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ClueScan" />
        <activity android:name=".Questions" />
        <activity android:name=".ScoreCal" />

    </application>

</manifest>


text:
==============
Slybot crawler
==============

Slybot is a Python web crawler for doing web scraping. It's implemented on top of the
`Scrapy`_ web crawling framework and the `Scrapely`_ extraction library.

The documentation (including installation and usage) can be found at:
http://slybot.readthedocs.org/

.. _Scrapely: https://github.com/scrapy/scrapely
.. _Scrapy: http://scrapy.org


text:
package edu.duke.cabig.c3pr.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import edu.duke.cabig.c3pr.constants.NotificationEventTypeEnum;
import edu.duke.cabig.c3pr.rules.exception.RuleException;
import edu.duke.cabig.c3pr.rules.runtime.BusinessRulesExecutionService;
import edu.duke.cabig.c3pr.service.RulesDelegationService;
import edu.duke.cabig.c3pr.service.ScheduledNotificationService;
import edu.duke.cabig.c3pr.service.SchedulerService;
import edu.duke.cabig.c3pr.tools.PropertiesGetterFactoryBean;

public class RulesDelegationServiceImpl implements RulesDelegationService{

	private static final Log log = LogFactory.getLog(RulesDelegationServiceImpl.class);

	public static final String NEW_STUDY_SAVED_EVENT = "NEW_STUDY_SAVED_EVENT";
	public static final String NEW_STUDY_SITE_SAVED_EVENT = "NEW_STUDY_SITE_SAVED_EVENT";
	public static final String STUDY_STATUS_CHANGE_EVENT = "STUDY_STATUS_CHANGE_EVENT";
	public static final String STUDY_SITE_STATUS_CHANGE_EVENT = "STUDY_SITE_STATUS_CHANGE_EVENT";
	public static final String REGISTRATION_EVENT = "REGISTRATION_EVENT";
	public static final String MASTER_SUBJECT_UPDATED_EVENT = "MASTER_SUBJECT_UPDATED_EVENT";

	private BusinessRulesExecutionService businessRulesExecutionService;

	private ScheduledNotificationService scheduledNotificationService;

	private SchedulerService schedulerService;

	public void activateRules(NotificationEventTypeEnum event, List<Object> objects){

		log.debug(this.getClass().getName() + ": Entering activateRules()");
		ArrayList <Object>objList = new ArrayList<Object>();
		objList.addAll(objects);
		objList.add(schedulerService);
		objList.add(scheduledNotificationService);
		objList.add(event);

		try{
			if(event != null){
				businessRulesExecutionService.fireRules("edu.duke.cabig.c3pr.rules.deploy.study_status_rules", objList);
			}
		}catch(RuleException re){
			log.error(re.getMessage());
		}
		log.debug(this.getClass().getName() + ": Exiting activateRules()");
	}

	public static void loadConfiguration(Properties props) {
    	ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:edu/duke/cabig/c3pr/applicationContext-config.xml");

    	String url = applicationContext.getBean("c3prPropertyConfigurerFromFile[datasource.url]").toString();
    	String driver = applicationContext.getBean("c3prPropertyConfigurerFromFile[datasource.driver]").toString();
    	String user = applicationContext.getBean("c3prPropertyConfigurerFromFile[datasource.username]").toString();
    	String pwd = applicationContext.getBean("c3prPropertyConfigurerFromFile[datasource.password]").toString();

		props.setProperty("datasource.driver", driver);
        props.setProperty("datasource.password", pwd);
        props.setProperty("datasource.username", user);
        props.setProperty("datasource.url", url);

	}

	public BusinessRulesExecutionService getBusinessRulesExecutionService() {
		return businessRulesExecutionService;
	}

	public void setBusinessRulesExecutionService(
			BusinessRulesExecutionService businessRulesExecutionService) {
		this.businessRulesExecutionService = businessRulesExecutionService;
	}

	public SchedulerService getSchedulerService() {
		return schedulerService;
	}

	public void setSchedulerService(SchedulerService schedulerService) {
		this.schedulerService = schedulerService;
	}

	public ScheduledNotificationService getScheduledNotificationService() {
		return scheduledNotificationService;
	}

	public void setScheduledNotificationService(
			ScheduledNotificationService scheduledNotificationService) {
		this.scheduledNotificationService = scheduledNotificationService;
	}
}


text:
'use strict';

var React = require('react');
var SvgIcon = require('../../svg-icon');

var FileFileUpload = React.createClass({
  displayName: 'FileFileUpload',

  render: function render() {
    return React.createElement(
      SvgIcon,
      this.props,
      React.createElement('path', { d: "M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z" })
    );
  }

});

module.exports = FileFileUpload;


text:
testdroid-cloud-remote-ruby
===========================


text:
package data;

/**
 * Simple class that runs a method.  Can we update the method without restarting the JVM.
 */
public class Simple {

	public static void main(String[] argv) {
		Simple s = new Simple();
		s.run();
	}

	public void run() {
		System.out.println("Hello World3");
	}

	public static void runStatic() {
		System.out.println("Hello World from static2");
	}

	public void newmethod() {
		System.out.println();
	}

}


text:
package com.carmanager.services;

import java.util.List;
import java.util.Set;

import org.springframework.validation.BindingResult;

import com.carmanager.entities.Page;
import com.carmanager.entities.User;

public interface UserService extends BaseService<User> {

	public User findByUsername(String username);

	public void createUser(User user);

	public void validate(User user, BindingResult bindingResult);

	public User findByEmail(String email);

	public User activeUserByEmail(String email, String activeCode);

	public Set<String> findRoles(String username);

	public Set<String> findPermissions(String username);

	public List<User> getAllAdmins();

	public Page<User> getGradeList(int pageNo, int pageSize);

	public Page<User> getScoreList(int pageNo, int pageSize);

}


text:
@interface HokutosaiShopsMenuItem : UIView

- (id)initWithFrame:(CGRect)frame itemName:(NSString*)itemName price:(NSInteger)price;

@end


text:
module Mongoid # :nodoc:
  module Relations #:nodoc:
    module Bindings #:nodoc:
      module Referenced #:nodoc:

        # Binding class for all referenced_in relations.
        class In < Binding

          # Binds the base object to the inverse of the relation. This is so we
          # are referenced to the actual objects themselves on both sides.
          #
          # This case sets the metadata on the inverse object as well as the
          # document itself.
          #
          # @example Bind the documents.
          #   game.person.bind(:continue => true)
          #   game.person = Person.new
          #
          # @param [ Hash ] options The binding options.
          #
          # @option options [ true, false ] :continue Continue binding the inverse.
          # @option options [ true, false ] :binding Are we in build mode?
          #
          # @since 2.0.0.rc.1
          def bind(options = {})
            inverse = metadata.inverse(target)
            base.send(metadata.foreign_key_setter, target.id)
            if metadata.inverse_type
              base.send(metadata.inverse_type_setter, target.class.model_name)
            end
            if inverse
              base.metadata = target.reflect_on_association(inverse)
              if options[:continue]
                if base.referenced_many?
                  target.do_or_do_not(
                    inverse, false, OPTIONS
                  ).push(base, :binding => true, :continue => false)
                else
                  target.do_or_do_not(
                    metadata.inverse_setter(target),
                    base,
                    OPTIONS
                  )
                end
              end
            end
          end
          alias :bind_one :bind

          # Unbinds the base object and the inverse, caused by setting the
          # reference to nil.
          #
          # @example Unbind the document.
          #   game.person.unbind(:continue => true)
          #   game.person = nil
          #
          # @param [ Hash ] options The options to pass through.
          #
          # @option options [ true, false ] :continue Do we continue unbinding?
          #
          # @since 2.0.0.rc.1
          def unbind(options = {})
            base.do_or_do_not(metadata.foreign_key_setter, nil)
            if options[:continue]
              target.do_or_do_not(metadata.inverse_setter(target), nil, OPTIONS)
            end
          end
          alias :unbind_one :unbind
        end
      end
    end
  end
end


text:
module RedmineAssetPipeline
  VERSION = "0.1.0"
end


text:
import React from "react";
const PropTypes = React.PropTypes;
import {Button} from "@blueprintjs/core";

const AddNewCard = props => (

			<button className={"pt-button pt-minimal pt-icon-cross"} onClick={props.onClose} />

			{/* TODO: extract component, maintaing spacing */}

				Title   {/* 3 spaces after 'Title' */}
				<input className="pt-input" style={{width: 200}} type="text"
					dir="auto" onChange={props.onUpdateTitle} />

				Tags  {/* 2 spaces after 'Tags' */}
				<input className="pt-input" style={{width: 200}} type="text"
					dir="auto" onChange={props.onUpdateTags} />

		<Button className="pt-intent-primary" text="Create" onClick={props.onSave} />

		<Button text="Discard" onClick={props.onClose}/>

);

AddNewCard.propTypes = {
	onSave: PropTypes.func.isRequired,
	onUpdateTitle: PropTypes.func.isRequired,
	onUpdateTags: PropTypes.func.isRequired,
	onClose: PropTypes.func.isRequired
};

export default AddNewCard;


text:
package io.github.benas.randombeans.beans;

import java.util.List;

public class ImmutableBean {

    private final String finalValue;

    private final List<String> finalCollection;

    public ImmutableBean(String finalValue, List<String> finalCollection) {
        this.finalValue = finalValue;
        this.finalCollection = finalCollection;
    }

    public String getFinalValue() {
        return finalValue;
    }

    public List<String> getFinalCollection() {
        return finalCollection;
    }
}


text:
/**
 * A vector is used to construct the vector space of documents and queries. These
 * vectors support operations to determine the similarity between two documents or
 * a document and a query.
 *
 * Normally no parameters are required for initializing a vector, but in the case of
 * loading a previously dumped vector the raw elements can be provided to the constructor.
 *
 * For performance reasons vectors are implemented with a flat array, where an elements
 * index is immediately followed by its value. E.g. [index, value, index, value]. This
 * allows the underlying array to be as sparse as possible and still offer decent
 * performance when being used for vector calculations.
 *
 * @constructor
 * @param {Number[]} [elements] - The flat list of element index and element value pairs.
 */
lunr.Vector = function (elements) {
  this._magnitude = 0
  this.elements = elements || []
}

/**
 * Calculates the position within the vector to insert a given index.
 *
 * This is used internally by insert and upsert. If there are duplicate indexes then
 * the position is returned as if the value for that index were to be updated, but it
 * is the callers responsibility to check whether there is a duplicate at that index
 *
 * @param {Number} insertIdx - The index at which the element should be inserted.
 * @returns {Number}
 */
lunr.Vector.prototype.positionForIndex = function (index) {
  // For an empty vector the tuple can be inserted at the beginning
  if (this.elements.length == 0) {
    return 0
  }

  var start = 0,
      end = this.elements.length / 2,
      sliceLength = end - start,
      pivotPoint = Math.floor(sliceLength / 2),
      pivotIndex = this.elements[pivotPoint * 2]

  while (sliceLength > 1) {
    if (pivotIndex < index) {
      start = pivotPoint
    }

    if (pivotIndex > index) {
      end = pivotPoint
    }

    if (pivotIndex == index) {
      break
    }

    sliceLength = end - start
    pivotPoint = start + Math.floor(sliceLength / 2)
    pivotIndex = this.elements[pivotPoint * 2]
  }

  if (pivotIndex == index) {
    return pivotPoint * 2
  }

  if (pivotIndex > index) {
    return pivotPoint * 2
  }

  if (pivotIndex < index) {
    return (pivotPoint + 1) * 2
  }
}

/**
 * Inserts an element at an index within the vector.
 *
 * Does not allow duplicates, will throw an error if there is already an entry
 * for this index.
 *
 * @param {Number} insertIdx - The index at which the element should be inserted.
 * @param {Number} val - The value to be inserted into the vector.
 */
lunr.Vector.prototype.insert = function (insertIdx, val) {
  this.upsert(insertIdx, val, function () {
    throw "duplicate index"
  })
}

/**
 * Inserts or updates an existing index within the vector.
 *
 * @param {Number} insertIdx - The index at which the element should be inserted.
 * @param {Number} val - The value to be inserted into the vector.
 * @param {function} fn - A function that is called for updates, the existing value and the
 * requested value are passed as arguments
 */
lunr.Vector.prototype.upsert = function (insertIdx, val, fn) {
  this._magnitude = 0
  var position = this.positionForIndex(insertIdx)

  if (this.elements[position] == insertIdx) {
    this.elements[position + 1] = fn(this.elements[position + 1], val)
  } else {
    this.elements.splice(position, 0, insertIdx, val)
  }
}

/**
 * Calculates the magnitude of this vector.
 *
 * @returns {Number}
 */
lunr.Vector.prototype.magnitude = function () {
  if (this._magnitude) return this._magnitude

  var sumOfSquares = 0,
      elementsLength = this.elements.length

  for (var i = 1; i < elementsLength; i += 2) {
    var val = this.elements[i]
    sumOfSquares += val * val
  }

  return this._magnitude = Math.sqrt(sumOfSquares)
}

/**
 * Calculates the dot product of this vector and another vector.
 *
 * @param {lunr.Vector} otherVector - The vector to compute the dot product with.
 * @returns {Number}
 */
lunr.Vector.prototype.dot = function (otherVector) {
  var dotProduct = 0,
      a = this.elements, b = otherVector.elements,
      aLen = a.length, bLen = b.length,
      aVal = 0, bVal = 0,
      i = 0, j = 0

  while (i < aLen && j < bLen) {
    aVal = a[i], bVal = b[j]
    if (aVal < bVal) {
      i += 2
    } else if (aVal > bVal) {
      j += 2
    } else if (aVal == bVal) {
      dotProduct += a[i + 1] * b[j + 1]
      i += 2
      j += 2
    }
  }

  return dotProduct
}

/**
 * Calculates the cosine similarity between this vector and another
 * vector.
 *
 * @param {lunr.Vector} otherVector - The other vector to calculate the
 * similarity with.
 * @returns {Number}
 */
lunr.Vector.prototype.similarity = function (otherVector) {
  return this.dot(otherVector) / (this.magnitude() * otherVector.magnitude())
}

/**
 * Converts the vector to an array of the elements within the vector.
 *
 * @returns {Number[]}
 */
lunr.Vector.prototype.toArray = function () {
  var output = new Array (this.elements.length / 2)

  for (var i = 1, j = 0; i < this.elements.length; i += 2, j++) {
    output[j] = this.elements[i]
  }

  return output
}

/**
 * A JSON serializable representation of the vector.
 *
 * @returns {Number[]}
 */
lunr.Vector.prototype.toJSON = function () {
  return this.elements
}


text:
<?php
$key = "Cell Rendering";
$pageTitle = "Angular Grid Cell Rendering";
$pageDescription = "You can customise every cell in Angular Grid. This is done by providing cell renderers. This page describe creating cell renderers.";
$pageKeyboards = "Angular Grid Cell Renderers";
include '../documentation_header.php';
?>

Cell Rendering

        Cell Rendering - this is a very powerful feature in Angular Grid. With this, you can put whatever
        you want in the grid. The job of the grid is to lay out the cells. What goes into the cells,
        that's where you come in!

        A cell renderer is a function that when called, returns HTML (either a Dom or Node element, or an HTML string).

        You can use a cell renderer for the following reasons:

The data needs to be formatted before displaying.

The cell should be rendered using more complex HTML thanks just a string.

        Below are some simple examples of cell rendering:

// example - make the value upper case
var colDef = {
    name: 'Col Name',
    field' 'Col Field',
    cellRenderer: function(params) {
        if (params.value=='Police') {
            return 'POLICE';
        } else {
            return params.value.toUpperCase();
        }
    }
}

// example - grab the field from a complex object (although possible, you should do this in a valueGetter)
var colDef = {
    name: 'Col Name',
    cellRenderer: function(params) {
        return params.data.field.deepObject.someName.value;
    }
}

// example - join two fields together (but you would probably do this with a value getter)
var colDef = {
    name: 'Col Name',
    cellRenderer: function(params) {
        return params.data.firstName + ' ' + params.data.lastName;
    }
}

// complex html, no Angular JS
var colDef = {
    name: 'Col Name',
    cellRenderer: function(params) {
        return '<span title="the tooltip">'+params.data.value+'</span>';
    }
}

// complex html, with Angular JS - need to have angularCompileRows=true in gridOptions
var colDef = {
    name: 'Col Name',
    cellRenderer: function(params) {
        return '<span title="the tooltip">{{value}}</span>';
    }
}

Cell Renderer Params

    Cell renderer functions take a params object with the following values:

            Value
            Description

            value
            The value to be rendered.

            data
            The row (from the rowData array, where value was taken) been rendered.

            colDef
            The colDef been rendered.

            column
            The column been rendered (in ag-Grid, each colDef is wrapped by a Column).

            $scope
            If compiling to Angular, is the row's child scope, otherwise null.

            rowIndex
            The index of the row renderer, after sorting and filtering.

            api
            A reference to the ag-Grid api.

            context
            The context as set on the gridOptions.

            refreshCell
            A callback function, to tell the grid to refresh this cell and reapply all css styles and classes.
            Useful if you update the data for the cell and want to just render again from scratch.

            valueGetter
            A function, that when called, gives you the value, calling the relevant valueGetter / expression
            if neccessary. This can be called at any time after rendering, so you could implement some kind of
            refresh and get the latest value this way when the 'value' param would be stale.

            eGridCell
            A reference to the virtual cell (during the rendering process, virtual cells are used).

Angular Compiling

    When using Angular Compiling, a new scope is created for each row. The data for the
    row is attached to the scope as 'data'.

Example: Formatting Cells

    The below example shows three columns formatted, demonstrating each of the three
    methods above.

    'Athlete' column uses cellStyle to format each cell in the column with the same style.

    'Age' column uses cellStyle to format each cell with the capital letter 'C'.

    'Gold' column renders the cell from scratch, by adding a gold star image for each
    gold medal won.

    <show-example example="example1"></show-example>

<?php include '../documentation_footer.php';?>


text:
Bash Flatten Folder script
==========================

Script that converts file tree into flat folder. File names in flat folder reflect their place in file tree. For example `dir1/dir2/file` will be renamed to `dir1__dir2__file`

It is useful for example for android developers. Android SDK doesn't support inner folders in drawable-Xdpi. But quite serious design includes lots of sliced images, that is usually grouped into folders. So here are two advantages of such a script: you shouldn't copy all files to the root directory manually and it saves the structure of files

Options
-------

- `-s DIR, --src DIR` Specify the source directory. By default it is set to `./`
- `-d DIR, --dst DIR` Specify the destination directory. By default it is set to `OUTPUT`
- `-D DELIMITER`  Specify the delimiter that is used to replace `/` when converting file names. By default it is set to `__`

Usage
-----

For example we have a `design` folder with the following structure:

```
$ tree ./design
./design
├── hdpi
│   ├── contacts
│   │   ├── ic_add_contact.png
│   │   └── ic_edit_contact.png
│   ├── home
│   │   ├── ic_logout.png
│   │   └── ic_menu_main.png
│   ├── logo.png
│   ├── settings
│   │   ├── ic_department.png
│   │   └── img_profile_photo.png
│   └── tutorial.png
└── mdpi
    ├── contacts
    │   ├── ic_add_contact.png
    │   └── ic_edit_contact.png
    ├── home
    │   ├── ic_logout.png
    │   └── ic_menu_main.png
    ├── logo.png
    ├── settings
    │   ├── ic_department.png
    │   └── img_profile_photo.png
    └── tutorial.png
```

There is a simple and easy-to-customize `flatten_drawables.sh` sample script:
```
#!/bin/bash

OUTPUT_FOLDER=OUTPUT
DESIGN_FOLDER=design

rm -rf $OUTPUT_FOLDER

for dpi in hdpi mdpi;
do
  ./flatten_folder.sh --src $DESIGN_FOLDER/$dpi  --dst $OUTPUT_FOLDER/$dpi
done
```

This script converts the previous structure to

```
$ tree OUTPUT/
OUTPUT/
├── hdpi
│   ├── contacts__ic_add_contact.png
│   ├── contacts__ic_edit_contact.png
│   ├── home__ic_logout.png
│   ├── home__ic_menu_main.png
│   ├── logo.png
│   ├── settings__ic_department.png
│   ├── settings__img_profile_photo.png
│   └── tutorial.png
└── mdpi
    ├── contacts__ic_add_contact.png
    ├── contacts__ic_edit_contact.png
    ├── home__ic_logout.png
    ├── home__ic_menu_main.png
    ├── logo.png
    ├── settings__ic_department.png
    ├── settings__img_profile_photo.png
    └── tutorial.png
```


text:
Crud API
========

This project takes its name from the acronym Create/Read/Update/Delete. It provides a generic, foundational abstraction for accessing and manipulating state in the Java programming language. This abstraction is implemented by other projects in the `crud-*` family—for example, [Crud HTTP](https://github.com/rickbw/crud-http) contains an HTTP-based implementation.

The Crud API supports data-oriented interactions based on generic _Resources_, which encapsulate state and build upon the [Observable](https://github.com/Netflix/RxJava/blob/master/rxjava-core/src/main/java/rx/Observable.java) abstraction from [RxJava](https://github.com/Netflix/RxJava/). The design emphasizes generality, safety and concurrency.

* _Generality_: The available interactions consist of simple read and write operations.
* _Safety_: The types of resources are statically type-safe,  configured by means of generic type parameters..
* _Concurrency_: The API encourages asynchronous implementations. It encapsulates asynchrony using RxJava's `Observable` class. This encapsulation means that applications can work with asynchronous implementations just as easily as synchronous ones, and cross-cutting behaviors like retries can be transparently composed as needed.

API Overview
------------
There are two primary abstractions in the API: `Resources` and `ResourceSets`. The former encapsulate the I/O operations on state, and hence uses a reactive style. There are two interfaces derived from [Resource](https://github.com/rickbw/crud-api/blob/master/src/main/java/rickbw/crud/core/Resource.java):
* [ReadableResource](https://github.com/rickbw/crud-api/blob/master/src/main/java/rickbw/crud/core/ReadableResource.java)
* [WritableResource](https://github.com/rickbw/crud-api/blob/master/src/main/java/rickbw/crud/core/WritableResource.java)

The latter abstraction, `ResourceSet`, provides local (i.e. assumed-cheap) navigation among `Resources`. This navigation uses a key-value lookup idiom, where keys are generic and may be simple—e.g. a URL—or arbitrarily complex—e.g. a database query—depending on the underlying data-access technology. There are two derived [ResourceSet](https://github.com/rickbw/crud-api/blob/master/src/main/java/rickbw/crud/core/ResourceSet.java) interfaces:
* [ReadableResourceSet](https://github.com/rickbw/crud-api/blob/master/src/main/java/rickbw/crud/core/ReadableResourceSet.java)
* [WritableResourceSet](https://github.com/rickbw/crud-api/blob/master/src/main/java/rickbw/crud/core/WritableResourceSet.java)

See Also
--------
* The [Crud HTTP](https://github.com/rickbw/crud-http) project (`crud-http`) implements this API for HTTP, based on [Jersey](https://jersey.java.net).
* The [Crud JDBC](https://github.com/rickbw/crud-jdbc) project (`crud-jdbc`) implements this API for JDBC.
* The [Crud Voldemort](https://github.com/rickbw/crud-voldemort) project (`crud-voldemort`) implements this API for [Project Voldemort](http://www.project-voldemort.com).

Copyright and License
---------------------
All files in this project are copyright Rick Warren and, unless otherwise noted, licensed under the terms of the Apache 2 license.


text:
package com.thoughtworks.xstream.converters.extended;

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
import java.util.Currency;

public class CurrencyConverter extends AbstractSingleValueConverter
{
  public boolean canConvert(Class paramClass)
  {
    return paramClass.equals(Currency.class);
  }

  public Object fromString(String paramString)
  {
    return Currency.getInstance(paramString);
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.thoughtworks.xstream.converters.extended.CurrencyConverter
 * JD-Core Version:    0.6.2
 */


text:
namespace blink {

// `UseCounterFeature` is a union of enum feature types that UseCounter can
// count, e.g. mojom::WebFeature.
class BLINK_COMMON_EXPORT UseCounterFeature {
 public:
  using EnumValue = uint32_t;

  // The default constructor should only be called by mojom interface.
  UseCounterFeature() = default;

  UseCounterFeature(mojom::UseCounterFeatureType type, EnumValue value);

  // Getters.
  mojom::UseCounterFeatureType type() const { return type_; }
  EnumValue value() const { return value_; }

  // Used for mojom traits only. Returns whether the input params are valid.
  bool SetTypeAndValue(mojom::UseCounterFeatureType type, EnumValue value);

  bool operator==(const UseCounterFeature& rhs) const;
  bool operator<(const UseCounterFeature& rhs) const;

 private:
  // Bound check `value_` field based on `type_`;
  bool IsValid() const;

  mojom::UseCounterFeatureType type_;
  EnumValue value_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_PUBLIC_COMMON_USE_COUNTER_USE_COUNTER_FEATURE_H_


text:
import pytest ; pytest

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# External imports
import mock

# Bokeh imports
from bokeh.core.validation import check_integrity
from bokeh.models import LayoutDOM

# Module under test
from bokeh.models.tools import Tool, Toolbar, ToolbarBox # isort:skip
import bokeh.models.tools as t # isort:skip

#-----------------------------------------------------------------------------
# Setup
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------

def test_Tool_from_string() -> None:
    assert isinstance(Tool.from_string("pan"), t.PanTool)
    assert isinstance(Tool.from_string("xpan"), t.PanTool)
    assert isinstance(Tool.from_string("ypan"), t.PanTool)
    assert isinstance(Tool.from_string("xwheel_pan"), t.WheelPanTool)
    assert isinstance(Tool.from_string("ywheel_pan"), t.WheelPanTool)
    assert isinstance(Tool.from_string("wheel_zoom"), t.WheelZoomTool)
    assert isinstance(Tool.from_string("xwheel_zoom"), t.WheelZoomTool)
    assert isinstance(Tool.from_string("ywheel_zoom"), t.WheelZoomTool)
    assert isinstance(Tool.from_string("zoom_in"), t.ZoomInTool)
    assert isinstance(Tool.from_string("xzoom_in"), t.ZoomInTool)
    assert isinstance(Tool.from_string("yzoom_in"), t.ZoomInTool)
    assert isinstance(Tool.from_string("zoom_out"), t.ZoomOutTool)
    assert isinstance(Tool.from_string("xzoom_out"), t.ZoomOutTool)
    assert isinstance(Tool.from_string("yzoom_out"), t.ZoomOutTool)
    assert isinstance(Tool.from_string("click"), t.TapTool)
    assert isinstance(Tool.from_string("tap"), t.TapTool)
    assert isinstance(Tool.from_string("crosshair"), t.CrosshairTool)
    assert isinstance(Tool.from_string("box_select"), t.BoxSelectTool)
    assert isinstance(Tool.from_string("xbox_select"), t.BoxSelectTool)
    assert isinstance(Tool.from_string("ybox_select"), t.BoxSelectTool)
    assert isinstance(Tool.from_string("poly_select"), t.PolySelectTool)
    assert isinstance(Tool.from_string("lasso_select"), t.LassoSelectTool)
    assert isinstance(Tool.from_string("line_edit"), t.LineEditTool)
    assert isinstance(Tool.from_string("box_zoom"), t.BoxZoomTool)
    assert isinstance(Tool.from_string("xbox_zoom"), t.BoxZoomTool)
    assert isinstance(Tool.from_string("ybox_zoom"), t.BoxZoomTool)
    assert isinstance(Tool.from_string("save"), t.SaveTool)
    assert isinstance(Tool.from_string("undo"), t.UndoTool)
    assert isinstance(Tool.from_string("redo"), t.RedoTool)
    assert isinstance(Tool.from_string("reset"), t.ResetTool)
    assert isinstance(Tool.from_string("help"), t.HelpTool)
    assert isinstance(Tool.from_string("box_edit"), t.BoxEditTool)
    assert isinstance(Tool.from_string("point_draw"), t.PointDrawTool)
    assert isinstance(Tool.from_string("poly_draw"), t.PolyDrawTool)
    assert isinstance(Tool.from_string("poly_edit"), t.PolyEditTool)
    assert isinstance(Tool.from_string("hover"), t.HoverTool)

def test_Toolbar() -> None:
    tb = Toolbar()
    assert tb.active_drag == 'auto'
    assert tb.active_inspect == 'auto'
    assert tb.active_scroll == 'auto'
    assert tb.active_tap == 'auto'
    assert tb.autohide is False

def test_Toolbar_with_autohide() -> None:
    tb = Toolbar(autohide=True)
    assert tb.active_drag == 'auto'
    assert tb.active_inspect == 'auto'
    assert tb.active_scroll == 'auto'
    assert tb.active_tap == 'auto'
    assert tb.autohide is True

#
# ToolbarBox
#

def test_toolbar_box_is_instance_of_LayoutDOM() -> None:
    tb_box = ToolbarBox()
    assert isinstance(tb_box, LayoutDOM)

def test_toolbar_box_properties() -> None:
    tb_box = ToolbarBox()
    assert tb_box.toolbar_location == "right"

@mock.patch('bokeh.io.showing._show_with_state')
def test_toolbar_box_with_no_children_does_not_raise_a_bokeh_warning(mock__show_with_state) -> None:
    # This is the normal way a ToolbarBox would be instantiated for example in
    # a gridplot. So we don't want to worry people with warnings. The children
    # for the ToolbarBox are created on the JS side.

    tb_box = ToolbarBox()
    with mock.patch('bokeh.core.validation.check.log') as mock_logger:
        check_integrity([tb_box])
        assert mock_logger.warning.call_count == 0

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------


text:
__author__ = 'CubexX'

import hashlib
import json
from datetime import datetime

from flask import redirect, render_template, request, session

from app import CONFIG, app
from app.models import Chat, Entity, Message, User, UserStat

def login_required(func):
    def wrapper(*args, **kwargs):
        if not session or session['hash'] != generate_hash(CONFIG['password']):
            return redirect('/admin/login')
        else:
            return func(*args, **kwargs)

    wrapper.__name__ = func.__name__
    return wrapper

@app.route('/admin')
@app.route('/admin/')
@login_required
def admin_index_view():
    stats = {'all_active_users': User.count(),
             'today_active_users': User.today_all_active_users(),
             'all_chats': Chat.count(),
             'today_chats': Chat.today_new_count(),
             'all_messages': sum(u.msg_count for u in UserStat.all()),
             'today_messages': Message.today_all_count(),
             'last_chats': Chat.last_chats_list()}

    return render_template('admin/index.html',
                           stats=stats,
                           entities=Entity.generate_list()[0],
                           format_time=format_time)

@app.route('/admin/login', methods=['GET', 'POST'])
def login_view():
    if request.method == 'POST':
        session['hash'] = generate_hash(request.form['password'])

        if session['hash'] == generate_hash(CONFIG['password']):
            return redirect('/admin')
        else:
            return redirect('/admin/login')
    return render_template('admin/login.html')

@app.route('/admin/exit')
def exit_admin_view():
    session.pop('hash', None)
    return redirect('/')

@app.route('/admin/logs', methods=['GET', 'POST'])
@login_required
def logs_view():
    return render_template('admin/logs.html', logs=get_logs())

@app.route('/admin/settings', methods=['GET', 'POST'])
@login_required
def settings_view():
    with open('config.json', 'r') as jsonFile:
        data = json.load(jsonFile)

    if request.method == 'POST':
        form = request.form

        if form['db_driver']:
            data['db']['driver'] = form['db_driver']

        if form['db_host']:
            data['db']['host'] = form['db_host']

        if form['db_database']:
            data['db']['database'] = form['db_database']

        if form['db_user']:
            data['db']['user'] = form['db_user']

        if form['db_password']:
            data['db']['password'] = form['db_password']

        if form['cache_server']:
            data['cache']['servers'][0] = form['cache_server']

        if form['cache_debug']:
            data['cache']['debug'] = bool(int(form['cache_debug']))

        if form['admin_password']:
            data['password'] = form['admin_password']

        if form['salt']:
            data['salt'] = form['salt']

        with open("config.json", "w") as jsonFile:
            json.dump(data, jsonFile)

    return render_template('admin/settings.html', data=data)

def format_time(ts):
    return datetime.fromtimestamp(ts).strftime('%H:%M, %d.%m.%y')

def generate_hash(text):
    text = str(text).encode('utf-8')
    salt = str(CONFIG['salt']).encode('utf-8')

    return hashlib.md5(text + salt).hexdigest()

def get_logs():
    try:
        # TODO: fix path
        with open('../confstat-bot/bot.log', 'r') as log:
            log = log.read()
            log_list = [line.split(' - ') for line in reversed(log.split('\n')) if "Timed out" not in line]

            return log_list[1:51]

    except FileNotFoundError:
        return []


text:
"""Reorder sys.path to put $VTROOT/dist/* paths before others.

This ensures libraries installed there will be preferred over other versions
that may be present at the system level. We do this at runtime because
regardless of what we set in the PYTHONPATH environment variable, the system
dist-packages folder gets prepended sometimes.

To use this, just import it before importing packages that you want to make
sure are overridden from $VTROOT/dist.

from vtdb import prefer_vtroot_imports  # pylint: disable=unused-import
"""

import os
import sys

def _prefer_vtroot_imports():
  """Reorder sys.path to put $VTROOT/dist before others."""

  vtroot = os.environ.get('VTROOT')
  if not vtroot:
    # VTROOT is not set. Don't try anything.
    return
  dist = os.path.join(vtroot, 'dist')

  dist_paths = []
  other_paths = []

  for path in sys.path:
    if path:
      if path.startswith(dist):
        dist_paths.append(path)
      else:
        other_paths.append(path)

  sys.path = [''] + dist_paths + other_paths

_prefer_vtroot_imports()


text:
package io.fabric8.gateway.apiman.rest;

import io.apiman.gateway.engine.async.IAsyncResult;
import io.apiman.gateway.engine.async.IAsyncResultHandler;
import io.apiman.gateway.engine.beans.Application;
import io.apiman.gateway.engine.beans.Service;
import io.apiman.gateway.engine.beans.ServiceEndpoint;
import io.fabric8.gateway.apiman.ApiManEngine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServerRequest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RestDispatcher {

	private static final transient Logger LOG = LoggerFactory.getLogger(RestDispatcher.class);
	private ObjectMapper mapper;

	public ObjectMapper getObjectMapper() {
		if (mapper == null) {
			mapper = new ObjectMapper();
		}
		return mapper;
	}

	public void dispatch(final HttpServerRequest request, final ApiManEngine engine) {

		//check headers
		LOG.info("Request: " + request.method() + " " + request.uri() + " from " + request.remoteAddress());
		if (request.method().equals("PUT")) {
			String contentType = request.headers().get("Content-Type");
			contentType = contentType.toUpperCase();
			if (contentType==null || !contentType.startsWith("APPLICATION/JSON")) {
				request.response().setStatusCode(403);
				request.response().end("Expecting Content-Type of 'application/json'");
				LOG.error("Expecting Content-Type of 'application/json");
				return;
			}
			if (contentType==null || !contentType.endsWith("UTF-8")) {
				request.response().setStatusCode(403);
				request.response().end("Expecting charset of 'UTF-8'");
				request.response().close();
				LOG.error("Expecting charset of 'UTF-8'");
				return;
			}
		}
		//read the body
		request.bodyHandler(new Handler<Buffer>() {

			@Override
			public void handle(Buffer event) {
				try {
					String body = event.getString(0, event.length());
					String uri = request.uri().substring(1);
					if (uri.contains("?")) uri = uri.substring(0, uri.indexOf("?"));
					String[] pathSegment = uri.split("/");

					// The async response handler used for all the void IRegistry calls
                    IAsyncResultHandler<Void> voidHandler = new IAsyncResultHandler<Void>() {
                        @Override
                        public void handle(IAsyncResult<Void> result) {
                            if (result.isError()) {
                                Throwable e = result.getError();
                                writeError(request, e);
                            } else {
                                request.response().setStatusCode(200);
                                request.response().end();
                            }
                        }
                    };

					if (uri.startsWith("rest/apimanager/applications")) {
						if (request.method().equals("PUT")) {
							Application application = getObjectMapper().readValue(body, Application.class);
                            engine.getRegistry().registerApplication(application, voidHandler);
						} else if (request.method().equals("DELETE"))  {
							//path {organizationId}/{applicationId}/{version}
							if (pathSegment.length < 6) {
							    throw new UserException("Query Parse Exception , expecting /rest/apimanager/applications/{organizationId}/{applicationId}/{version}");
							}
							Application application = new Application();
					        application.setOrganizationId(pathSegment[3]);
					        application.setApplicationId(pathSegment[4]);
					        application.setVersion(pathSegment[5]);
                            engine.getRegistry().unregisterApplication(application, voidHandler);
						} else {
							throw new UserException("Method not Supported");
						}
					} else if (uri.startsWith("rest/apimanager/services")) {
						if (request.method().equals("PUT")) {
							Service service = getObjectMapper().readValue(body, Service.class);
							engine.getRegistry().publishService(service, voidHandler);
							LOG.info("Published to Registry " + service.getEndpoint());
						}
						else if (request.method().equals("DELETE"))  {
							//path {organizationId}/{serviceId}/{version}
							if (pathSegment.length < 6) throw new UserException("Query Parse Exception , "
									+ "expecting /rest/apimanager/applications/{organizationId}/{serviceId}/{version}");
					        Service service = new Service();
					        service.setOrganizationId(pathSegment[3]);
					        service.setServiceId(pathSegment[4]);
					        service.setVersion(pathSegment[5]);
                            engine.getRegistry().retireService(service , voidHandler);
                            LOG.info("Retired service " + service.getOrganizationId() + "/" + service.getServiceId() + ", version " + service.getVersion());
						} else if (request.method().equals("GET")) {
							//path {organizationId}/{serviceId}/{version}
							if (pathSegment.length < 7) throw new UserException("Query Parse Exception , "
									+ "expecting /rest/apimanager/applications/{organizationId}/{serviceId}/{version}/endpoint");
							String organizationId = pathSegment[3];
							String serviceId = pathSegment[4];
					        String version = pathSegment[5];

					        engine.getRegistry().getService(organizationId, serviceId, version, new IAsyncResultHandler<Service>() {
                                @Override
                                public void handle(IAsyncResult<Service> result) {
                                    if (result.isError()) {
                                        Throwable e = result.getError();
                                        writeError(request, e);
                                    } else {
                                        Service service = result.getResult();
                                        ServiceEndpoint serviceEndpoint = new ServiceEndpoint();
                                        serviceEndpoint.setEndpoint(engine.serviceMapping(service));
                                        try {
                                            String json = getObjectMapper().writeValueAsString(serviceEndpoint);
                                            request.response().headers().set("ContentType", "application/json");
                                            request.response().headers().set("Content-Length", String.valueOf(json.length()));
                                            request.response().write(json);
                                            request.response().setStatusCode(200);
                                            request.response().end();
                                        } catch (JsonProcessingException e) {
                                            writeError(request, e);
                                        }
                                    }
                                }
                            });
						} else {
							throw new UserException("Method not Supported");
						}

					} else if (uri.startsWith("rest/apimanager/system/status")) {
						SystemResource systemResource = new SystemResource(engine);
						String json = getObjectMapper().writeValueAsString(systemResource.getStatus());
						request.response().headers().set("ContentType", "application/json");
						request.response().headers().set("Content-Length", String.valueOf(json.length()));
						request.response().write(json);
	                    request.response().setStatusCode(200);
	                    request.response().end();
					} else {
						throw new UserException("No Such Service");
					}
				} catch (UserException e) {
					LOG.error(e.getMessage(),e);
					request.response().setStatusCode(404);
					request.response().setStatusMessage(e.getMessage());
					request.response().end();
				} catch (Throwable e) {
				    writeError(request, e);
				}
			}

		});
	}

    protected static void writeError(final HttpServerRequest request, Throwable e) {
        LOG.error(e.getMessage(), e);
        request.response().setStatusCode(500);
        request.response().setStatusMessage(e.getMessage());
        request.response().end();
    }

}


text:
import robotarium
from numpy.testing import assert_allclose

def test_complete_gl():
    n = 5
    graph = robotarium.graph.complete_gl(n)
    print(graph)
    assert graph.sum() == 0
    assert_allclose(graph.diagonal(), n - 1)
    assert_allclose(graph.sum(axis=1), 0)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biblthca Lichenol. 18: 164 (1983)

#### Original name
Megalospora kalbii Sipman

### Remarks
null


text:
```java
public class OnlineReaderSystem {
	private Library library;
	private UserManager userManager;
	private Display display;
	private Book activeBook;
	private User activeUser;

	public OnlineReaderSystem() {
		userManager = new UserManager();
		library = new Library();
		display = new Display();
	}

	public Library getLibrary() {
		return library;
	}

	public UserManager getUserManager() {
		return userManager;
	}

	public Display getDisplay() {
		return display;
	}

	public Book getActiveBook() {
		return activeBook;
	}

	public void setActiveBook(Book book) {
		activeBook = book;
		display.displayBook(book);
	}

	public User getActiveUser() {
		return activeUser;
	}

	public void setUser(User user) {
		activeUser = user;
	}

}

public class Library {
	Private HashTable<Integer, Book> books;

	public Book addBook() {

	}

	public boolean remove(Book b){}
	public boolean remove(int id){}

	public Book find(int id) {}
}

public class UserManager {
	private Hashtable<Integer, User> users;

	public User addUser(int id, String details, int accountType) {
		if (users.containsKey(id)) {
			return null;
		}

		User user = new User(id, details, accountType);
		user.put(id, user);
		return user;
	}

	public boolean remove(User u) {
		return remove(u.getID());
	}

	public boolean remove(int id) {
		if (!users.containsKey(id)) {
			return false;
		}

		return users.remove(id);
	}

	public User find(int id) {
		return users.get(id);
	}
}

public class Display {
	private Book activeBook;
	private User activeUser;
	private int pageNumber = 0;

	public void displayUser(User user){}
	public void displayBook(Book book){}
	public void turnPageForward() {}
	public void turnPageBackward(){}

	// Refresh functions
}

public class Book {
	private int bookId;
	private String details;

	public Book (int id, int det) {}

	public int getID(){}
	public void setID(){}
	public String getDetails(){}
	public void setDetails(){}
}

public class User {
	private int userId;
	private String details;
	private int accountType;

	public void renewMembership() {}

	public User (int id, String details, int accountType){}

	//getters and setters
}
```


text:
var assert = require('assert')
var exec = require('child_process').exec

var exists = require('command-exists')
var toFlags = require('to-flags')
var xtend = require('xtend')

module.exports = function ebookConvert (args, options, callback) {
  assert.equal(typeof args, 'object', 'args object is required')
  assert.equal(typeof args.input, 'string', 'string filepath of input file is required')
  assert.equal(typeof args.output, 'string', 'string filepath of output file is required')

  if (typeof options === 'function') {
    callback = options
    options = {}
  }

  var input = args.input
  var output = args.output
  delete args.input
  delete args.output

  exists('ebook-convert', function (err, ok) {
    if (err || !ok) {
      var msg = 'Error: ebook-convert command must be installed as part of calibre. Find instructions at http://calibre-ebook.com'
      return callback(new Error(msg))
    }
    args = toFlags(args).join(' ')
    var cmd = 'ebook-convert ' + input + ' ' + output + ' ' + args
    exec(cmd, options, callback)
  })
}


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > A New Girlfriend

						Expand All | Collapse All

A New Girlfriend

 By Thursday, John was very tired. He got a call from his girlfriend. John decided not to answer. "I think I like my couch more than my girlfriend," he said.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
@interface FJTitleButton : UIButton

@end


text:
@protocol P0
@property(readonly,assign) id X; // expected-warning {{property attributes 'readonly' and 'assign' are mutually exclusive}}
@end

@protocol P1
@property(readonly,retain) id X; // expected-warning {{property attributes 'readonly' and 'retain' are mutually exclusive}}
@end

@protocol P2
@property(readonly,copy) id X; // expected-warning {{property attributes 'readonly' and 'copy' are mutually exclusive}}
@end

@protocol P3
@property(readonly,readwrite) id X; // expected-error {{property attributes 'readonly' and 'readwrite' are mutually exclusive}}
@end

@protocol P4
@property(assign,copy) id X; // expected-error {{property attributes 'assign' and 'copy' are mutually exclusive}}
@end

@protocol P5
@property(assign,retain) id X; // expected-error {{property attributes 'assign' and 'retain' are mutually exclusive}}
@end

@protocol P6
@property(copy,retain) id X; // expected-error {{property attributes 'copy' and 'retain' are mutually exclusive}}
@end


text:
using System;

namespace ZipStream
{
	public class ZipStreamEntry
    {
        static string[] _compressionMethods = new string[]{
            "store",
            "shrunk",
            "reduce1",
            "reduce2",
            "reduce3",
            "reduce4",
            "implode",
            "token",
            "deflate",
            "deflate64",
            "pkware",
            "reserved",
            "bzip2"
        };

        // only supported compression types
        public const int COMPRESS_STORE    = 0;
        public const int COMPRESS_DEFLATE  = 8;

        internal int _signature;
        internal short _version;
        internal short _flags;
        internal short _compression;
        internal short _time;
        internal short _date;
        internal int _crc32;
        internal int _compressedLength;
        internal int _uncompressedLength;
        internal short _nameLength;
        internal short _extraLength;
        internal byte[] _fileName;
        internal byte[] _extraField;

        public int Signature {
            get {
                return _signature;
            }
        }

        public short Version {
            get {
                return _version;
            }
        }

        public short Flags {
            get {
                return _flags;
            }
        }

        public short CompressionMethod {
            get {
                return _compression;
            }
        }

        public string CompressionMethodName {
            get {
                return _compressionMethods[_compression];
            }
        }

        public short ModificationTime {
            get {
                return _time;
            }
        }

        public short ModificationDate {
            get {
                return _date;
            }
        }

        public int CRC32 {
            get {
                return _crc32;
            }
        }

        public int CompressedLength {
            get {
                return _compressedLength;
            }
        }

        public int UncompressedLength {
            get {
                return _uncompressedLength;
            }
        }

        public short NameLength {
            get {
                return _nameLength;
            }
        }

        public short ExtraLength {
            get {
                return _extraLength;
            }
        }

        public String FileName {
            get {
                return System.Text.Encoding.UTF8.GetString(_fileName);
            }
        }

        internal ZipStreamEntry()
        {

        }

        public override string ToString()
        {
            string dump = "";
            dump += String.Format("Signature   : {0,8:X8}\n", Signature);
            dump += String.Format("Version     : {0,8:X8}\n", Version);
            dump += String.Format("Flags       : {0,8:X8}\n", Flags);
            dump += String.Format("Compression : {0,8:X8} ({1})\n", CompressionMethod, CompressionMethodName);
            dump += String.Format("Time        : {0,8:X8}\n", ModificationTime);
            dump += String.Format("Date        : {0,8:X8}\n", ModificationDate);
            dump += String.Format("CRC32       : {0,8:X8}\n", CRC32);
            dump += String.Format("CompSize    : {0}\n", CompressedLength);
            dump += String.Format("Size        : {0}\n", UncompressedLength);
            dump += String.Format("NameLength  : {0}\n", NameLength);
            dump += String.Format("ExtraLength : {0}\n", ExtraLength);
            dump += String.Format("Name:       : {0}\n", FileName);
            return dump;
        }
    }
}


text:
<?php

namespace App\Form\Type;

use FOS\UserBundle\Form\Type\RegistrationFormType;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationTypeExtension extends AbstractTypeExtension
{
    /**
     * @return iterable The name of the type being extended
     */
    public static function getExtendedTypes(): iterable
    {
        return [RegistrationFormType::class];
    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('firstname', TextType::class,
                ['label' => 'registration.firstname', 'translation_domain' => 'ShopBundle'])
            ->add('lastname', TextType::class,
                ['label' => 'registration.lastname', 'translation_domain' => 'ShopBundle'])
            ->add('phone', TextType::class,
                ['label' => 'registration.phone', 'translation_domain' => 'ShopBundle'])
            ->add('address', TextareaType::class,
                ['label' => 'registration.address', 'translation_domain' => 'ShopBundle']);
    }
}


text:
namespace AngleSharp.Parser.Css
{
    using AngleSharp.Extensions;
    using System;
    using System.Collections.Generic;
    using System.Globalization;

    /// <summary>
    /// Represents the CSS range token.
    /// </summary>
    sealed class CssRangeToken : CssToken
    {
        #region Fields

        readonly String[] _range;
        readonly String _start;
        readonly String _end;

        #endregion

        #region ctor

        /// <summary>
        /// Creates a new CSS range token.
        /// </summary>
        /// <param name="range">The selected range string.</param>
        /// <param name="position">The token's position.</param>
        public CssRangeToken(String range, TextPosition position)
            : base(CssTokenType.Range, range, position)
        {
            _start = range.Replace(Symbols.QuestionMark, '0');
            _end = range.Replace(Symbols.QuestionMark, 'F');
            _range = GetRange();
        }

        /// <summary>
        /// Creates a new CSS range token.
        /// </summary>
        /// <param name="start">The selected range's start.</param>
        /// <param name="end">The selected range's end.</param>
        /// <param name="position">The token's position.</param>
        public CssRangeToken(String start, String end, TextPosition position)
            : base(CssTokenType.Range, String.Concat(start, "-", end), position)
        {
            _start = start;
            _end = end;
            _range = GetRange();

        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets the status of the range.
        /// </summary>
        public Boolean IsEmpty
        {
            get { return _range == null || _range.Length == 0; }
        }

        /// <summary>
        /// Gets the range's start.
        /// </summary>
        public String Start
        {
            get { return _start; }
        }

        /// <summary>
        /// Gets the range's end.
        /// </summary>
        public String End
        {
            get { return _end; }
        }

        /// <summary>
        /// Gets the content of the range token.
        /// </summary>
        public String[] SelectedRange
        {
            get { return _range; }
        }

        #endregion

        #region Helpers

        String[] GetRange()
        {
            var index = Int32.Parse(_start, NumberStyles.HexNumber);

            if (index <= Symbols.MaximumCodepoint)
            {
                if (_end != null)
                {
                    var list = new List<String>();
                    var f = Int32.Parse(_end, NumberStyles.HexNumber);

                    if (f > Symbols.MaximumCodepoint)
                    {
                        f = Symbols.MaximumCodepoint;
                    }

                    while (index <= f)
                    {
                        list.Add(index.ConvertFromUtf32());
                        index++;
                    }

                    return list.ToArray();
                }

                return new String[] { index.ConvertFromUtf32() };
            }

            return null;
        }

        #endregion
    }
}


text:
import Tensor from './Tensor'
import { webgl2 } from './WebGL2'
import ops from 'ndarray-ops'

/**
 * Layer class
 */
export default class Layer {
  /**
   * Creates a layer
   * @param {Object} [attrs] - layer attributes
   */
  constructor(attrs = {}) {
    this.layerClass = 'Layer'
    this.name = attrs.name
    this.gpu = webgl2.isSupported && attrs.gpu

    this.params = []
    this.weights = {}

    this.inbound = []
    this.outbound = []
  }

  /**
   * Set layer weights
   *
   * @param {Tensor[]} weightsArr - array of weights which are instances of Tensor
   */
  setWeights(weightsArr, createGLTexture = true) {
    this.params.forEach((p, i) => {
      this.weights[p] = weightsArr[i]

      if (this.gpu && createGLTexture) {
        this.weights[p].createGLTexture()
      }
    })
  }

  /**
   * Layer computational logic
   * @param {Tensor} x
   * @returns {Tensor} x
   */
  call(x) {
    return x
  }

  /**
   * Toggle GPU mode on/off
   *
   * @param {Boolean} mode - on/off
   */
  toggleGpu(mode) {
    const newMode = typeof mode === 'undefined' ? !this.gpu : mode
    if (webgl2.isSupported && newMode) {
      this.gpu = true
    } else {
      this.gpu = false
    }
  }
}