text:
package com.gemstone.gemfire.management.internal.cli.parser.jopt;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import com.gemstone.gemfire.management.internal.cli.MultipleValueConverter;
import com.gemstone.gemfire.management.internal.cli.exceptions.CliCommandOptionException;
import com.gemstone.gemfire.management.internal.cli.exceptions.ExceptionGenerator;
import com.gemstone.gemfire.management.internal.cli.parser.Argument;
import com.gemstone.gemfire.management.internal.cli.parser.GfshOptionParser;
import com.gemstone.gemfire.management.internal.cli.parser.Option;
import com.gemstone.gemfire.management.internal.cli.parser.OptionSet;
import com.gemstone.gemfire.management.internal.cli.parser.SyntaxConstants;
import com.gemstone.gemfire.management.internal.cli.parser.preprocessor.Preprocessor;
import com.gemstone.gemfire.management.internal.cli.parser.preprocessor.PreprocessorUtils;
import com.gemstone.gemfire.management.internal.cli.parser.preprocessor.TrimmedInput;
import com.gemstone.gemfire.management.internal.cli.util.spring.StringUtils;
import joptsimple.ArgumentAcceptingOptionSpec;
import joptsimple.MultipleArgumentsForOptionException;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSpecBuilder;

/**
 * Implementation of {@link GfshOptionParser} which internally makes use of
 * {@link com.gemstone.joptsimple.OptionParser}
 *
 * @author Nikhil Jadhav
 * @since 7.0
 *
 */
public class JoptOptionParser implements GfshOptionParser {

  private OptionParser parser;
  private LinkedList<Argument> arguments = new LinkedList<Argument>();
  private LinkedList<Option> options;

  /**
   * Constructor
   */
  public JoptOptionParser() {
    parser = new OptionParser(true);
  }

  public void setArguments(LinkedList<Argument> arguments) {
    List<Argument> optional = new LinkedList<Argument>();
    // Let us arrange arguments as mandatory arguments
    // followed by optional arguments
    for (Argument argument : arguments) {
      if (argument.isRequired()) {
        this.arguments.add(argument);
      } else {
        optional.add(argument);
      }
    }
    for (Argument argument : optional) {
      this.arguments.add(argument);
    }
  }

  public void setOptions(LinkedList<Option> options) {
    this.options = options;
    for (Option option : options) {
      addJoptOptionObject(option);
    }
  }

  private void addJoptOptionObject(Option option) {
    OptionSpecBuilder optionBuilder = null;

    optionBuilder = parser.acceptsAll(option.getAggregate(),
        option.getHelp());

    /* Now set the the attributes related to the option */

    ArgumentAcceptingOptionSpec<String> argumentSpecs = null;

    if (option.isWithRequiredArgs()) {
      argumentSpecs = optionBuilder.withRequiredArg();
    } else {
      argumentSpecs = optionBuilder.withOptionalArg();
    }

    if (option.isRequired()) {
      argumentSpecs.required();
    }
    if (option.getValueSeparator() != null) {
      argumentSpecs.withValuesSeparatedBy(option.getValueSeparator());
    }
  }

  public OptionSet parse(String userInput) throws CliCommandOptionException {
    OptionSet optionSet = new OptionSet();
    optionSet.setUserInput(userInput!=null?userInput.trim():"");
    if (userInput != null) {
      TrimmedInput input = PreprocessorUtils.trim(userInput);
      String[] preProcessedInput = preProcess(input.getString());
      joptsimple.OptionSet joptOptionSet = null;
      CliCommandOptionException ce = null;
      // int factor = 0;
      try {
        joptOptionSet = parser.parse(preProcessedInput);
      } catch (Exception e) {
        if (e instanceof OptionException) {
          ce = processException(e);
          joptOptionSet = ((OptionException) e).getDetected();
        }
      }
      if (joptOptionSet != null) {

        // Make sure there are no miscellaneous, unknown strings that cannot be identified as
        // either options or arguments.
        if (joptOptionSet.nonOptionArguments().size() > arguments.size()) {
          String unknownString = joptOptionSet.nonOptionArguments().get(arguments.size());
          // If the first option is un-parseable then it will be returned as "<option>=<value>" since it's
          // been interpreted as an argument. However, all subsequent options will be returned as "<option>".
          // This hack splits off the string before the "=" sign if it's the first case.
          if (unknownString.matches("^-*\\w+=.*$")) {
            unknownString = unknownString.substring(0, unknownString.indexOf('='));
          }
          ce = processException(OptionException.createUnrecognizedOptionException(unknownString, joptOptionSet));
        }

        // First process the arguments
        StringBuffer argument = new StringBuffer();
        int j = 0;
        for (int i = 0; i < joptOptionSet.nonOptionArguments().size()
            && j < arguments.size(); i++) {
          argument = argument.append(joptOptionSet.nonOptionArguments().get(i));
          // Check for syntax of arguments before adding them to the
          // option set as we want to support quoted arguments and those
          // in brackets
          if (PreprocessorUtils.isSyntaxValid(argument.toString())) {
            optionSet.put(arguments.get(j), argument.toString());
            j++;
            argument.delete(0, argument.length());
          }
        }
        if(argument.length()>0){
          // Here we do not need to check for the syntax of the argument
          // because the argument list is now over and this is the last
          // argument which was not added due to improper syntax
          optionSet.put(arguments.get(j),argument.toString());
        }

        // Now process the options
        for (Option option : options) {
          List<String> synonyms = option.getAggregate();
          for (String string : synonyms) {
            if (joptOptionSet.has(string)) {
              // Check whether the user has actually entered the
              // full option or just the start
              boolean present = false;
              outer: for (String inputSplit : preProcessedInput) {
                if (inputSplit.startsWith(SyntaxConstants.LONG_OPTION_SPECIFIER)) {
                  // Remove option prefix
                  inputSplit = StringUtils.removePrefix(inputSplit,
                      SyntaxConstants.LONG_OPTION_SPECIFIER);
                  // Remove value specifier
                  inputSplit = StringUtils.removeSuffix(inputSplit,
                      SyntaxConstants.OPTION_VALUE_SPECIFIER);
                  if (!inputSplit.equals("")) {
                    if (option.getLongOption().equals(inputSplit)) {
                      present = true;
                      break outer;
                    } else {
                      for (String optionSynonym : option.getSynonyms()) {
                        if (optionSynonym.equals(inputSplit)) {
                          present = true;
                          break outer;
                        }
                      }
                    }
                  }
                }
              }
              if (present) {
                if (joptOptionSet.hasArgument(string)) {
                  List<?> arguments = joptOptionSet.valuesOf(string);
                  if (arguments.size() > 1 && !(option.getConverter() instanceof MultipleValueConverter) && option.getValueSeparator() == null) {
                    List<String> optionList = new ArrayList<String>(1);
                    optionList.add(string);
                    ce = processException(new MultipleArgumentsForOptionException(optionList, joptOptionSet));
                  } else if ((arguments.size() == 1 && !(option.getConverter() instanceof MultipleValueConverter)) || option.getValueSeparator() == null) {
                    optionSet.put(option, arguments.get(0).toString().trim());
                  } else {
                    StringBuffer value = new StringBuffer();
                    String valueSeparator = option.getValueSeparator();
                    for (Object object : joptOptionSet.valuesOf(string)) {
                      if (value.length() == 0) {
                        value.append((String) object);
                      } else {
                        if (valueSeparator != null) {
                          value.append(valueSeparator + ((String) object).trim());
                        } else {
                          value.append(((String) object).trim());
                        }
                      }
                    }
                    optionSet.put(option, value.toString());
                  }
                } else {
                  optionSet.put(option, option.getSpecifiedDefaultValue());
                }
                break;
              }
            }
          }
        }
      }

      // Convert the preProcessedInput into List<String>
      List<String> split = new ArrayList<String>();
      for (int i = 0; i < preProcessedInput.length; i++) {
        split.add(preProcessedInput[i]);
      }
      optionSet
          .setNoOfSpacesRemoved(input.getNoOfSpacesRemoved() /* + factor */);
      optionSet.setSplit(split);
      if (ce != null) {
        ce.setOptionSet(optionSet);
        throw ce;
      }
    }
    return optionSet;
  }

  private CliCommandOptionException processException(Exception e) {
    CliCommandOptionException ce = null;
    if (e instanceof OptionException) {
      ce = (CliCommandOptionException) ExceptionGenerator
          .generate((OptionException) e);
      if (ce != null) {
        if (ce instanceof CliCommandOptionException) {
          ((CliCommandOptionException) ce)
              .setOption(getOption((OptionException) e));
        }
      }
    }
    return ce;
  }

  private Option getOption(OptionException oe) {
    Option exceptionOption = null;
    Iterator<String> iterator = oe.options().iterator();
    outermost: for (Option option : options) {
      /* outer: */for (String string : option.getAggregate()) {
        /* inner: */while(iterator.hasNext()) {
          String joptOption = iterator.next();
          if (string.equals(joptOption)) {
            exceptionOption = option;
            break outermost;
          }
        }
      }
    }

    if (exceptionOption == null) {
      if (oe.options() != null) {
        if (oe.options().size() > 0) {
          exceptionOption = new Option(oe.options().iterator().next());
        }
      }
    }
    return exceptionOption;
  }

  private String[] preProcess(String userInput) {
    return Preprocessor.split(userInput);
  }

  public LinkedList<Argument> getArguments() {
    return arguments;
  }

  public LinkedList<Option> getOptions() {
    return options;
  }

}


text:
body {
    background-color: #202020;
    margin: 5px;
    font-family: 'Roboto', sans-serif;
}

.pointer {
    cursor: pointer
}

redpajama_set_name: RedPajamaGithub


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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Acn.Slp.IO;

namespace Acn.Slp.Packets
{
    public class ServiceDeregistrationPacket:SlpPacket
    {
        #region Setup and Initialisation

        public ServiceDeregistrationPacket():base(SlpFunctionId.ServiceDeRegister)
        {
        }

        #endregion

        #region Packet Contents

        public string ScopeList { get; set; }

        public string AttrList { get; set; }

        #endregion

        #region Read and Write

        protected override void ReadData(SlpBinaryReader data)
        {
            ScopeList = data.ReadNetworkString();
            AttrList = data.ReadNetworkString();
        }

        protected override void WriteData(SlpBinaryWriter data)
        {
            data.WriteNetworkString(ScopeList);
            data.WriteNetworkString(AttrList);
        }

        #endregion
    }
}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [TAKGAUtil defaultSetting];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {

}

- (void)applicationDidEnterBackground:(UIApplication *)application {

}

- (void)applicationWillEnterForeground:(UIApplication *)application {

}

- (void)applicationDidBecomeActive:(UIApplication *)application {

}

- (void)applicationWillTerminate:(UIApplication *)application {

}

@end


text:
<?php

namespace BP;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{

    /*
     * The init() method is called for every module implementing this feature, on every page request,
     * and should only be used for performing lightweight tasks such as registering event listeners.
     */

    /*
     * public function init(ModuleManager $moduleManager)
     * {
     * // Remember to keep the init() method as lightweight as possible
     * $events = $moduleManager->getEventManager();
     * $events->attach('loadModules.post', array($this, 'modulesLoaded'));
     * }
     */

    /*
     * The onBootstrap() method is called for every module implementing this feature, on every page request,
     * and should only be used for performing lightweight tasks such as registering event listeners.
     */
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    /**
     *
     * @return unknown
     */
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__
                )
            )
        );
    }
}


text:
package edu.berkeley.path.beats.simulator;

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

final public class DemandSet extends edu.berkeley.path.beats.jaxb.DemandSet {

	private Scenario myScenario;
	private Map<Long,DemandProfile> link_id_to_demandprofile;

	/////////////////////////////////////////////////////////////////////
	// populate / reset / validate / update
	/////////////////////////////////////////////////////////////////////

	protected void populate(Scenario myScenario) {

		this.myScenario = myScenario;

		if(getDemandProfile().isEmpty())
			return;

		// link to demand profile map
		link_id_to_demandprofile = new HashMap<Long,DemandProfile>();
		for(edu.berkeley.path.beats.jaxb.DemandProfile dp : getDemandProfile()){

			DemandProfile sdp = (DemandProfile) dp;

			link_id_to_demandprofile.put(new Long(dp.getLinkIdOrg()), sdp);

			// populate demand profile
			sdp.populate(myScenario);
		}
	}

	protected void reset() {
		for(edu.berkeley.path.beats.jaxb.DemandProfile dp : getDemandProfile())
			((DemandProfile) dp).reset();
	}

	protected void validate() {

		if(getDemandProfile()==null)
			return;

		if(getDemandProfile().isEmpty())
			return;

		for(edu.berkeley.path.beats.jaxb.DemandProfile dp : getDemandProfile())
			((DemandProfile)dp).validate();
	}

	protected void update() {
    	for(edu.berkeley.path.beats.jaxb.DemandProfile dp : getDemandProfile())
    		((DemandProfile) dp).update(false);
	}

	/////////////////////////////////////////////////////////////////////
	// public interface
	/////////////////////////////////////////////////////////////////////

//	public double[] getFutureTotalDemandInVeh_NoNoise(long link_id,double dt_in_seconds,int num_steps) throws BeatsException{
//
//		if(!BeatsMath.isintegermultipleof(dt_in_seconds,myScenario.getSimdtinseconds()))
//			throw new BeatsException("dt_in_seconds must be an integer multiple of simulation dt.");
//
//		// demand profile for this link
//		DemandProfile dp = link_id_to_demandprofile.get(link_id);
//
//		if(dp==null)
//			throw new BeatsException("requested demand for non-existent link.");
//
//		// simulation dt per output dt
//		int num_times_per_sample = BeatsMath.round(dt_in_seconds / myScenario.getSimdtinseconds());
//
//		// current simulation time step
//		int current_step = myScenario.getClock().getCurrentstep();
//
//		// return value
//		double [] X = new double [num_steps];
//
//		int n,k,step;
//		double nth_demand;
//		for(n=0;n<num_steps;n++){
//			nth_demand = 0d;
//            for(k=0;k<num_times_per_sample;k++){
//                if(dp.getSamplesteps()>0)
//                    step = BeatsMath.floor((current_step-dp.getStepinitial())/((float)dp.getSamplesteps()));
//                else
//                    step = 0;
//                step = Math.min(step,dp.getProfile_length()-1);
//                double x = dp.getTotalForStep(step);
//                x = dp.applyKnob(x);
//                nth_demand += x;
//                current_step++;
//            }
//			X[n] = nth_demand;
//		}
//
//		return X;
//	}

}


text:
"""
Session
-------

The database session module.
"""

from collections import defaultdict
import typing as t

import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.sql import ClauseElement, Executable, Select

from .model import DeclarativeModel

T = t.TypeVar("T")

class Session(orm.Session):
    """
    Manages persistence operations for ORM-mapped objects.

    See Also:
        For full SQLAlchemy documentation: https://docs.sqlalchemy.org/en/latest/orm/session.html
    """

    def all(
        self,
        statement: Executable,
        params: t.Optional[
            t.Union[t.Mapping[str, t.Any], t.Sequence[t.Mapping[str, t.Any]]]
        ] = None,
        execution_options: t.Optional[t.Mapping[str, t.Any]] = None,
        bind_arguments: t.Optional[t.Mapping[str, t.Any]] = None,
    ) -> t.List[t.Any]:
        """
        Return list of objects from execution of `statement`.

        If `statement` is a selectable that returns ORM models, then the model objects will be
        returned.

        If a joined-load is used that requires uniquification, then ``Result.unique()`` will
        automatically be called.

        Args:
            statement: An executable statement such as ``sqlalchemy.select``.
            params: Optional dictionary or list of dictionaries containing bound parameter values.
                If a single dictionary, single-row execution occurs; if a list of dictionaries, an
                "executemany" will be invoked. The keys in each dictionary must correspond to
                parameter names present in the statement.
            execution_options: Optional dictionary of execution options, which will be associated
                with the statement execution.  This dictionary can provide a subset of the options
                that are accepted by ``sqlalchemy._future.Connection.execution_options``, and may
                also provide additional options understood only in an ORM context.
            bind_arguments: Dictionary of additional arguments to determine the bind. May include
                "mapper", "bind", or other custom arguments. Contents of this dictionary are passed
                to the ``Session.get_bind`` method.
        """
        result = self.execute(
            statement, params, execution_options=execution_options, bind_arguments=bind_arguments
        )
        if isinstance(result, sa.engine.CursorResult):
            items = result.all()
        else:
            compile_state = result.raw.context.compiled.compile_state
            if compile_state and compile_state.multi_row_eager_loaders:
                result = result.unique()
            items = result.scalars().all()
        return items

    def first(
        self,
        statement: Executable,
        params: t.Optional[
            t.Union[t.Mapping[str, t.Any], t.Sequence[t.Mapping[str, t.Any]]]
        ] = None,
        execution_options: t.Optional[t.Mapping[str, t.Any]] = None,
        bind_arguments: t.Optional[t.Mapping[str, t.Any]] = None,
    ) -> t.Optional[t.Any]:
        """
        Return first result of `statement` or ``None`` if no results.

        If `statement` is a selectable that returns ORM models, then the model object will be
        returned.

        Args:
            statement: An executable statement such as ``sqlalchemy.select``.
            params: Optional dictionary or list of dictionaries containing bound parameter values.
                If a single dictionary, single-row execution occurs; if a list of dictionaries, an
                "executemany" will be invoked.  The keys in each dictionary must correspond to
                parameter names present in the statement.
            execution_options: Optional dictionary of execution options, which will be associated
                with the statement execution.  This dictionary can provide a subset of the options
                that are accepted by ``sqlalchemy._future.Connection.execution_options``, and may
                also provide additional options understood only in an ORM context.
            bind_arguments: Dictionary of additional arguments to determine the bind. May include
                "mapper", "bind", or other custom arguments. Contents of this dictionary are passed
                to the ``Session.get_bind`` method.
        """
        result = self.execute(
            statement, params, execution_options=execution_options, bind_arguments=bind_arguments
        )
        if isinstance(result, sa.engine.CursorResult):
            item = result.first()
        else:
            item = result.scalar()
        return item

    def one(
        self,
        statement: Executable,
        params: t.Optional[
            t.Union[t.Mapping[str, t.Any], t.Sequence[t.Mapping[str, t.Any]]]
        ] = None,
        execution_options: t.Optional[t.Mapping[str, t.Any]] = None,
        bind_arguments: t.Optional[t.Mapping[str, t.Any]] = None,
    ) -> t.Any:
        """
        Return exactly one result or raise an exception.

        If `statement` is a selectable that returns ORM models, then the model object will be
        returned.

        Args:
            statement: An executable statement such as ``sqlalchemy.select``.
            params: Optional dictionary or list of dictionaries containing bound parameter values.
                If a single dictionary, single-row execution occurs; if a list of dictionaries, an
                "executemany" will be invoked.  The keys in each dictionary must correspond to
                parameter names present in the statement.
            execution_options: Optional dictionary of execution options, which will be associated
                with the statement execution.  This dictionary can provide a subset of the options
                that are accepted by ``sqlalchemy._future.Connection.execution_options``, and may
                also provide additional options understood only in an ORM context.
            bind_arguments: Dictionary of additional arguments to determine the bind. May include
                "mapper", "bind", or other custom arguments. Contents of this dictionary are passed
                to the ``Session.get_bind`` method.
        """
        result = self.execute(
            statement, params, execution_options=execution_options, bind_arguments=bind_arguments
        )
        if isinstance(result, sa.engine.CursorResult):
            item = result.one()
        else:
            item = result.scalar_one()
        return item

    def one_or_none(
        self,
        statement: Executable,
        params: t.Optional[
            t.Union[t.Mapping[str, t.Any], t.Sequence[t.Mapping[str, t.Any]]]
        ] = None,
        execution_options: t.Optional[t.Mapping[str, t.Any]] = None,
        bind_arguments: t.Optional[t.Mapping[str, t.Any]] = None,
    ) -> t.Optional[t.Any]:
        """
        Return exactly one result or ``None`` if no results or raise if more than one result.

        If `statement` is a selectable that returns ORM models, then the model object will be
        returned.

        Args:
            statement: An executable statement such as ``sqlalchemy.select``.
            params: Optional dictionary or list of dictionaries containing bound parameter values.
                If a single dictionary, single-row execution occurs; if a list of dictionaries, an
                "executemany" will be invoked.  The keys in each dictionary must correspond to
                parameter names present in the statement.
            execution_options: Optional dictionary of execution options, which will be associated
                with the statement execution.  This dictionary can provide a subset of the options
                that are accepted by ``sqlalchemy._future.Connection.execution_options``, and may
                also provide additional options understood only in an ORM context.
            bind_arguments: Dictionary of additional arguments to determine the bind. May include
                "mapper", "bind", or other custom arguments. Contents of this dictionary are passed
                to the ``Session.get_bind`` method.
        """
        result = self.execute(
            statement, params, execution_options=execution_options, bind_arguments=bind_arguments
        )
        if isinstance(result, sa.engine.CursorResult):
            item = result.one_or_none()
        else:
            item = result.scalar_one_or_none()
        return item

    def save(self, model: T) -> T:
        """
        Save model in the database using insert, update, or upsert on primary key(s).

        See Also:
            See :meth:`.Session.save_all` for more details.

        Args:
            model: Models to save to database.

        Raises:
            - ``TypeError``: On validation errors.
            - ``sqlalchemy.exc.*``: On execution errors.
        """
        if not isinstance(model, DeclarativeModel):
            raise TypeError(f"save not supported for object of type {type(model)}")
        return self.save_all([model])[0]

    def save_all(self, models: t.Union[t.Iterable[t.Any], t.Any]) -> t.List[t.Any]:
        """
        Save `models` into the database using insert, update, or upsert on primary key(s).

        It's not required that each model be of the same model class. A mixture of model classes are
        allowed.

        The "upsert" will only occur for models that have their primary key(s) set. Upsert on keys
        other than primary keys is not supported. The "upsert" itself occurs at the
        application-layer only and does not take advantage of any database specific upsert support.
        Therefore, it is possible that there could be a race-condition that would result in an
        ``IntegrityError`` if a model's primary key is set, but not found in the database, but is
        then inserted into the database by another process before this method can insert it.

        If a corresponding model instance with the same primary key(s) as one of the models exists
        in the current sessions but not in the models list, then the model in the models list will
        be merged with the corresponding instance in the session state.

        If multiple instances of a model class in models have the same primary-key, an exception
        will be raised.

        Warning:
            Saving will result in 1 "SELECT" query for every unique model class in the list of
            models. The maximum returned result from each query would be the total not of entities
            of each model class in the list of models.

        Args:
            models: Models to save to database.

        Raises:
            - ``TypeError``: On validation errors.
            - ``sqlalchemy.exc.*``: On execution errors.
        """
        if isinstance(models, DeclarativeModel):
            models = [models]
        else:
            # Cast to list since we may end up modifying the list below, and we don't want to mutate
            # passed in arguments.
            models = list(models)

        if not models:
            raise TypeError("save_all requires at least one object")

        invalid_types = {type(model) for model in models if not isinstance(model, DeclarativeModel)}
        if invalid_types:
            raise TypeError(f"save_all not supported for objects of types {invalid_types}")

        for model_group, select_models_stmt in iter_mergeable_models_by_class(models):
            results = self.execute(select_models_stmt).scalars()
            existing_models_by_pk = {model_pk(model): model for model in results}

            for idx, pk, model in model_group:
                if model not in self and pk in existing_models_by_pk:
                    copy_model_pk(existing_models_by_pk[pk], model)
                    models[idx] = self.merge(model)

        self.add_all(models)

        return models

def iter_mergeable_models_by_class(
    models: t.Iterable[t.Any],
) -> t.Iterator[t.Tuple[t.List[t.Tuple[int, tuple, t.Any]], Select]]:
    # Model instances that have their primary key(s) set which may already exist in the
    # database. These models will either be inserted or updated, but some database querying will
    # be required to make that determination.
    mergeable: t.Dict[type, t.List[t.Tuple[int, tuple, t.Any]]] = defaultdict(list)

    # Use dictionary of primary-keys to keep track of unique primary key values between models
    # to enforce that all models given must correspond to unique records.
    primary_keys: t.Dict[type, set] = defaultdict(set)

    # Partition models into `insertable` or `mergeable` buckets.
    for idx, model in enumerate(models):
        pk = model_pk(model)

        if all(v is not None for v in pk):
            # Primary key set so add to the mergeable list.
            model_class = type(model)
            if pk in primary_keys[model_class]:
                raise TypeError(f"save_all duplicate primary-key set for {model_class}: {pk}")

            # Model's primary key is set so it might be mergeable. Keep track of original index
            # because we'll need to update the `models` list with the merged instance.
            mergeable[model_class].append((idx, model_pk(model), model))
            primary_keys[model_class].add(pk)

    for model_class, model_group in mergeable.items():
        criteria = pk_filter(*(model for *_, model in model_group))
        select_models_stmt = sa.select(model_class).where(criteria)
        yield model_group, select_models_stmt

def model_pk(model: t.Any) -> t.Tuple[t.Any, ...]:
    """Return tuple of primary-key values for given model instance."""
    mapper: orm.Mapper = sa.inspect(type(model))
    return mapper.primary_key_from_instance(model)

def pk_filter(*models) -> ClauseElement:
    """
    Return SQL filter expression over primary-key values of given models.

    The filter will have the form:

    ::

        (pk_col1 = models[0].pk_col1 ... AND pk_colN = models[0].pk_colN) OR
        (pk_col1 = models[1].pk_col1 ... AND pk_colN = models[1].pk_colN) ... OR
        (pk_col1 = models[M].pk_col1 ... AND pk_colN = models[M].pk_colN)
    """
    mappers: t.Dict[type, orm.Mapper] = {}
    all_pk_filters = []

    for model in models:
        model_class = type(model)
        mapper = mappers.get(model_class)
        if mapper is None:
            mapper = sa.inspect(model_class)
            mappers[model_class] = mapper

        pk_filters = zip(mapper.primary_key, mapper.primary_key_from_instance(model))
        all_pk_filters.append(sa.and_(*(col == val for col, val in pk_filters)))

    return sa.or_(*all_pk_filters)

def copy_model_pk(from_model: t.Any, to_model: t.Any) -> None:
    """Transfer primary key value from ``parent_model`` to ``child_model``."""
    mapper: orm.Mapper = sa.inspect(type(from_model))
    attrs_by_col_name = {
        col_attr.expression.name: attr for attr, col_attr in mapper.column_attrs.items()
    }
    pk_pairs = zip(mapper.primary_key, mapper.primary_key_from_instance(from_model))
    for col, val in pk_pairs:
        attr = attrs_by_col_name[col.name]
        setattr(to_model, attr, val)


text:
class CoordinatorsController < ApplicationController
end


text:
package org.semanticweb.elk.owl.filters;

import org.semanticweb.elk.owl.interfaces.ElkPropertyRestrictionQualified;

/**
 * A filter producing objects in {@link ElkPropertyRestrictionQualified} from
 * objects of this type.
 *
 * @author "Yevgeny Kazakov"
 *
 */
public interface ElkPropertyRestrictionQualifiedFilter extends
		ElkCardinalityRestrictionQualifiedFilter, ElkDataHasValueFilter,
		ElkObjectAllValuesFromFilter, ElkObjectHasValueFilter,
		ElkObjectSomeValuesFromFilter {

	// combined visitor

}


text:
package com.runetooncraft.warpigeon.engine.graphics;

import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import com.runetooncraft.warpigeon.engine.WPEngine5;
import com.runetooncraft.warpigeon.engine.utils3d.*;

public class ScreenEngine3D {

	private WPEngine5 engine;
	private final Bitmap frameBuffer;
	private final BufferStrategy bufferStrategy;
	private final Graphics graphics;
//	private double renderDistance = 7000;

	public ScreenEngine3D(int width, int height, WPEngine5 engine) {
		this.engine = engine;
		frameBuffer = new Bitmap(width, height);
		frameBuffer.clear((byte)0x60);
		engine.createBufferStrategy(1);
		bufferStrategy = engine.getBufferStrategy();
		graphics = bufferStrategy.getDrawGraphics();
	}

	public  void SwapBuffers() {
		frameBuffer.copyTobyteArray(engine.getPixels());
		graphics.drawImage(engine.getView(), 0, 0, frameBuffer.getWidth(), frameBuffer.getHeight(), null);
		bufferStrategy.show();
	}

	public Bitmap getFrameBuffer() {
		return frameBuffer;
	}
}


text:
.. Copyright 2015 tsuru authors. All rights reserved.
   Use of this source code is governed by a BSD-style
   license that can be found in the LICENSE file.

++++++++++++++++++++++++++++++++++++++
Deploying PHP applications in tsuru
++++++++++++++++++++++++++++++++++++++

Overview
========

This document is a hands-on guide to deploying a simple PHP application in
tsuru. The example application will be a very simple Wordpress project
associated to a MySQL service. It's applicable to any php over apache
application.

Creating the app in tsuru
=========================

To create an app, you use the command `app-create`:

.. highlight:: bash

::

    $ tsuru app-create <app-name> <app-platform>

For PHP, the app platform is, guess what, ``php``! Let's be over creative
and develop a never-developed tutorial-app: a blog, and its name will also be
very creative, let's call it "blog":

.. highlight:: bash

::

    $ tsuru app-create blog php

To list all available platforms, use the command `platform-list`.

You can see all your applications using the command `app-list`:

.. highlight:: bash

::

    $ tsuru app-list
    +-------------+-------------------------+--------------------------+
    | Application | Units State Summary     | Address                  |
    +-------------+-------------------------+--------------------------+
    | blog        | 0 of 0 units in-service | blog.192.168.50.4.nip.io |
    +-------------+-------------------------+--------------------------+

Application code
================

This document will not focus on how to write a php blog, you can download the
entire source direct from wordpress: http://wordpress.org/latest.zip. Here is
all you need to do with your project:

.. highlight:: bash

::

    # Download and unpack wordpress
    $ wget http://wordpress.org/latest.zip
    $ unzip latest.zip
    # Preparing wordpress for tsuru
    $ cd wordpress
    # Notify tsuru about the necessary packages
    $ echo php5-mysql > requirements.apt
    # Preparing the application to receive the tsuru environment related to the mysql service
    $ sed "s/'database_name_here'/getenv('MYSQL_DATABASE_NAME')/; \
                s/'username_here'/getenv('MYSQL_USER')/; \
                s/'localhost'/getenv('MYSQL_HOST')/; \
                s/'password_here'/getenv('MYSQL_PASSWORD')/" \
                wp-config-sample.php  > wp-config.php
    # Creating a local Git repository
    $ git init
    $ git add .
    $ git commit -m 'initial project version'

Git deployment
==============

When you create a new app, tsuru will display the Git remote that you should
use. You can always get it using the command `app-info`:

.. highlight:: bash

::

    $ tsuru app-info --app blog
    Application: blog
    Repository: git@192.168.50.4.nip.io:blog.git
    Platform: php
    Teams: admin
    Address: blog.192.168.50.4.nip.io
    Owner: admin@example.com
    Team owner: admin
    Deploys: 0
    Pool: theonepool

    App Plan:
    +---------------+--------+------+-----------+--------+---------+
    | Name          | Memory | Swap | Cpu Share | Router | Default |
    +---------------+--------+------+-----------+--------+---------+
    | autogenerated | 0 MB   | 0 MB | 100       |        | false   |
    +---------------+--------+------+-----------+--------+---------+

The Git remote will be used to deploy your application using Git. You can just
push to tsuru remote and your project will be deployed:

.. highlight:: bash

::

    $ git push git@192.168.50.4.nip.io:blog.git master
    Counting objects: 1295, done.
    Delta compression using up to 4 threads.
    Compressing objects: 100% (1271/1271), done.
    Writing objects: 100% (1295/1295), 6.09 MiB | 5.65 MiB/s, done.
    Total 1295 (delta 102), reused 0 (delta 0)
    remote: text
    remote: Deploying the PHP application...
    remote: tar: Removing leading `/' from member names
    #########################################
    #  OMIT DEPENDENCIES STEPS (see below)  #
    #########################################
    remote:
    remote: ---- Building application image ----
    remote:  ---> Sending image to repository (51.40MB)
    remote:  ---> Cleaning up
    remote:
    remote: ---- Starting 1 new unit ----
    remote:  ---> Started unit 027c2a31a0...
    remote:
    remote: ---- Binding and checking 1 new units ----
    remote:  ---> Bound and checked unit 027c2a31a0
    remote:
    remote: ---- Adding routes to 1 new units ----
    remote:  ---> Added route to unit 027c2a31a0
    remote:
    remote: OK
    To git@192.168.50.4.nip.io:blog.git
     * [new branch]      master -> master

If you get a "Permission denied (publickey).", make sure you're member of a
team and have a public key added to tsuru. To add a key, use the command
`key-add`:

.. highlight:: bash

::

    $ tsuru key-add mykey ~/.ssh/id_dsa.pub

You can use ``git remote add`` to avoid typing the entire remote url every time
you want to push:

.. highlight:: bash

::

    $ git remote add tsuru git@192.168.50.4.nip.io:blog.git

Then you can run:

.. highlight:: bash

::

    $ git push tsuru master
    Everything up-to-date

And you will be also able to omit the ``--app`` flag from now on:

.. highlight:: bash

::

    $ tsuru app-info
    Application: blog
    Repository: git@192.168.50.4.nip.io:blog.git
    Platform: php
    Teams: admin
    Address: blog.192.168.50.4.nip.io
    Owner: admin@example.com
    Team owner: admin
    Deploys: 1
    Pool: theonepool
    Units: 1
    +------------+---------+
    | Unit       | State   |
    +------------+---------+
    | 027c2a31a0 | started |
    +------------+---------+

    App Plan:
    +---------------+--------+------+-----------+--------+---------+
    | Name          | Memory | Swap | Cpu Share | Router | Default |
    +---------------+--------+------+-----------+--------+---------+
    | autogenerated | 0 MB   | 0 MB | 100       |        | false   |
    +---------------+--------+------+-----------+--------+---------+

Listing dependencies
====================

In the last section we omitted the dependencies step of deploy. In tsuru, an
application can have two kinds of dependencies:

* **Operating system dependencies**, represented by packages in the package manager
  of the underlying operating system (e.g.: ``yum`` and ``apt-get``);
* **Platform dependencies**, represented by packages in the package manager of the
  platform/language (e.g. in Python, ``pip``).

All ``apt-get`` dependencies must be specified in a ``requirements.apt`` file,
located in the root of your application, and pip dependencies must be located
in a file called ``requirements.txt``, also in the root of the application.
Since we will use MySQL with PHP, we need to install the package depends on just
one ``apt-get`` package:
``php5-mysql``, so here is how ``requirements.apt``
looks like:

::

    php5-mysql

You can see the complete output of installing these dependencies below:

.. highlight:: bash

::

    % git push tsuru master
    #####################################
    #                OMIT               #
    #####################################
    Counting objects: 1155, done.
    Delta compression using up to 4 threads.
    Compressing objects: 100% (1124/1124), done.
    Writing objects: 100% (1155/1155), 4.01 MiB | 327 KiB/s, done.
    Total 1155 (delta 65), reused 0 (delta 0)
    remote: Cloning into '/home/application/current'...
    remote: Reading package lists...
    remote: Building dependency tree...
    remote: Reading state information...
    remote: The following extra packages will be installed:
    remote:   libmysqlclient18 mysql-common
    remote: The following NEW packages will be installed:
    remote:   libmysqlclient18 mysql-common php5-mysql
    remote: 0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
    remote: Need to get 1042 kB of archives.
    remote: After this operation, 3928 kB of additional disk space will be used.
    remote: Get:1 http://archive.ubuntu.com/ubuntu/ quantal/main mysql-common all 5.5.27-0ubuntu2 [13.7 kB]
    remote: Get:2 http://archive.ubuntu.com/ubuntu/ quantal/main libmysqlclient18 amd64 5.5.27-0ubuntu2 [949 kB]
    remote: Get:3 http://archive.ubuntu.com/ubuntu/ quantal/main php5-mysql amd64 5.4.6-1ubuntu1 [79.0 kB]
    remote: Fetched 1042 kB in 1s (739 kB/s)
    remote: Selecting previously unselected package mysql-common.
    remote: (Reading database ... 23874 files and directories currently installed.)
    remote: Unpacking mysql-common (from .../mysql-common_5.5.27-0ubuntu2_all.deb) ...
    remote: Selecting previously unselected package libmysqlclient18:amd64.
    remote: Unpacking libmysqlclient18:amd64 (from .../libmysqlclient18_5.5.27-0ubuntu2_amd64.deb) ...
    remote: Selecting previously unselected package php5-mysql.
    remote: Unpacking php5-mysql (from .../php5-mysql_5.4.6-1ubuntu1_amd64.deb) ...
    remote: Processing triggers for libapache2-mod-php5 ...
    remote:  * Reloading web server config
    remote:    ...done.
    remote: Setting up mysql-common (5.5.27-0ubuntu2) ...
    remote: Setting up libmysqlclient18:amd64 (5.5.27-0ubuntu2) ...
    remote: Setting up php5-mysql (5.4.6-1ubuntu1) ...
    remote: Processing triggers for libc-bin ...
    remote: ldconfig deferred processing now taking place
    remote: Processing triggers for libapache2-mod-php5 ...
    remote:  * Reloading web server config
    remote:    ...done.
    remote: sudo: unable to resolve host 8cf20f4da877
    remote: sudo: unable to resolve host 8cf20f4da877
    remote: debconf: unable to initialize frontend: Dialog
    remote: debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
    remote: debconf: falling back to frontend: Readline
    remote: debconf: unable to initialize frontend: Dialog
    remote: debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
    remote: debconf: falling back to frontend: Readline
    remote:
    remote: Creating config file /etc/php5/mods-available/mysql.ini with new version
    remote: debconf: unable to initialize frontend: Dialog
    remote: debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
    remote: debconf: falling back to frontend: Readline
    remote:
    remote: Creating config file /etc/php5/mods-available/mysqli.ini with new version
    remote: debconf: unable to initialize frontend: Dialog
    remote: debconf: (Dialog frontend will not work on a dumb terminal, an emacs shell buffer, or without a controlling terminal.)
    remote: debconf: falling back to frontend: Readline
    remote:
    remote: Creating config file /etc/php5/mods-available/pdo_mysql.ini with new version
    remote:
    remote:  ---> App will be restarted, please check its log for more details...
    remote:
    To git@192.168.50.4.nip.io:blog.git
     * [new branch]      master -> master

Running the application
=======================

As you can see, in the deploy output there is a step described as "App will be
restarted". In this step, tsuru will restart your app if it's running, or start
it if it's not.
Now that the app is deployed, you can access it from your browser, getting the
IP or host listed in ``app-list`` and opening it. For example,
in the list below:

::

    $ tsuru app-list
    +-------------+-------------------------+---------------------+
    | Application | Units State Summary     | Address             |
    +-------------+-------------------------+---------------------+
    | blog        | 1 of 1 units in-service | blog.cloud.tsuru.io |
    +-------------+-------------------------+---------------------+

Using services
==============

Now that php is running, we can accesss the application in the browser,
but we get a database connection error: `"Error establishing a database connection"`.
This error means that we can't connect to MySQL. That's because we
should not connect to MySQL on localhost, we must use a service.
The service workflow can be resumed to two steps:

#. Create a service instance
#. Bind the service instance to the app

But how can I see what services are available? Easy! Use the command
`service-list`:

.. highlight:: bash

::

    $ tsuru service-list
    +----------------+-----------+
    | Services       | Instances |
    +----------------+-----------+
    | elastic-search |           |
    | mysql          |           |
    +----------------+-----------+

The output from ``service-list`` above says that there are two available
services: "elastic-search" and "mysql", and no instances. To create our MySQL
instance, we need to run the command `service-add`:

.. highlight:: bash

::

    $ tsuru service-add mysql blogsql
    Service successfully added.

Now, if we run ``service-list`` again, we will see our new service instance in
the list:

.. highlight:: bash

::

    $ tsuru service-list
    +----------------+-----------+
    | Services       | Instances |
    +----------------+-----------+
    | elastic-search |           |
    | mysql          | blogsql   |
    +----------------+-----------+

To bind the service instance to the application, we use the command
`service-bind`:

.. highlight:: bash

::

    $ tsuru service-bind mysql blogsql
    Instance blogsql is now bound to the app blog.

    The following environment variables are now available for use in your app:

    - MYSQL_PORT
    - MYSQL_PASSWORD
    - MYSQL_USER
    - MYSQL_HOST
    - MYSQL_DATABASE_NAME

    For more details, please check the documentation for the service, using service-doc command.

As you can see from bind output, we use environment variables to connect to the
MySQL server. Next step would be update the ``wp-config.php`` to use these variables to
connect in the database:

.. highlight:: bash

::

    $ grep getenv wp-config.php
    define('DB_NAME', getenv('MYSQL_DATABASE_NAME'));
    define('DB_USER', getenv('MYSQL_USER'));
    define('DB_PASSWORD', getenv('MYSQL_PASSWORD'));
    define('DB_HOST', getenv('MYSQL_HOST'));

You can extend your wordpress installing plugins into your repository. In the example below, we
are adding the Amazon S3 capability to wordpress, just installing 2 more plugins: `Amazon S3 and Cloudfront <http://wordpress.org/plugins/amazon-s3-and-cloudfront>`_ +
`Amazon Web Services <http://wordpress.org/plugins/amazon-web-services>`_. It's the right way to store content files into tsuru.

.. highlight:: bash

::

    $ cd wp-content/plugins/
    $ wget http://downloads.wordpress.org/plugin/amazon-web-services.0.1.zip
    $ wget http://downloads.wordpress.org/plugin/amazon-s3-and-cloudfront.0.6.1.zip
    $ unzip amazon-web-services.0.1.zip
    $ unzip amazon-s3-and-cloudfront.0.6.1.zip
    $ rm -f amazon-web-services.0.1.zip amazon-s3-and-cloudfront.0.6.1.zip
    $ git add amazon-web-services/ amazon-s3-and-cloudfront/

Now you need to add the amazon AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environments
support into wp-config.php. You could add these environments right after the WP_DEBUG as below:

.. highlight:: bash

::

    $ grep -A2 define.*WP_DEBUG  wp-config.php
    define('WP_DEBUG', false);
    define('AWS_ACCESS_KEY_ID', getenv('AWS_ACCESS_KEY_ID'));
    define('AWS_SECRET_ACCESS_KEY', getenv('AWS_SECRET_ACCESS_KEY'));
    $ git add wp-config.php
    $ git commit -m 'adding plugins for S3'
    $ git push tsuru master

Now, just inject the right values for these environments with tsuru env-set as below:

.. highlight:: bash

::

    $ tsuru env-set AWS_ACCESS_KEY_ID="xxx" AWS_SECRET_ACCESS_KEY="xxxxx" -a blog

It's done! Now we have a PHP project deployed on tsuru, with S3 support using a MySQL
service.

Customizing the platform
========================

The PHP platform supports customizations in the frontend and the interpreter,
for more details, check the `README of the platform
<https://github.com/tsuru/basebuilder/blob/master/php/README.md>`_.

Going further
=============

For more information, you can dig into `tsuru docs <http://docs.tsuru.io>`_, or
read `complete instructions of use for the tsuru command
<https://tsuru.readthedocs.org>`_.


text:
import com.yimei.HelloService;
import com.yimei.UserService;
import com.yimei.ext.hessian.KittHessianProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.caucho.HessianProxyFactoryBean;

@Configuration
public class TestConfig {

    @Bean
    public HessianProxyFactoryBean helloClient() {
        HessianProxyFactoryBean factory = new KittHessianProxyFactoryBean();
        factory.setServiceUrl("http://localhost:8080/HelloService");
        factory.setServiceInterface(HelloService.class);
        return factory;
    }

    @Bean
    public HessianProxyFactoryBean helloClient1() {
        HessianProxyFactoryBean factory = new KittHessianProxyFactoryBean();
        factory.setServiceUrl("http://localhost:8080/UserService");
        factory.setServiceInterface(UserService.class);
        return factory;
    }
}


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

namespace CodeFighter.Data
{
    public class ShipHullPartCountData
    {
        [Key]
        public int Id { get; set; }
        public int ShipHullDataId { get; set; }
        public ShipHullData ShipHullData { get; set; }
        public int PartCountDataId { get; set; }
        public PartCountData PartCountData { get; set; }
    }
}


text:
package com.cidic.design.model;

public class ProductUserModel {

	private int pId;
	private String title;
	private String thumb;
	private String realname;
	private String mobile;
	private String address;
	private int groupId;

	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getThumb() {
		return thumb;
	}
	public void setThumb(String thumb) {
		this.thumb = thumb;
	}
	public String getRealname() {
		return realname;
	}
	public void setRealname(String realname) {
		this.realname = realname;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getGroupId() {
		return groupId;
	}
	public void setGroupId(int groupId) {
		this.groupId = groupId;
	}
	public int getpId() {
		return pId;
	}
	public void setpId(int pId) {
		this.pId = pId;
	}

}


text:
'use strict';

module.exports = Module._createSub('teamSupport');
module.exports.prototype.init = (function() {
    var setOptions = (function() {
        var params = {
            el: null,
            data: {}
        };
        return function(options) {
            options = $.extend({}, params, options);
            return options;
        };
    }());

    var setSelectors = function($box) {
        return {
            $selector: $box,
            $container: $box.find('.container')
        };
    };

    require('./_teamSupport.scss');
    var template = require('./_teamSupport.ejs');

    return function(options) {
        options = setOptions(options);
        this.selector = setSelectors($(template(options.data)));
        var that = this;
        this.selector.$selector.appendTo(options.el);
        return this;
    };
}());


text:
/**
 * \file ccl_xml.h
 * \brief Header for CCL + XML stuff
 */
#ifndef YAZ_CCL_XML_H
#define YAZ_CCL_XML_H

#include <yaz/ccl.h>
#include <yaz/xmltypes.h>

YAZ_BEGIN_CDECL

#if YAZ_HAVE_XML2
/** \brief configures CCL bibset using XML configuration
    \param bibset CCL bibliographic profile
    \param ptr xml node pointer pointing to "cclmap" element
    \param addinfo has error message if configuration could not be parsed
    \retval 0 OK
    \retval -1 errors. Inspect addinfo for error message

    Configuration example:
\verbatim
<cclmap defaultattrset="bib-1">
   <qual name="term">
       <attr type="u" value="1016"/>
       <attr type="s" value="pw"/>
   </qual>
   <qual name="title">
       <attr type="u" value="4"/>
   </qual>
   <qual name="distributor">
       <attr attrset="gils" type="u" value="2000"/>
   </qual>
  <directive name="and" value="+"/>
</cclmap>
\endverbatim
*/
YAZ_EXPORT
int ccl_xml_config(CCL_bibset bibset, const xmlNode *ptr,
                   const char **addinfo);
#endif
YAZ_END_CDECL

#endif
/*
 * Local variables:
 * c-basic-offset: 4
 * c-file-style: "Stroustrup"
 * indent-tabs-mode: nil
 * End:
 * vim: shiftwidth=4 tabstop=8 expandtab
 */


text:
Camel Router with Kotlin Project
================================

To build this project use

    mvn install

To run this project

    mvn exec:java

For more help see the Apache Camel documentation

    http://camel.apache.org/


text:
import copy as _copy
from hidparser.enums import CollectionType, ReportFlags, EnumMask, ReportType
from hidparser.UsagePage import UsagePage, Usage, UsageType, UsageRange
from hidparser.Device import Device, Report, ReportGroup, Collection
from hidparser.helper import ValueRange

class DeviceBuilder:
    def __init__(self):
        self._state_stack = []

        # Global Items
        self.usage_page = None
        self.unit = None
        self.unit_exponent = 1

        self.report_id = 0
        self.report_size = 0
        self.report_count = 0
        self.logical_range = ValueRange()
        self.physical_range = self.logical_range

        # Local Items
        self._usages = []
        self._last_usage = None

        self.designators = range(0)
        self.strings = range(0)

        self._collection = Collection(allowed_usage_types=UsageType.COLLECTION_APPLICATION)
        self._current_collection = self._collection

    def add_report(self, report_type: ReportType, flags):
        usages = []
        if not flags & ReportFlags.CONSTANT or len(self._usages):
            if len(self._usages) is 0:
                usages = [self._last_usage]*self.report_count
            else:
                while len(usages) < self.report_count:
                    usage = self._usages.pop(0)
                    self._last_usage = usage
                    usages.extend(usage.get_range() if isinstance(usage, UsageRange) else [usage])

        designators = range(0)
        if len(self.designators) > 0:
            designator_diff =  len(self.designators) - self.report_count
            assert designator_diff >= 0, "Too few designators for report"
            designators = self.designators[0:-designator_diff]
            self.designators = self.designators[designator_diff + 1:]

        strings = range(0)
        if len(self.strings) > 0:
            strings_diff = len(self.strings) - self.report_count
            assert strings_diff >= 0, "Too few strings for report"
            strings = self.strings[0:-strings_diff]
            self.strings = self.strings[strings_diff + 1:]

        self._current_collection.append(Report(
            report_id=self.report_id,
            report_type=report_type,
            usages=usages,
            designators=designators,
            strings=strings,
            size=self.report_size,
            count=self.report_count,
            logical_range=_copy.copy(self.logical_range),
            physical_range=_copy.copy(self.physical_range),
            unit=self.unit,
            exponent=self.unit_exponent,
            flags=flags
        ))

    def set_report_id(self, report_id: int):
        self.report_id = report_id

    def set_designator_range(self, minimum=None, maximum=None):
        if minimum is None:
            minimum = self.designators.start
        if maximum is None:
            maximum = self.designators.stop - 1 # Subtract one, so the output range generator is inclusive from start to stop
        self.designators = range(minimum, maximum + 1)

    def set_string_range(self, minimum=None, maximum=None):
        if minimum is None:
            minimum = self.strings.start
        if maximum is None:
            maximum = self.strings.stop - 1  # Subtract one, so the output range generator is inclusive from start to stop
        self.strings = range(minimum, maximum + 1)

    def set_usage_range(self, minimum=None, maximum=None):
        usage = self._usages[len(self._usages)-1] if len(self._usages) else None
        if usage is None or not isinstance(usage, UsageRange):
            usage = UsageRange(self.usage_page)
            self._usages.append(usage)

        if minimum is not None:
            usage.minimum = minimum
        if maximum is not None:
            usage.maximum = maximum

    def set_logical_range(self, minimum = None, maximum = None):
        if minimum is not None:
            self.logical_range.minimum = minimum

        if maximum is not None:
            self.logical_range.maximum = maximum

    def set_physical_range(self, minimum=None, maximum=None):
        if minimum is not None:
            self.physical_range.minimum = minimum

        if maximum is not None:
            self.physical_range.maximum = maximum

    def add_usage(self, usage):
        if isinstance(usage, Usage):
            self._usages.append(usage)
        elif isinstance(usage, UsagePage):
            self._usages.append(usage.value)
        else:
            usage_page = self.usage_page if (usage & ~0xFFFF) == 0 else UsagePage.find_usage_page((usage & ~0xFFFF) >> 16)
            if usage_page is None:
                raise ValueError("Invalid usage page")
            self._usages.append(usage_page.get_usage(usage & 0xFFFF))

    def set_usage_page(self, usage_page: UsagePage.__class__):
        self.usage_page = usage_page
        self._usages.clear()

    def push_collection(self, collection: CollectionType):
        try:
            usage = self._usages.pop(0)
        except IndexError:
            usage = None
        collection_element = Collection(
            usage=usage,
            parent=self._current_collection,
            collection_type=collection
        )
        self._current_collection.append(collection_element)
        self._current_collection = collection_element

        self._usages.clear()
        return self

    def pop_collection(self):
        if self._current_collection.parent is None:
            raise RuntimeError("Can not pop collection state")
        self._current_collection = self._current_collection.parent

        self._usages.clear()
        return self

    def push(self):
        """
        Pushes the state of all the global items onto the stack
        """
        global_items = (
            "usage_page", "unit","unit_exponent", "report_id",
            "report_size", "report_count", "logical_range", "physical_range"
        )
        state = _copy.deepcopy({k:v for k,v in self.__dict__.items() if k in global_items})
        self._state_stack.append(state)
        return self

    def pop(self):
        """
        Pops and restores the global item states from the stack
        """
        if len(self._state_stack) > 0:
            state = self._state_stack.pop()
            self.__dict__.update(state)
        return self

    def build(self):
        return Device(self._collection.items)


text:
/** \file SMTPlib.c
 *  \brief SMTP wrapper for FreeRTOS
 *
 * \addtogroup net
 * @{
*/

/**
\defgroup SMTPlib SMTPlib stack
@{

The SMTP commands allows to set the parameters for the SMTP connection, and to send emails from the Flyport.

*/

/* **************************************************************************
 *                                OpenPicus                 www.openpicus.com
 *                                                            italian concept
 *
 *            openSource wireless Platform for sensors and Internet of Things
 * **************************************************************************
 *  FileName:        SMTPlib.c
 *  Dependencies:    Microchip configs files
 *  Module:          FlyPort WI-FI
 *  Compiler:        Microchip C30 v3.12 or higher
 *
 *  Author               Rev.    Date              Comment
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  Gabriele Allegria    1.0     1/20/2011		   First release  (core team)
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *
 *  Software License Agreement
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 *  This is free software; you can redistribute it and/or modify it under
 *  the terms of the GNU General Public License (version 2) as published by
 *  the Free Software Foundation AND MODIFIED BY OpenPicus team.
 *
 *  ***NOTE*** The exception to the GPL is included to allow you to distribute
 *  a combined work that includes OpenPicus code without being obliged to
 *  provide the source code for proprietary components outside of the OpenPicus
 *  code.
 *  OpenPicus software is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 *  more details.
 *
 *
 * Warranty
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
 * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
 * LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * WE ARE LIABLE FOR ANY INCIDENTAL, SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF
 * PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR SERVICES, ANY CLAIMS
 * BY THIRD PARTIES (INCLUDING BUT NOT LIMITED TO ANY DEFENSE
 * THEREOF), ANY CLAIMS FOR INDEMNITY OR CONTRIBUTION, OR OTHER
 * SIMILAR COSTS, WHETHER ASSERTED ON THE BASIS OF CONTRACT, TORT
 * (INCLUDING NEGLIGENCE), BREACH OF WARRANTY, OR OTHERWISE.
 *
 **************************************************************************/

#include "SMTPlib.h"

static int ToSend = 0;

#if defined(STACK_USE_SMTP_CLIENT)
 /// @cond debug
//****************************************************************************
//	Generic function to accomplish: start, send, busy and stop (to save space)
//****************************************************************************
BOOL GenericSMTP(int fSMTP)
{
	BOOL opok = FALSE;
	while (!opok)
	{
		while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE
		if (xFrontEndStat == 0)
		{
			ToSend = fSMTP;
			xFrontEndStatRet = 2;

			xQueueSendToBack(xQueue,&ToSend,0);					//	Send TCPIsConnected command to the stack
			xFrontEndStat = 1;
			xSemaphoreGive(xSemFrontEnd);						//	xSemFrontEnd GIVE
			opok = TRUE;
		}
		else
		{
			xSemaphoreGive(xSemFrontEnd);
			taskYIELD();
			//	If WiFi module if turned OFF, function doesn't do anything
			if (xFrontEndStat == -1)
				return FALSE;
		}
	}

	while (xFrontEndStat != 2);								//	Waits for stack answer
	while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE

	BOOL retBool;
	retBool = xBool;
	xFrontEndStat = 0;
	xSemaphoreGive(xSemFrontEnd);							//	xSemFrontEnd GIVE
	taskYIELD();
	return retBool;
}
 /// @endcond

/**
 * Initializes the SMTP module. If the client is already in use, the initialization will not be possible.
 * \param None
 * \return TRUE: the SMTP client was correctly initialized.
 * \return FALSE: the SMTP client wasn't initialized. Maybe it's already used
 */
 BOOL SMTPStart()
 {
	return GenericSMTP(26);
 }

 /// @cond debug
 int cSMTPStart()
 {
	xBool = SMTPBeginUsage();
	return 0;
 }
 /// @endcond

/**
 * Sets all the parameters for the SMTP remote server (server name, username, password and port).
 * \param servparam the parameter to set. Available list is the following:

SERVER_NAME: the name of the SMTP server.

SERVER_USER: the username for access to the server.</L1>

SERVER_PASS: the password associated to the username.</L1>

SERVER_PORT: the port of the SMTP server.</L1>

 * \param paramfield a string containing the associated value to the parameter (server name, username, password or SMTP port).

  For example: SMTPSetServer(SERVER_NAME , "smtp.serverxyz.com")
 * \return None.
 */
void SMTPSetServer(int servparam , char * paramfield)
{
	BOOL opok = FALSE;
	while (!opok)
	{
		while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE
		if (xFrontEndStat == 0)
		{
			ToSend = 27;
			xFrontEndStatRet = 2;
			xInt = servparam;
			xChar = paramfield;
			xQueueSendToBack(xQueue,&ToSend,0);					//	Send TCPIsConnected command to the stack
			xFrontEndStat = 1;
			xSemaphoreGive(xSemFrontEnd);						//	xSemFrontEnd GIVE
			opok = TRUE;
		}
		else
		{
			xSemaphoreGive(xSemFrontEnd);
			taskYIELD();
			//	If WiFi module if turned OFF, function doesn't do anything
			if (xFrontEndStat == -1)
				return;
		}
	}
	while (xFrontEndStat != 2);								//	Waits for stack answer
	while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE

	xFrontEndStat = 0;
	xSemaphoreGive(xSemFrontEnd);							//	xSemFrontEnd GIVE
	taskYIELD();
}

 /// @cond debug
int cSMTPSetServer()
{
	switch (xInt)
	{
	//	Setting server name
	case SERVER_NAME:
		SMTPClient.Server.szRAM = (BYTE *) xChar;
		break;

	//	Setting username
	case SERVER_USER:
		SMTPClient.Username.szRAM = (BYTE *) xChar;
		break;

	//	Setting password
	case SERVER_PASS:
		SMTPClient.Password.szRAM = (BYTE *) xChar;
		break;

	//	Port setting
	case SERVER_PORT:
		SMTPClient.ServerPort = (WORD)atol(xChar);
		break;
	}
	return 0;
}
 /// @endcond

/**
 * Sets all the parameters for the email message to send (the sender, the destination address, the cc and bcc addresses, email subject and body).
 * \param msgparam the parameter to set. Available list is the following:

MSG_TO: the destination address.

MSG_CC: the cc address.</L1>

MSG_BCC: the bcc address.</L1>

MSG_FROM: the sender of the email message.</L1>

MSG_SUBJECT: the object of the email message.</L1>

MSG_BODY: the body of the email message.</L1>

 * \param mparamfield a string containing the associated value to the parameter.

  For example: if we want to send a message to example@openpicus.com. SMTPSetMsg(MSG_TO , "example@openpicus.com")
 * \return None.
 */
void SMTPSetMsg(int msgparam , char * mparamfield)
{
	BOOL opok = FALSE;
	while (!opok)
	{
		while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE
		if (xFrontEndStat == 0)
		{
			ToSend = 28;
			xFrontEndStatRet = 2;
			xInt = msgparam;
			xChar = mparamfield;
			xQueueSendToBack(xQueue,&ToSend,0);					//	Send TCPIsConnected command to the stack
			xFrontEndStat = 1;
			xSemaphoreGive(xSemFrontEnd);						//	xSemFrontEnd GIVE
			opok = TRUE;
		}
		else
		{
			xSemaphoreGive(xSemFrontEnd);
			taskYIELD();
			//	If WiFi module if turned OFF, function doesn't do anything
			if (xFrontEndStat == -1)
				return;
		}
	}

	while (xFrontEndStat != 2);								//	Waits for stack answer
	while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE

	xFrontEndStat = 0;
	xSemaphoreGive(xSemFrontEnd);							//	xSemFrontEnd GIVE
	taskYIELD();
}

 /// @cond debug
int cSMTPSetMsg()
{
	switch (xInt)
	{
	//	Setting destination email address
	case MSG_TO:
		SMTPClient.To.szRAM = (BYTE *) xChar;
		break;

	//	Setting cc for the message
	case MSG_CC:
		SMTPClient.CC.szRAM = (BYTE *) xChar;
		break;

	//	Setting bcc for the message
	case MSG_BCC:
		SMTPClient.BCC.szRAM = (BYTE *) xChar;
		break;

	//	Setting sender of the message
	case MSG_FROM:
		SMTPClient.From.szRAM = (BYTE *) xChar;
		break;

	//	Setting subject of the message
	case MSG_SUBJECT:
		SMTPClient.Subject.szRAM = (BYTE *) xChar;
		break;

	//	Setting the body of the message
	case MSG_BODY:
		SMTPClient.Body.szRAM = (BYTE *) xChar;
		break;
	}
	return 0;
}
 /// @endcond

/**
 * Once all the connection and message settings are done, it's possible to send the desired email message with this command
 * \param None
 * \return TRUE: the message was correctly sent.
 * \return FALSE: there was an error. Maybe the SMTP client is still busy in sending another message, or it's not initialized.
 */
BOOL SMTPSend()
{
	return GenericSMTP(29);
}

 /// @cond debug
//****************************************************************************
//	Only internal use
//	SMTPSend callback function
//****************************************************************************
int cSMTPSend()
{
	SMTPSendMail();
	xBool = TRUE;
	return 0;
}
 /// @endcond

/**
 * Verifies if the SMTP client is busy perfoming some action. Until the client is busy is not possible to other SMTP commands.
 * \param None
 * \return TRUE: the client is busy.
 * \return FALSE: the client is not performing any action, and can be used by the firmware.
 */
BOOL SMTPBusy()
{
	return GenericSMTP(30);
}

 /// @cond debug
//****************************************************************************
//	Only internal use
//	SMTPBusy callback funtion
//****************************************************************************
int cSMTPBusy()
{
	xBool = SMTPIsBusy();
	return 0;
}
 /// @endcond

BOOL SMTPStop()
{
	return GenericSMTP(31);
}

 /// @cond debug
//****************************************************************************
//	Only internal use
//	SMTPStop callback function
//****************************************************************************
int cSMTPStop()
{
	if (SMTPEndUsage() == SMTP_SUCCESS)
		xBool = TRUE;
	else
		xBool = FALSE;
	return 0;
}
 /// @endcond

 /**
 * Closes the SMTP client and gives a report about email sending, reporting the SMTP server response code. To send another email SMTP must be restarted.
 * \param None
 * \return the server answer code received by Flyport.
 *
 */
WORD SMTPReport()
{
	BOOL opok = FALSE;
	while (!opok)
	{
		while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE
		if (xFrontEndStat == 0)
		{
			ToSend = 32;
			xFrontEndStatRet = 2;

			xQueueSendToBack(xQueue,&ToSend,0);					//	Send TCPIsConnected command to the stack
			xFrontEndStat = 1;
			xSemaphoreGive(xSemFrontEnd);						//	xSemFrontEnd GIVE
			opok = TRUE;
		}
		else
		{
			xSemaphoreGive(xSemFrontEnd);
			taskYIELD();
			//	If WiFi module if turned OFF, function doesn't do anything
			if (xFrontEndStat == -1)
				return FALSE;
		}
	}

	while (xFrontEndStat != 2);								//	Waits for stack answer
	while (xSemaphoreTake(xSemFrontEnd,0) != pdTRUE);		//	xSemFrontEnd TAKE

	WORD retWord;
	retWord = xWord;
	xFrontEndStat = 0;
	xSemaphoreGive(xSemFrontEnd);							//	xSemFrontEnd GIVE
	taskYIELD();
	return retWord;
}

 /// @cond debug
//****************************************************************************
//	Only internal use
//	SMTPReport callback function
//****************************************************************************
int cSMTPReport()
{
	xWord = SMTPEndUsage();
	return 0 ;
}
 /// @endcond
#endif


text:
vpath %.c ../../common
vpath %.h ../../common
TARGET = util_poolset
OBJS = util_poolset.o mocks.o util.o set.o out.o

out.o: CFLAGS += -DDEBUG -DSRCVERSION=\"utversion\"
util.o: CFLAGS += -DDEBUG
set.o: CFLAGS += -DDEBUG

LIBPMEM=y

USE_PMEMSPOIL=y

include ../Makefile.inc
LDFLAGS += $(call extract_funcs, mocks.c)
INCS += -I../../common


text:
package org.apache.hadoop.hbase.io.hfile;

import java.nio.ByteBuffer;
import junit.framework.TestCase;

public class TestCachedBlockQueue extends TestCase {

  public void testQueue() throws Exception {

    CachedBlock cb1 = new CachedBlock(1000, "cb1", 1);
    CachedBlock cb2 = new CachedBlock(1500, "cb2", 2);
    CachedBlock cb3 = new CachedBlock(1000, "cb3", 3);
    CachedBlock cb4 = new CachedBlock(1500, "cb4", 4);
    CachedBlock cb5 = new CachedBlock(1000, "cb5", 5);
    CachedBlock cb6 = new CachedBlock(1750, "cb6", 6);
    CachedBlock cb7 = new CachedBlock(1000, "cb7", 7);
    CachedBlock cb8 = new CachedBlock(1500, "cb8", 8);
    CachedBlock cb9 = new CachedBlock(1000, "cb9", 9);
    CachedBlock cb10 = new CachedBlock(1500, "cb10", 10);

    CachedBlockQueue queue = new CachedBlockQueue(10000,1000);

    queue.add(cb1);
    queue.add(cb2);
    queue.add(cb3);
    queue.add(cb4);
    queue.add(cb5);
    queue.add(cb6);
    queue.add(cb7);
    queue.add(cb8);
    queue.add(cb9);
    queue.add(cb10);

    // We expect cb1 through cb8 to be in the queue
    long expectedSize = cb1.heapSize() + cb2.heapSize() + cb3.heapSize() +
      cb4.heapSize() + cb5.heapSize() + cb6.heapSize() + cb7.heapSize() +
      cb8.heapSize();

    assertEquals(queue.heapSize(), expectedSize);

    org.apache.hadoop.hbase.io.hfile.CachedBlock [] blocks = queue.get();
    assertEquals(blocks[0].getName(), "cb1");
    assertEquals(blocks[1].getName(), "cb2");
    assertEquals(blocks[2].getName(), "cb3");
    assertEquals(blocks[3].getName(), "cb4");
    assertEquals(blocks[4].getName(), "cb5");
    assertEquals(blocks[5].getName(), "cb6");
    assertEquals(blocks[6].getName(), "cb7");
    assertEquals(blocks[7].getName(), "cb8");

  }

  public void testQueueSmallBlockEdgeCase() throws Exception {

    CachedBlock cb1 = new CachedBlock(1000, "cb1", 1);
    CachedBlock cb2 = new CachedBlock(1500, "cb2", 2);
    CachedBlock cb3 = new CachedBlock(1000, "cb3", 3);
    CachedBlock cb4 = new CachedBlock(1500, "cb4", 4);
    CachedBlock cb5 = new CachedBlock(1000, "cb5", 5);
    CachedBlock cb6 = new CachedBlock(1750, "cb6", 6);
    CachedBlock cb7 = new CachedBlock(1000, "cb7", 7);
    CachedBlock cb8 = new CachedBlock(1500, "cb8", 8);
    CachedBlock cb9 = new CachedBlock(1000, "cb9", 9);
    CachedBlock cb10 = new CachedBlock(1500, "cb10", 10);

    CachedBlockQueue queue = new CachedBlockQueue(10000,1000);

    queue.add(cb1);
    queue.add(cb2);
    queue.add(cb3);
    queue.add(cb4);
    queue.add(cb5);
    queue.add(cb6);
    queue.add(cb7);
    queue.add(cb8);
    queue.add(cb9);
    queue.add(cb10);

    CachedBlock cb0 = new CachedBlock(10 + CachedBlock.PER_BLOCK_OVERHEAD, "cb0", 0);
    queue.add(cb0);

    // This is older so we must include it, but it will not end up kicking
    // anything out because (heapSize - cb8.heapSize + cb0.heapSize < maxSize)
    // and we must always maintain heapSize >= maxSize once we achieve it.

    // We expect cb0 through cb8 to be in the queue
    long expectedSize = cb1.heapSize() + cb2.heapSize() + cb3.heapSize() +
      cb4.heapSize() + cb5.heapSize() + cb6.heapSize() + cb7.heapSize() +
      cb8.heapSize() + cb0.heapSize();

    assertEquals(queue.heapSize(), expectedSize);

    org.apache.hadoop.hbase.io.hfile.CachedBlock [] blocks = queue.get();
    assertEquals(blocks[0].getName(), "cb0");
    assertEquals(blocks[1].getName(), "cb1");
    assertEquals(blocks[2].getName(), "cb2");
    assertEquals(blocks[3].getName(), "cb3");
    assertEquals(blocks[4].getName(), "cb4");
    assertEquals(blocks[5].getName(), "cb5");
    assertEquals(blocks[6].getName(), "cb6");
    assertEquals(blocks[7].getName(), "cb7");
    assertEquals(blocks[8].getName(), "cb8");

  }

  private class CachedBlock extends org.apache.hadoop.hbase.io.hfile.CachedBlock
  {
    public CachedBlock(long heapSize, String name, long accessTime) {
      super(name,
          ByteBuffer.allocate((int)(heapSize - CachedBlock.PER_BLOCK_OVERHEAD)),
          accessTime,false);
    }
  }

}


text:
Ithemal

      Enter a code sequence below, and Ithemal will predict the throughput of that sequence (the number of cycles to execute it in the body of a loop, assuming that all data is in cache).

      Ithemal only operates on basic blocks, so you cannot include any sort of jump commands.
      Ithemal will also not generate predictions for sequences using exotic instructions that were not in the training set (e.g. instructions like aeskeygenassist stump Ithemal).

      Please check out our code at: https://github.com/psg-mit/Ithemal

    <form action="predict" method="post">
      <textarea autofocus="true" cols="80" rows="20" required="true" name="code" autocomplete="off" spellcheck="false" autocorrect="off" autocapitalize="off">
{% if code_text %}
{{ code_text }}
{% else %}
cmp    byte ptr [rsp+0x38], 0x01
sbb    rax, rax
and    eax, 0x00000640
add    rax, 0x00024d00
cmp    byte ptr [rsp+0xa0], 0x01
{% endif %}
</textarea>

      <select name="model">
        <option value="hsw">Haswell</option>
        <option value="skl">Skylake</option>
        <option value="ivb">Ivy Bridge</option>
      </select>
      <input type="submit" value="Predict!"/>
    </form>

    {% if code_html %}

Last Run: {{ last_model }}

    {{ code_html | safe }}

    {% if prediction %}
    Prediction: {{ prediction }} cycles per iteration
    {% else %}
    Could not generate a prediction:  {{ error | safe }}
    {% endif %}
    {% endif %}


text:
package org.apache.olingo.commons.core.edm;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmAction;
import org.apache.olingo.commons.api.edm.EdmAnnotations;
import org.apache.olingo.commons.api.edm.EdmComplexType;
import org.apache.olingo.commons.api.edm.EdmEntityContainer;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.commons.api.edm.EdmEnumType;
import org.apache.olingo.commons.api.edm.EdmFunction;
import org.apache.olingo.commons.api.edm.EdmSchema;
import org.apache.olingo.commons.api.edm.EdmTerm;
import org.apache.olingo.commons.api.edm.EdmTypeDefinition;
import org.apache.olingo.commons.api.edm.FullQualifiedName;

public abstract class AbstractEdm implements Edm {

  protected Map<String, EdmSchema> schemas;
  protected List<EdmSchema> schemaList;

  private final Map<FullQualifiedName, EdmEntityContainer> entityContainers =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmEntityContainer>());

  private final Map<FullQualifiedName, EdmEnumType> enumTypes =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmEnumType>());

  private final Map<FullQualifiedName, EdmTypeDefinition> typeDefinitions =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmTypeDefinition>());

  private final Map<FullQualifiedName, EdmEntityType> entityTypes =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmEntityType>());

  private final Map<FullQualifiedName, EdmComplexType> complexTypes =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmComplexType>());

  private final Map<FullQualifiedName, EdmAction> unboundActions =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmAction>());

  private final Map<FullQualifiedName, List<EdmFunction>> unboundFunctionsByName =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, List<EdmFunction>>());

  private final Map<FunctionMapKey, EdmFunction> unboundFunctionsByKey =
      Collections.synchronizedMap(new HashMap<FunctionMapKey, EdmFunction>());

  private final Map<ActionMapKey, EdmAction> boundActions =
      Collections.synchronizedMap(new HashMap<ActionMapKey, EdmAction>());

  private final Map<FunctionMapKey, EdmFunction> boundFunctions =
      Collections.synchronizedMap(new HashMap<FunctionMapKey, EdmFunction>());

  private final Map<FullQualifiedName, EdmTerm> terms =
      Collections.synchronizedMap(new HashMap<FullQualifiedName, EdmTerm>());

  private final Map<TargetQualifierMapKey, EdmAnnotations> annotationGroups =
      Collections.synchronizedMap(new HashMap<TargetQualifierMapKey, EdmAnnotations>());

  private Map<String, String> aliasToNamespaceInfo = null;

  @Override
  public List<EdmSchema> getSchemas() {
    if (schemaList == null) {
      initSchemas();
    }
    return schemaList;
  }

  @Override
  public EdmSchema getSchema(final String namespace) {
    if (schemas == null) {
      initSchemas();
    }

    EdmSchema schema = schemas.get(namespace);
    if (schema == null) {
      schema = schemas.get(aliasToNamespaceInfo.get(namespace));
    }
    return schema;
  }

  private void initSchemas() {
    loadAliasToNamespaceInfo();
    Map<String, EdmSchema> localSchemas = createSchemas();
    schemas = Collections.synchronizedMap(localSchemas);

    if (schemas == null) {
      schemas = Collections.emptyMap();
    }
    schemaList = Collections.unmodifiableList(new ArrayList<EdmSchema>(schemas.values()));
  }

  private void loadAliasToNamespaceInfo() {
    Map<String, String> localAliasToNamespaceInfo = createAliasToNamespaceInfo();
    aliasToNamespaceInfo = Collections.synchronizedMap(localAliasToNamespaceInfo);
  }

  @Override
  public EdmEntityContainer getEntityContainer() {
    return getEntityContainer(null);
  }

  @Override
  public EdmEntityContainer getEntityContainer(final FullQualifiedName namespaceOrAliasFQN) {
    final FullQualifiedName fqn = resolvePossibleAlias(namespaceOrAliasFQN);
    EdmEntityContainer container = entityContainers.get(fqn);
    if (container == null) {
      container = createEntityContainer(fqn);
      if (container != null) {
        entityContainers.put(fqn, container);
        if (fqn == null) {
          entityContainers.put(new FullQualifiedName(container.getNamespace(), container.getName()), container);
        }
      }
    }
    return container;
  }

  @Override
  public EdmEnumType getEnumType(final FullQualifiedName namespaceOrAliasFQN) {
    final FullQualifiedName fqn = resolvePossibleAlias(namespaceOrAliasFQN);
    EdmEnumType enumType = enumTypes.get(fqn);
    if (enumType == null) {
      enumType = createEnumType(fqn);
      if (enumType != null) {
        enumTypes.put(fqn, enumType);
      }
    }
    return enumType;
  }

  @Override
  public EdmTypeDefinition getTypeDefinition(final FullQualifiedName namespaceOrAliasFQN) {
    final FullQualifiedName fqn = resolvePossibleAlias(namespaceOrAliasFQN);
    EdmTypeDefinition typeDefinition = typeDefinitions.get(fqn);
    if (typeDefinition == null) {
      typeDefinition = createTypeDefinition(fqn);
      if (typeDefinition != null) {
        typeDefinitions.put(fqn, typeDefinition);
      }
    }
    return typeDefinition;
  }

  @Override
  public EdmEntityType getEntityType(final FullQualifiedName namespaceOrAliasFQN) {
    final FullQualifiedName fqn = resolvePossibleAlias(namespaceOrAliasFQN);
    EdmEntityType entityType = entityTypes.get(fqn);
    if (entityType == null) {
      entityType = createEntityType(fqn);
      if (entityType != null) {
        entityTypes.put(fqn, entityType);
      }
    }
    return entityType;
  }

  @Override
  public EdmComplexType getComplexType(final FullQualifiedName namespaceOrAliasFQN) {
    final FullQualifiedName fqn = resolvePossibleAlias(namespaceOrAliasFQN);
    EdmComplexType complexType = complexTypes.get(fqn);
    if (complexType == null) {
      complexType = createComplexType(fqn);
      if (complexType != null) {
        complexTypes.put(fqn, complexType);
      }
    }
    return complexType;
  }

  @Override
  public EdmAction getUnboundAction(final FullQualifiedName actionName) {
    final FullQualifiedName fqn = resolvePossibleAlias(actionName);
    EdmAction action = unboundActions.get(fqn);
    if (action == null) {
      action = createUnboundAction(fqn);
      if (action != null) {
        unboundActions.put(actionName, action);
      }
    }

    return action;
  }

  @Override
  public EdmAction getBoundAction(final FullQualifiedName actionName,
      final FullQualifiedName bindingParameterTypeName, final Boolean isBindingParameterCollection) {

    final FullQualifiedName actionFqn = resolvePossibleAlias(actionName);
    final FullQualifiedName bindingParameterTypeFqn = resolvePossibleAlias(bindingParameterTypeName);
    final ActionMapKey key = new ActionMapKey(actionFqn, bindingParameterTypeFqn, isBindingParameterCollection);
    EdmAction action = boundActions.get(key);
    if (action == null) {
      action = createBoundAction(actionFqn, bindingParameterTypeFqn, isBindingParameterCollection);
      if (action != null) {
        boundActions.put(key, action);
      }
    }

    return action;
  }

  @Override
  public List<EdmFunction> getUnboundFunctions(final FullQualifiedName functionName) {
    final FullQualifiedName functionFqn = resolvePossibleAlias(functionName);

    List<EdmFunction> functions = unboundFunctionsByName.get(functionFqn);
    if (functions == null) {
      functions = createUnboundFunctions(functionFqn);
      if (functions != null) {
        unboundFunctionsByName.put(functionFqn, functions);

        for (EdmFunction unbound : functions) {
          final FunctionMapKey key = new FunctionMapKey(
              new FullQualifiedName(unbound.getNamespace(), unbound.getName()),
              unbound.getBindingParameterTypeFqn(),
              unbound.isBindingParameterTypeCollection(),
              unbound.getParameterNames());
          unboundFunctionsByKey.put(key, unbound);
        }
      }
    }

    return functions;
  }

  @Override
  public EdmFunction getUnboundFunction(final FullQualifiedName functionName, final List<String> parameterNames) {
    final FullQualifiedName functionFqn = resolvePossibleAlias(functionName);

    final FunctionMapKey key = new FunctionMapKey(functionFqn, null, null, parameterNames);
    EdmFunction function = unboundFunctionsByKey.get(key);
    if (function == null) {
      function = createUnboundFunction(functionFqn, parameterNames);
      if (function != null) {
        unboundFunctionsByKey.put(key, function);
      }
    }

    return function;
  }

  @Override
  public EdmFunction getBoundFunction(final FullQualifiedName functionName,
      final FullQualifiedName bindingParameterTypeName,
      final Boolean isBindingParameterCollection, final List<String> parameterNames) {

    final FullQualifiedName functionFqn = resolvePossibleAlias(functionName);
    final FullQualifiedName bindingParameterTypeFqn = resolvePossibleAlias(bindingParameterTypeName);
    final FunctionMapKey key =
        new FunctionMapKey(functionFqn, bindingParameterTypeFqn, isBindingParameterCollection, parameterNames);
    EdmFunction function = boundFunctions.get(key);
    if (function == null) {
      function = createBoundFunction(functionFqn, bindingParameterTypeFqn, isBindingParameterCollection,
          parameterNames);
      if (function != null) {
        boundFunctions.put(key, function);
      }
    }

    return function;
  }

  @Override
  public EdmTerm getTerm(final FullQualifiedName termName) {
    final FullQualifiedName fqn = resolvePossibleAlias(termName);
    EdmTerm term = terms.get(fqn);
    if (term == null) {
      term = createTerm(fqn);
      if (term != null) {
        terms.put(fqn, term);
      }
    }
    return term;
  }

  @Override
  public EdmAnnotations getAnnotationGroup(final FullQualifiedName targetName, String qualifier) {
    final FullQualifiedName fqn = resolvePossibleAlias(targetName);
    TargetQualifierMapKey key = new TargetQualifierMapKey(fqn, qualifier);
    EdmAnnotations _annotations = annotationGroups.get(key);
    if (_annotations == null) {
      _annotations = createAnnotationGroup(fqn, qualifier);
      if (_annotations != null) {
        annotationGroups.put(key, _annotations);
      }
    }
    return _annotations;
  }

  private FullQualifiedName resolvePossibleAlias(final FullQualifiedName namespaceOrAliasFQN) {
    if (aliasToNamespaceInfo == null) {
      loadAliasToNamespaceInfo();
    }
    FullQualifiedName finalFQN = null;
    if (namespaceOrAliasFQN != null) {
      final String namespace = aliasToNamespaceInfo.get(namespaceOrAliasFQN.getNamespace());
      // If not contained in info it must be a namespace
      if (namespace == null) {
        finalFQN = namespaceOrAliasFQN;
      } else {
        finalFQN = new FullQualifiedName(namespace, namespaceOrAliasFQN.getName());
      }
    }
    return finalFQN;
  }

  protected abstract Map<String, EdmSchema> createSchemas();

  protected abstract Map<String, String> createAliasToNamespaceInfo();

  public void cacheAliasNamespaceInfo(final String alias, final String namespace) {
    aliasToNamespaceInfo.put(alias, namespace);
  }

  protected abstract EdmEntityContainer createEntityContainer(FullQualifiedName containerName);

  public void cacheEntityContainer(final FullQualifiedName containerFQN, final EdmEntityContainer container) {
    entityContainers.put(containerFQN, container);
  }

  protected abstract EdmEnumType createEnumType(FullQualifiedName enumName);

  public void cacheEnumType(final FullQualifiedName enumName, final EdmEnumType enumType) {
    enumTypes.put(enumName, enumType);
  }

  protected abstract EdmTypeDefinition createTypeDefinition(FullQualifiedName typeDefinitionName);

  public void cacheTypeDefinition(final FullQualifiedName typeDefName, final EdmTypeDefinition typeDef) {
    typeDefinitions.put(typeDefName, typeDef);
  }

  protected abstract EdmEntityType createEntityType(FullQualifiedName entityTypeName);

  public void cacheEntityType(final FullQualifiedName entityTypeName, final EdmEntityType entityType) {
    entityTypes.put(entityTypeName, entityType);
  }

  protected abstract EdmComplexType createComplexType(FullQualifiedName complexTypeName);

  public void cacheComplexType(final FullQualifiedName compelxTypeName, final EdmComplexType complexType) {
    complexTypes.put(compelxTypeName, complexType);
  }

  protected abstract EdmAction createUnboundAction(FullQualifiedName actionName);

  protected abstract List<EdmFunction> createUnboundFunctions(FullQualifiedName functionName);

  protected abstract EdmFunction createUnboundFunction(FullQualifiedName functionName, List<String> parameterNames);

  protected abstract EdmAction createBoundAction(FullQualifiedName actionName,
      FullQualifiedName bindingParameterTypeName,
      Boolean isBindingParameterCollection);

  protected abstract EdmFunction createBoundFunction(FullQualifiedName functionName,
      FullQualifiedName bindingParameterTypeName, Boolean isBindingParameterCollection,
      List<String> parameterNames);

  public void cacheFunction(final FullQualifiedName functionName, final EdmFunction function) {
    final FunctionMapKey key = new FunctionMapKey(functionName,
        function.getBindingParameterTypeFqn(), function.isBindingParameterTypeCollection(),
        function.getParameterNames());

    if (function.isBound()) {
      boundFunctions.put(key, function);
    } else {
      if (!unboundFunctionsByName.containsKey(functionName)) {
        unboundFunctionsByName.put(functionName, new ArrayList<EdmFunction>());
      }
      unboundFunctionsByName.get(functionName).add(function);

      unboundFunctionsByKey.put(key, function);
    }
  }

  public void cacheAction(final FullQualifiedName actionName, final EdmAction action) {
    if (action.isBound()) {
      final ActionMapKey key = new ActionMapKey(actionName,
          action.getBindingParameterTypeFqn(), action.isBindingParameterTypeCollection());
      boundActions.put(key, action);
    } else {
      unboundActions.put(actionName, action);
    }
  }

  protected abstract EdmTerm createTerm(FullQualifiedName termName);

  public void cacheTerm(final FullQualifiedName termName, final EdmTerm term) {
    terms.put(termName, term);
  }

  protected abstract EdmAnnotations createAnnotationGroup(FullQualifiedName targetName, String qualifier);

  public void cacheAnnotationGroup(final FullQualifiedName targetName,
      final EdmAnnotations annotationsGroup) {
    TargetQualifierMapKey key = new TargetQualifierMapKey(targetName, annotationsGroup.getQualifier());
    annotationGroups.put(key, annotationsGroup);
  }
}


text:
.class public abstract Lcom/htc/sunny/SGalleryAdapter;
.super Lcom/htc/sunny/SBaseAdapter;
.source "SGalleryAdapter.java"

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 25
    invoke-direct {p0}, Lcom/htc/sunny/SBaseAdapter;-><init>()V

    return-void
.end method

# virtual methods
.method public abstract getItemCount()I
.end method

.method public abstract getView(Lcom/htc/sunny/SView;I)Lcom/htc/sunny/SView;
.end method


text:
using LmpClient.Events;
using LmpClient.Systems.ShareProgress;
using LmpCommon.Enums;
using System;
using Guid = System.Guid;

namespace LmpClient.Systems.ShareFunds
{
    public class ShareFundsSystem : ShareProgressBaseSystem<ShareFundsSystem, ShareFundsMessageSender, ShareFundsMessageHandler>
    {
        public override string SystemName { get; } = nameof(ShareFundsSystem);

        private ShareFundsEvents ShareFundsEvents { get; } = new ShareFundsEvents();

        private double _lastFunds;

        //This queue system is not used because we use one big queue in ShareCareerSystem for this system.
        protected override bool ShareSystemReady => true;

        protected override GameMode RelevantGameModes => GameMode.Career;

        public bool Reverting { get; set; }

        public Tuple<Guid, float> CurrentShipCost { get; set; }

        protected override void OnEnabled()
        {
            base.OnEnabled();

            if (!CurrentGameModeIsRelevant) return;
            GameEvents.OnFundsChanged.Add(ShareFundsEvents.FundsChanged);

            RevertEvent.onRevertingToLaunch.Add(ShareFundsEvents.RevertingDetected);
            RevertEvent.onReturningToEditor.Add(ShareFundsEvents.RevertingToEditorDetected);
            GameEvents.onLevelWasLoadedGUIReady.Add(ShareFundsEvents.LevelLoaded);
            GameEvents.onVesselSwitching.Add(ShareFundsEvents.VesselSwitching);
            VesselAssemblyEvent.onAssembledVessel.Add(ShareFundsEvents.VesselAssembled);
        }

        protected override void OnDisabled()
        {
            base.OnDisabled();

            //Always try to remove the event, as when we disconnect from a server the server settings will get the default values
            GameEvents.OnFundsChanged.Remove(ShareFundsEvents.FundsChanged);

            RevertEvent.onRevertingToLaunch.Remove(ShareFundsEvents.RevertingDetected);
            RevertEvent.onReturningToEditor.Remove(ShareFundsEvents.RevertingToEditorDetected);
            GameEvents.onLevelWasLoadedGUIReady.Remove(ShareFundsEvents.LevelLoaded);
            GameEvents.onVesselSwitching.Remove(ShareFundsEvents.VesselSwitching);
            VesselAssemblyEvent.onAssembledVessel.Remove(ShareFundsEvents.VesselAssembled);

            _lastFunds = 0;
            Reverting = false;
        }

        public override void SaveState()
        {
            base.SaveState();
            _lastFunds = Funding.Instance.Funds;
        }

        public override void RestoreState()
        {
            base.RestoreState();
            Funding.Instance.SetFunds(_lastFunds, TransactionReasons.None);
        }

        public void SetFundsWithoutTriggeringEvent(double funds)
        {
            if (!CurrentGameModeIsRelevant) return;

            StartIgnoringEvents();
            Funding.Instance.SetFunds(funds, TransactionReasons.None);
            StopIgnoringEvents();
        }
    }
}