text:
package org.simpleframework.util.parse;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The MapParser object represents a parser for name
 * value pairs. Any parser extending this will typically be parsing
 * name=value tokens or the like, and inserting these pairs into
 * the internal map. This type of parser is useful as it exposes all
 * pairs extracted using the java.util.Map interface
 * and as such can be used with the Java collections framework. The
 * internal map used by this is a Hashtable, however
 * subclasses are free to assign a different type to the map used.
 *
 * @author Niall Gallagher
 */
public abstract class MapParser<T> extends Parser implements Map<T, T> {

   /**
    * Represents all values inserted to the map as a list of values.
    */
   protected Map<T, List<T>> all;

   /**
    * Represents the last value inserted into this map instance.
    */
   protected Map<T, T> map;

   /**
    * Constructor for the MapParser object. This is
    * used to create a new parser that makes use of a thread safe
    * map implementation. The HashMap is used so
    * that the resulting parser can be accessed in a concurrent
    * environment with the fear of data corruption.
    */
   protected MapParser(){
      this.all = new HashMap<T, List<T>>();
      this.map = new HashMap<T, T>();
   }

   /**
    * This is used to determine whether a token representing the
    * name of a pair has been inserted into the internal map. The
    * object passed into this method should be a string, as all
    * tokens stored within the map will be stored as strings.
    *
    * @param name this is the name of a pair within the map
    *
    * @return this returns true if the pair of that name exists
    */
   public boolean containsKey(Object name) {
      return map.containsKey(name);
   }

   /**
    * This method is used to determine whether any pair that has
    * been inserted into the internal map had the presented value.
    * If one or more pairs within the collected tokens contains
    * the value provided then this method will return true.
    *
    * @param value this is the value that is to be searched for
    *
    * @return this returns true if any value is equal to this
    */
   public boolean containsValue(Object value) {
      return map.containsValue(value);
   }

   /**
    * This method is used to acquire the name and value pairs that
    * have currently been collected by this parser. This is used
    * to determine which tokens have been extracted from the
    * source. It is useful when the tokens have to be gathered.
    *
    * @return this set of token pairs that have been extracted
    */
   public Set<Map.Entry<T, T>> entrySet() {
      return map.entrySet();
   }

   /**
    * The get method is used to acquire the value for
    * a named pair. So if a pair of name=value has been parsed and
    * inserted into the collection of tokens this will return the
    * value given the name. The value returned will be a string.
    *
    * @param name this is a string used to search for the value
    *
    * @return this is the value, as a string, that has been found
    */
   public T get(Object name) {
      return map.get(name);
   }

   /**
    * This method is used to acquire a List for all of
    * the values that have been put in to the map. The list allows
    * all values associated with the specified key. This enables a
    * parser to collect a number of associated tokens.
    *
    * @param key this is the key used to search for the value
    *
    * @return this is the list of values associated with the key
    */
   public List<T> getAll(Object key) {
      return all.get(key);
   }

   /**
    * This method is used to determine whether the parser has any
    * tokens available. If the size is zero then the
    * parser is empty and this returns true. The is acts as a
    * proxy the the isEmpty of the internal map.
    *
    * @return this is true if there are no available tokens
    */
   public boolean isEmpty() {
      return map.isEmpty();
   }

   /**
    * This is used to acquire the names for all the tokens that
    * have currently been collected by this parser. This is used
    * to determine which tokens have been extracted from the
    * source. It is useful when the tokens have to be gathered.
    *
    * @return the set of name tokens that have been extracted
    */
   public Set<T> keySet() {
      return map.keySet();
   }

   /**
    * The put method is used to insert the name and
    * value provided into the collection of tokens. Although it is
    * up to the parser to decide what values will be inserted it
    * is generally the case that the inserted tokens will be text.
    *
    * @param name this is the name token from a name=value pair
    * @param value this is the value token from a name=value pair
    *
    * @return this returns the previous value if there was any
    */
   public T put(T name, T value) {
      List<T> list = all.get(name);
      T first = map.get(name);

      if(list == null) {
         list = new ArrayList<T>();
         all.put(name, list);
      }
      list.add(value);

      if(first == null) {
         return map.put(name, value);
      }
      return null;
   }

   /**
    * This method is used to insert a collection of tokens into
    * the parsers map. This is used when another source of tokens
    * is required to populate the connection currently maintained
    * within this parsers internal map. Any tokens that currently
    * exist with similar names will be overwritten by this.
    *
    * @param data this is the collection of tokens to be added
    */
   public void putAll(Map<? extends T, ? extends T> data) {
      Set<? extends T> keySet = data.keySet();

      for(T key : keySet) {
         T value = data.get(key);

         if(value != null) {
            put(key, value);
         }
      }
   }

   /**
    * The remove method is used to remove the named
    * token pair from the collection of tokens. This acts like a
    * take, in that it will get the token value and remove if
    * from the collection of tokens the parser has stored.
    *
    * @param name this is a string used to search for the value
    *
    * @return this is the value, as a string, that is removed
    */
   public T remove(Object name) {
      return map.remove(name);
   }

   /**
    * This obviously enough provides the number of tokens that
    * have been inserted into the internal map. This acts as
    * a proxy method for the internal map size.
    *
    * @return this returns the number of tokens are available
    */
   public int size() {
      return map.size();
   }

   /**
    * This method is used to acquire the value for all tokens that
    * have currently been collected by this parser. This is used
    * to determine which tokens have been extracted from the
    * source. It is useful when the tokens have to be gathered.
    *
    * @return the list of value tokens that have been extracted
    */
   public Collection<T> values() {
      return map.values();
   }

   /**
    * The clear method is used to wipe out all the
    * currently existing tokens from the collection. This is used
    * to recycle the parser so that it can be used to parse some
    * other source of tokens without any lingering state.
    */
   public void clear() {
      all.clear();
      map.clear();
   }
}


text:
package fi.mabrosim.memowidget;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ImageButton;

public class ButtonStateTextWatcher implements TextWatcher {
    private final ImageButton mImgBtn;

    enum STATE {
        INACTIVE,
        CLEAR,
        UNDO
    }

    ButtonStateTextWatcher(ImageButton imgBtn) {
        mImgBtn = imgBtn;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (String.valueOf(mImgBtn.getTag(R.id.cachedText)).isEmpty()) {
            setButtonState(mImgBtn, s.toString().isEmpty() ? STATE.INACTIVE : STATE.CLEAR);
        } else {
            setButtonState(mImgBtn, s.toString().isEmpty() ? STATE.UNDO : STATE.CLEAR);
        }
    }

    private static void setButtonState(ImageButton imageButton, STATE state) {
        if (state == imageButton.getTag(R.id.buttonState)) {
            return;
        }
        imageButton.setTag(R.id.buttonState, state);
        switch (state) {
            case CLEAR: {
                imageButton.setImageResource(R.drawable.ic_clear_black_24dp);
                imageButton.setTag(R.id.cachedText, "");
                break;
            }
            case UNDO: {
                imageButton.setImageResource(R.drawable.ic_undo_black_24dp);
                break;
            }
            default:
            case INACTIVE: {
                imageButton.setImageResource(R.drawable.ic_clear_grey_400_24dp);
                break;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { TaskConfiguration, TaskConfigurationGenerator } from '../../src';
import { RepositoryInitializerTaskOptions } from './options';
export interface CommitOptions {
    message?: string;
    name: string;
    email: string;
}
export declare class RepositoryInitializerTask implements TaskConfigurationGenerator<RepositoryInitializerTaskOptions> {
    workingDirectory: string | undefined;
    commitOptions: CommitOptions | undefined;
    constructor(workingDirectory?: string | undefined, commitOptions?: CommitOptions | undefined);
    toConfiguration(): TaskConfiguration<RepositoryInitializerTaskOptions>;
}


text:
namespace blink {

PassRefPtr<ImagePattern> ImagePattern::create(PassRefPtr<Image> image, RepeatMode repeatMode)
{
    return adoptRef(new ImagePattern(image, repeatMode));
}

ImagePattern::ImagePattern(PassRefPtr<Image> image, RepeatMode repeatMode)
    : Pattern(repeatMode)
    , m_tileImage(image->imageForCurrentFrame())
{
    if (m_tileImage) {
        // TODO(fmalita): mechanism to extract the actual SkImageInfo from an SkImage?
        const SkImageInfo info =
            SkImageInfo::MakeN32Premul(m_tileImage->width(), m_tileImage->height());
        adjustExternalMemoryAllocated(info.getSafeSize(info.minRowBytes()));
    }
}

PassRefPtr<SkShader> ImagePattern::createShader()
{
    if (!m_tileImage)
        return adoptRef(SkShader::CreateColorShader(SK_ColorTRANSPARENT));

    SkMatrix localMatrix = affineTransformToSkMatrix(m_patternSpaceTransformation);

    if (isRepeatXY()) {
        // Fast path: for repeatXY we just return a shader from the original image.
        return adoptRef(m_tileImage->newShader(SkShader::kRepeat_TileMode,
            SkShader::kRepeat_TileMode, &localMatrix));
    }

    // Skia does not have a "draw the tile only once" option. Clamp_TileMode
    // repeats the last line of the image after drawing one tile. To avoid
    // filling the space with arbitrary pixels, this workaround forces the
    // image to have a line of transparent pixels on the "repeated" edge(s),
    // thus causing extra space to be transparent filled.
    SkShader::TileMode tileModeX = isRepeatX()
        ? SkShader::kRepeat_TileMode : SkShader::kClamp_TileMode;
    SkShader::TileMode tileModeY = isRepeatY()
        ? SkShader::kRepeat_TileMode : SkShader::kClamp_TileMode;
    int expandW = isRepeatX() ? 0 : 1;
    int expandH = isRepeatY() ? 0 : 1;

    // Create a transparent image 1 pixel wider and/or taller than the
    // original, then copy the orignal into it.
    // FIXME: Is there a better way to pad (not scale) an image in skia?
    RefPtr<SkSurface> surface = adoptRef(SkSurface::NewRasterN32Premul(
        m_tileImage->width() + expandW, m_tileImage->height() + expandH));
    if (!surface)
        return adoptRef(SkShader::CreateColorShader(SK_ColorTRANSPARENT));

    surface->getCanvas()->clear(SK_ColorTRANSPARENT);
    SkPaint paint;
    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
    surface->getCanvas()->drawImage(m_tileImage.get(), 0, 0, &paint);
    RefPtr<SkImage> expandedImage = adoptRef(surface->newImageSnapshot());

    return adoptRef(expandedImage->newShader(tileModeX, tileModeY, &localMatrix));
}

bool ImagePattern::isTextureBacked() const
{
    return m_tileImage && m_tileImage->isTextureBacked();
}

} // namespace


text:
package com.intellij.util.ui;

import java.awt.*;

public abstract class AbstractLayoutManager implements LayoutManager2 {

  @Override
  public void addLayoutComponent(final Component comp, final Object constraints) {
  }

  @Override
  public Dimension maximumLayoutSize(final Container target) {
    return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
  }

  @Override
  public float getLayoutAlignmentX(final Container target) {
    return 0;
  }

  @Override
  public float getLayoutAlignmentY(final Container target) {
    return 0;
  }

  @Override
  public void invalidateLayout(final Container target) {
  }

  @Override
  public void addLayoutComponent(final String name, final Component comp) {
  }

  @Override
  public void removeLayoutComponent(final Component comp) {
  }

  @Override
  public Dimension minimumLayoutSize(final Container parent) {
    return JBUI.emptySize();
  }

}


text:
package rawpresentation

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/golang/protobuf/ptypes"

	annopb "go.chromium.org/luci/luciexe/legacy/annotee/proto"
	"go.chromium.org/luci/milo/common/model/milostatus"
	"go.chromium.org/luci/milo/frontend/ui"
)

// URLBuilder constructs URLs for various link types.
type URLBuilder interface {
	// LinkURL returns the URL associated with the supplied Link.
	//
	// If no URL could be built for that Link, nil will be returned.
	BuildLink(l *annopb.AnnotationLink) *ui.Link
}

// miloBuildStep converts a logdog/annopb step to a BuildComponent struct.
// buildCompletedTime must be zero if build did not complete yet.
func miloBuildStep(c context.Context, ub URLBuilder, anno *annopb.Step, includeChildren bool) ui.BuildComponent {

	comp := ui.BuildComponent{
		Label: ui.NewLink(anno.Name, "", anno.Name),
	}
	switch anno.Status {
	case annopb.Status_RUNNING:
		comp.Status = milostatus.Running

	case annopb.Status_SUCCESS:
		comp.Status = milostatus.Success

	case annopb.Status_FAILURE:
		if fd := anno.GetFailureDetails(); fd != nil {
			switch fd.Type {
			case annopb.FailureDetails_EXCEPTION, annopb.FailureDetails_INFRA:
				comp.Status = milostatus.InfraFailure

			case annopb.FailureDetails_EXPIRED:
				comp.Status = milostatus.Expired

			default:
				comp.Status = milostatus.Failure
			}

			if fd.Text != "" {
				comp.Text = append(comp.Text, fd.Text)
			}
		} else {
			comp.Status = milostatus.Failure
		}

	case annopb.Status_PENDING:
		comp.Status = milostatus.NotRun

		// Missing the case of waiting on unfinished dependency...
	default:
		comp.Status = milostatus.NotRun
	}

	// Main link is a link to the stdout.
	var stdoutLink *annopb.AnnotationLink
	if anno.StdoutStream != nil {
		stdoutLink = &annopb.AnnotationLink{
			Label: "stdout",
			Value: &annopb.AnnotationLink_LogdogStream{
				LogdogStream: anno.StdoutStream,
			},
		}
	}

	if anno.Link != nil {
		comp.MainLink = ui.LinkSet{ub.BuildLink(anno.Link)}

		// If we also have a STDOUT stream, add it to our OtherLinks.
		if stdoutLink != nil {
			anno.OtherLinks = append([]*annopb.AnnotationLink{stdoutLink}, anno.OtherLinks...)
		}
	} else if stdoutLink != nil {
		comp.MainLink = ui.LinkSet{ub.BuildLink(stdoutLink)}
	}

	// Add STDERR link, if available.
	if anno.StderrStream != nil {
		anno.OtherLinks = append(anno.OtherLinks, &annopb.AnnotationLink{
			Label: "stderr",
			Value: &annopb.AnnotationLink_LogdogStream{
				LogdogStream: anno.StderrStream,
			},
		})
	}

	// Sub link is for one link per log that isn't stdout.
	for _, link := range anno.GetOtherLinks() {
		if l := ub.BuildLink(link); l != nil {
			comp.SubLink = append(comp.SubLink, ui.LinkSet{l})
		}
	}

	// This should always be a step.
	comp.Type = ui.StepLegacy

	// Timestamps
	var start, end time.Time
	if t, err := ptypes.Timestamp(anno.Started); err == nil {
		start = t
	}
	if t, err := ptypes.Timestamp(anno.Ended); err == nil {
		end = t
	}
	comp.ExecutionTime = ui.NewInterval(c, start, end)

	// This should be the exact same thing.
	comp.Text = append(comp.Text, anno.Text...)

	if !includeChildren {
		return comp
	}

	ss := anno.GetSubstep()
	comp.Children = make([]*ui.BuildComponent, 0, len(ss))

	// Process nested steps.
	for _, substep := range ss {
		var subanno *annopb.Step
		switch s := substep.GetSubstep().(type) {
		case *annopb.Step_Substep_Step:
			subanno = s.Step
		case *annopb.Step_Substep_AnnotationStream:
			panic("Non-inline substeps not supported")
		default:
			panic(fmt.Errorf("unknown type %v", s))
		}
		subcomp := miloBuildStep(c, ub, subanno, includeChildren)
		comp.Children = append(comp.Children, &subcomp)
	}

	return comp
}

func addPropGroups(groups *[]*ui.PropertyGroup, bs *ui.BuildComponent, anno *annopb.Step) {
	propGroup := &ui.PropertyGroup{GroupName: bs.Label.Label}
	for _, prop := range anno.Property {
		propGroup.Property = append(propGroup.Property, &ui.Property{
			Key:   prop.Name,
			Value: prop.Value,
		})
	}
	*groups = append(*groups, propGroup)

	for _, child := range bs.Children {
		addPropGroups(groups, child, anno)
	}
}

// SubStepsToUI converts a slice of annotation substeps to ui.BuildComponent and
// slice of ui.PropertyGroups.
func SubStepsToUI(c context.Context, ub URLBuilder, substeps []*annopb.Step_Substep) ([]*ui.BuildComponent, []*ui.PropertyGroup) {
	components := make([]*ui.BuildComponent, 0, len(substeps))
	propGroups := make([]*ui.PropertyGroup, 0, len(substeps)+1) // This is the max number or property groups.
	for _, substepContainer := range substeps {
		anno := substepContainer.GetStep()
		if anno == nil {
			// TODO: We ignore non-embedded substeps for now.
			continue
		}

		bs := miloBuildStep(c, ub, anno, true)
		components = append(components, &bs)
		addPropGroups(&propGroups, &bs, anno)
	}

	return components, propGroups
}

// AddLogDogToBuild takes a set of logdog streams and populate a milo build.
// build.Summary.Finished must be set.
func AddLogDogToBuild(
	c context.Context, ub URLBuilder, mainAnno *annopb.Step, build *ui.MiloBuildLegacy) {

	// Now fill in each of the step components.
	// TODO(hinoka): This is totes cacheable.
	build.Summary = miloBuildStep(c, ub, mainAnno, false)
	build.Components, build.PropertyGroup = SubStepsToUI(c, ub, mainAnno.Substep)

	// Take care of properties
	propGroup := &ui.PropertyGroup{GroupName: "Main"}
	for _, prop := range mainAnno.Property {
		propGroup.Property = append(propGroup.Property, &ui.Property{
			Key:   prop.Name,
			Value: prop.Value,
		})
	}
	build.PropertyGroup = append(build.PropertyGroup, propGroup)

	// Build a property map so we can extract revision properties.
	propMap := map[string]string{}
	for _, pg := range build.PropertyGroup {
		for _, p := range pg.Property {
			propMap[p.Key] = p.Value
		}
	}
	// HACK(hinoka,iannucci): Extract revision out of properties. This should use
	// source manifests instead.
	jrev, ok := propMap["got_revision"]
	if !ok {
		jrev, ok = propMap["revision"]
	}
	if ok {
		// got_revision/revision are json strings, so it looks like "aaaaaabbcc123..."
		var rev string
		err := json.Unmarshal([]byte(jrev), &rev)
		if err == nil {
			if build.Trigger == nil {
				build.Trigger = &ui.Trigger{}
			}
			build.Trigger.Revision = ui.NewLink(
				rev, fmt.Sprintf("https://crrev.com/%s", rev), fmt.Sprintf("revision %s", rev))
		}
	}
}


text:
'use strict';

/**
 * Module dependencies
 * If a module is a directory, the file in the module directory that will be evaluated must be named index.js
 */

// Overrides the standard behaviour of `{[title}}` to ensure the content is correctly escaped

var hbs = require('express-hbs');

function title(options) {
  return new hbs.handlebars.SafeString(hbs.handlebars.Utils.escapeExpression(this.title || ''));
}

module.exports = title;


text:
@import UIKit;

@class Avatar;

@interface APLDetailViewController : UIViewController

@property (nonatomic, strong) Avatar *avatar;

@end


text:
Mongoid::Sequence2.setup do |config|
 config.collection_name = :__sequences
 config.session = :default
end


text:
({
    init:function(component){
    	//setting value here won't make into markup where it reference the value with #.
        component.set("v.initValue","value from init method");
        //var mp = component.get("v.mapValue");
        //component.set("v.mapValue", mp);
    },

    changeProperties:function(component){
        component.set("v.initValue","CHANGED init value");
        component.set("v.booleanValue",false);
        component.set("v.numberValue","8335");
        component.set("v.stringValue","CHANGED string value");
    },

    handleMapValueChangeEvent: function(component) {
    	component.set("v.changeEventTriggered", true);
    }
})


text:
from django.core.management.base import BaseCommand, CommandError
from timetracker.tracker.models import Tbluser

class Command(BaseCommand):
    help = \
        'Sends a reminder of the current balance levels to all accounts ' \
        'in the argument list'

    def handle(self, *args, **options):
        for user in Tbluser.objects.filter(market__in=args, disabled=False):
            user.send_weekly_reminder()


text:
package io.pivotal.demo.smartgrid.frontend.timeseries;

import java.io.Serializable;

/**
 * @author Thomas Darimont
 */
public class DataPoint implements Serializable {

	private static final long serialVersionUID = 1L;

	private long ts;
	private double value;

	public DataPoint(long ts, double value) {
		this.ts = ts;
		this.value = value;
	}

	public long getTs() {
		return ts;
	}

	public void setTs(long ts) {
		this.ts = ts;
	}

	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}
}


text:
            Catálogo Ciudades

                 Inicio>Catálogo Ciudades

			    <button type="button" class="btn btn-primary btn-sm" ng-click="$ctrl.OpenAddCiudad()" title="Crear una ciudad nueva"> NUEVA CIUDAD</button>

                        <input type="text" name="InpSearchCiudad" class="form-control input-sm" ng-model="$SearchCiudad" placeholder="Buscar Ciudad">

                            Id
                            Nombre de la ciudad
                            Acciones

							SIN REGISTROS

                            {{ X.Clv_Ciudad }}
                            {{ X.Nombre }}
                            <button type="button" class="btn btn-info btn-xs" ng-click="$ctrl.OpenViewCiudad(X.Clv_Ciudad)" title="Consultar Ciudad"> CONSULTAR</button>
                            <button type="button" class="btn btn-warning btn-xs" ng-click="$ctrl.OpenUpdateCiudad(X.Clv_Ciudad)" title="Editar Ciudad"> EDITAR</button>
                            <button type="button" class="btn btn-danger btn-xs" ng-click="$ctrl.OpenDeleteCiudad(X.Clv_Ciudad)" title="Eliminar Ciudad"> ELIMINAR</button>

					<dir-pagination-controls max-size="7" direction-links="true" boundary-links="true" ng-if="$ctrl.CiudadLista.length > 0">
					</dir-pagination-controls>


text:
package centaur.cwl

import better.files._
import cats.effect.IO
import centaur.api.CentaurCromwellClient
import centaur.cwl.Outputs._
import centaur.test.TestOptions
import centaur.test.standard.{CentaurTestCase, CentaurTestFormat}
import centaur.test.submit.{SubmitHttpResponse, SubmitWorkflowResponse}
import centaur.test.workflow.{AllBackendsRequired, SubmittedWorkflowTracker, Workflow, WorkflowData}
import com.typesafe.scalalogging.StrictLogging
import common.util.VersionUtil
import cromwell.api.model.{Aborted, Failed, NonTerminalStatus, Succeeded}
import cromwell.core.WorkflowOptions
import cromwell.core.path.PathBuilderFactory
import cromwell.core.path.BetterFileMethods.Cmds
import cwl.preprocessor.{CwlFileReference, CwlPreProcessor}
import spray.json._

import scala.concurrent.Await
import scala.concurrent.duration.Duration

/**
  * Runs workflows in a "cwl-runner" friendly way.
  *
  * https://github.com/broadinstitute/cromwell/issues/2590
  * https://github.com/common-workflow-language/common-workflow-language/blob/v1.0.1/CONFORMANCE_TESTS.md
  * https://github.com/common-workflow-language/common-workflow-language/blob/v1.0.1/draft-3/cwl-runner.cwl#L5-L68
  * https://github.com/common-workflow-language/common-workflow-language/pull/278/files#diff-ee814a9c027fc9750beb075c283a973cR49
  */
object CentaurCwlRunner extends StrictLogging {

  case class SkippedTest(sourceName: String, inputsName: String) {
    def shouldSkip(args: CommandLineArguments) = {
      args.workflowSource.exists(_.name.equalsIgnoreCase(sourceName)) &&
        args.workflowInputs.exists(_.name.equalsIgnoreCase(inputsName))
    }
  }

  case class CommandLineArguments(workflowSource: Option[File] = None,
                                  workflowInputs: Option[File] = None,
                                  quiet: Boolean = false,
                                  outdir: Option[File] = None,
                                  skipFile: Option[File] = None)

  // TODO: This would be cleaner with Enumeratum
  object ExitCode extends Enumeration {

    protected case class ExitVal(status: Int) extends super.Val

    implicit class ValueToVal(val exitCodeValue: Value) extends AnyVal {
      def status: Int = exitCodeValue.asInstanceOf[ExitVal].status
    }

    val Success = ExitVal(0)
    val Failure = ExitVal(1)
    val NotImplemented = ExitVal(33)
  }

  private val cwlPreProcessor = new CwlPreProcessor()
  private val centaurCwlRunnerRunMode = CentaurCwlRunnerRunMode.fromConfig(CentaurCwlRunnerConfig.conf)
  private val parser = buildParser()
  private lazy val centaurCwlRunnerVersion = VersionUtil.getVersion("centaur-cwl-runner")
  private lazy val versionString = s"$centaurCwlRunnerVersion ${centaurCwlRunnerRunMode.description}"

  private def showUsage(): ExitCode.Value = {
    System.err.println(parser.usage)
    ExitCode.Failure
  }

  private def buildParser(): scopt.OptionParser[CommandLineArguments] = {
    new scopt.OptionParser[CommandLineArguments]("java -jar /path/to/centaurCwlRunner.jar") {
      head("centaur-cwl-runner", versionString)

      help("help").text("Centaur CWL Runner - Cromwell integration testing environment")

      version("version").text("Print version and exit")

      arg[String]("workflow-source").text("Workflow source file.").required().
        action((s, c) => c.copy(workflowSource = Option(File(s))))

      arg[String]("inputs").text("Workflow inputs file.").optional().
        action((s, c) => c.copy(workflowInputs = Option(File(s))))

      opt[Unit]("quiet").text("Only print warnings and errors.").optional().
        action((_, c) => c.copy(quiet = true))

      opt[String]("outdir").text("Output directory, default current directory.").optional().
        action((s, c) =>
          c.copy(outdir = Option(File(s))))

      opt[String]("skip-file").text("A csv file describing workflows to be skipped based on their name.").optional().
        action((s, c) =>
          c.copy(skipFile = Option(File(s))))
    }
  }

  private def runCentaur(args: CommandLineArguments): ExitCode.Value = {

    def zipSiblings(file: File): File = {
      val zipFile = File.newTemporaryFile("cwl_imports.", ".zip")
      val dir = file.parent
      if (!args.quiet) {
        logger.info(s"Zipping files under 1mb in $dir to $zipFile")
      }
      // TODO: Only include files under 1mb for now. When cwl runners run in parallel this can use a lot of space.
      val files = dir
        .children
        .filter(_.isRegularFile)
        .filter(_.size < 1 * 1024 * 1024)
      Cmds.zip(files.toSeq: _*)(zipFile)
      zipFile
    }

    val workflowPath = args.workflowSource.get
    val (parsedWorkflowPath, workflowRoot) = workflowPath.path.toAbsolutePath.toString.split("#") match {
      case Array(file) => File(file) -> None
      case Array(file, root) => File(file) -> Option(root)
    }
    val outdirOption = args.outdir.map(_.pathAsString)
    val testName = workflowPath.name
    val preProcessedWorkflow = cwlPreProcessor
      .preProcessCwlToString(CwlFileReference(parsedWorkflowPath, workflowRoot))
      .value.unsafeRunSync() match {
      case Left(errors) =>
        logger.error(s"Failed to pre process cwl workflow: ${errors.toList.mkString(", ")}")
        return ExitCode.Failure
      case Right(v) => v
    }

    val workflowContents = centaurCwlRunnerRunMode.preProcessWorkflow(preProcessedWorkflow)
    val inputContents = args.workflowInputs
      .map(centaurCwlRunnerRunMode.preProcessInput)
      .map(preProcessed => {
        preProcessed.value.unsafeRunSync() match {
          case Left(errors) =>
            logger.error(s"Failed to pre process cwl workflow: ${errors.toList.mkString(", ")}")
            return ExitCode.Failure
          case Right(value) => value
        }
      })

    val workflowType = Option("cwl")
    val workflowTypeVersion = None
    val optionsContents = outdirOption map { outdir =>
      JsObject("cwl_outdir" -> JsString(outdir)).compactPrint
    }
    val labels = List.empty
    val zippedImports = Option(zipSiblings(workflowPath)) // TODO: Zipping all the things! Be more selective.
    val backends = AllBackendsRequired(List.empty)
    val workflowMetadata = None
    val notInMetadata = List.empty
    val directoryContentCounts = None
    val testFormat = CentaurTestFormat.WorkflowSuccessTest
    val testOptions = TestOptions(List.empty, ignore = false)
    val submitResponseOption = None

    val submittedWorkflowTracker = new SubmittedWorkflowTracker()

    val workflowData = WorkflowData(
      Option(workflowContents),
      None,
      None,
      workflowType,
      workflowTypeVersion,
      inputContents.map(IO.pure),
      optionsContents.map(IO.pure),
      labels,
      zippedImports
    )
    val workflow = Workflow(
      testName,
      workflowData,
      workflowMetadata,
      notInMetadata,
      directoryContentCounts,
      backends,
      retryTestFailures = false,
      allowOtherOutputs = true,
      skipDescribeEndpointValidation = true,
      submittedWorkflowTracker = submittedWorkflowTracker,
      maximumAllowedTime = None
    )

    val testCase = CentaurTestCase(workflow, testFormat, testOptions, submittedWorkflowTracker, submitResponseOption)(cromwellTracker = None)

    if (!args.quiet) {
      logger.info(s"Starting test for $workflowPath")
    }

    val pathBuilderFactory: PathBuilderFactory = centaurCwlRunnerRunMode.pathBuilderFactory

    try {
      import CentaurCromwellClient.{blockingEc, system}
      lazy val pathBuilder = Await.result(pathBuilderFactory.withOptions(WorkflowOptions.empty), Duration.Inf)

      testCase.testFunction.run.unsafeRunSync() match {
        case unexpected: SubmitHttpResponse =>
          logger.error(s"Unexpected response: $unexpected")
          ExitCode.Failure
        case SubmitWorkflowResponse(submittedWorkflow) =>
          val status = CentaurCromwellClient.status(submittedWorkflow).unsafeRunSync()
          status match {
            case unexpected: NonTerminalStatus =>
              logger.error(s"Unexpected status: $unexpected")
              ExitCode.Failure
            case Aborted =>
              logger.error(s"Unexpected abort.")
              ExitCode.Failure
            case Failed =>
              logger.error(s"Unexpected failure.")
              ExitCode.Failure
            case Succeeded =>
              val result = handleOutput(submittedWorkflow, pathBuilder)
              if (!args.quiet) {
                logger.info(s"Result: $result")
              } else {
                // Print directly to stdout during --quiet
                println(result)
              }
              ExitCode.Success
          }
      }
    } finally {
      zippedImports map { zipFile =>
        if (!args.quiet) {
          logger.info(s"Deleting $zipFile")
        }
        zipFile.delete(swallowIOExceptions = true)
      }
      Await.result(CentaurCromwellClient.system.terminate(), Duration.Inf)
      ()
    }
  }

  private def skip(args: CommandLineArguments): Boolean =
    args.skipFile
      .map(_.lines).getOrElse(List.empty)
      .map(_.split(','))
      .map({
        case Array(source, inputs) => SkippedTest(source, inputs)
        case invalid => throw new RuntimeException(s"Invalid skipped_tests file: $invalid")
      })
      .exists(_.shouldSkip(args))

  def main(args: Array[String]): Unit = {
    val parsedArgsOption = parser.parse(args, CommandLineArguments())
    val exitCode = parsedArgsOption match {
      case Some(parsedArgs) if skip(parsedArgs) => ExitCode.NotImplemented
      case Some(parsedArgs) => runCentaur(parsedArgs)
      case None => showUsage()
    }
    System.exit(exitCode.status)
  }
}


text:
package com.github.codersparks.brickorganiser.repository.bricklink;

import com.github.codersparks.brickorganiser.model.bricklink.BrickLinkCategory;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * Created by codersparks on 02/01/2017.
 */
public interface BrickLinkCategoryRepository extends MongoRepository<BrickLinkCategory, Integer> {
}


text:
var all_sockets = null;

exports.set_sockets = function(sockets) {
    all_sockets = sockets;
};

exports.connect_chatter = function(config) {
    var sala = config.sala || "principal";
    var socketHandler = require('./server-io-handler')(sala,config.io,config.socket);

    config.socket.on('image message', socketHandler.image_message);
    config.socket.on('chat message', socketHandler.chat_message);
    config.socket.on('prvt message', socketHandler.prvt_message);
    config.socket.on('kickPrv', socketHandler.kick_prv);
    config.socket.on('changeData', socketHandler.change_data);
    config.socket.on('changeRoom', socketHandler.change_room);
    config.socket.on('disconnect', socketHandler.disconnect);
};


text:
package runtime

// TODO this file is copied from pkg/adapterManager.
// Remove the adapterManager package once adapters2 switch is complete.

import (
	"errors"
	"fmt"

	"github.com/golang/glog"

	"istio.io/mixer/pkg/adapter"
)

type logger struct {
	name string
}

var _ adapter.Logger = &logger{}

// stackDepth is used by glog / runtime.Caller
// to determine how many levels of stack to skip
// it should be 1 if logging through a struct and
// it should be 2 if logging through an interface
// If depth=1 is used with an interface, filename appears as <autogenerated>
// logger is used through the adapter.Logger interface.
const stackDepth = 2

func newLogger(name string) logger {
	return logger{name: name}
}

func (l logger) VerbosityLevel(level adapter.VerbosityLevel) bool {
	v := glog.V(glog.Level(level))
	return bool(v)
}

func (l logger) Infof(format string, args ...interface{}) {
	glog.InfoDepth(stackDepth, l.name+":"+fmt.Sprintf(format, args...))
}

func (l logger) Warningf(format string, args ...interface{}) {
	glog.WarningDepth(stackDepth, l.name+":"+fmt.Sprintf(format, args...))
}

func (l logger) Errorf(format string, args ...interface{}) error {
	s := fmt.Sprintf(format, args...)
	glog.ErrorDepth(stackDepth, l.name+":"+s)
	return errors.New(s)
}


text:
set -e  # Fail on error
set -x  # Display commands as run

BUILD_ROOT="$PWD"
SRC="$PWD/github/amber"
BUILD_TYPE="Release"

export ANDROID_NDK="$BUILD_ROOT/android-ndk-r20"
ANDROID_STL="c++_static"
ANDROID_PLATFORM="android-14"
ANDROID_ABI="armeabi-v7a with NEON"

TOOLCHAIN_PATH="$ANDROID_NDK/build/cmake/android.toolchain.cmake"

# removing the old version
echo y | sudo apt-get purge --auto-remove cmake

# Installing the 3.10.2 version
wget http://www.cmake.org/files/v3.10/cmake-3.10.2.tar.gz
tar -xvzf cmake-3.10.2.tar.gz
pushd cmake-3.10.2/
./configure
make
sudo make install
echo "$(date): $(cmake --version)"
popd

# Get NINJA.
wget -q https://github.com/ninja-build/ninja/releases/download/v1.8.2/ninja-linux.zip
unzip -q ninja-linux.zip
export PATH="$PWD:$PATH"

# Get Android NDK.
wget -q https://dl.google.com/android/repository/android-ndk-r20-linux-x86_64.zip
unzip -q android-ndk-r20-linux-x86_64.zip
# ANDROID_NDK is set earlier.

cd "$SRC"
./tools/git-sync-deps

mkdir build && cd "$SRC/build"

# Invoke the build.
echo "$(date): Starting build..."
cmake -GNinja \
    "-DCMAKE_BUILD_TYPE=$BUILD_TYPE" \
    "-DANDROID_ABI=$ANDROID_ABI" \
    "-DANDROID_PLATFORM=$ANDROID_PLATFORM" \
    "-DANDROID_NDK=$ANDROID_NDK" \
    "-DANDROID_STL=$ANDROID_STL" \
    "-DCMAKE_TOOLCHAIN_FILE=$TOOLCHAIN_PATH" \
     ..

echo "$(date): Build everything..."
ninja
echo "$(date): Build completed."


text:
package com.raauto.jaxb;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (name="correctiveStep")
public class CorrectiveStep implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = -4612748846470261821L;
	private int 	m_id;
	private String name;
	private ApplicableWhen applicableWhen;

	/**
	 * @return the m_Id
	 */
	@XmlAttribute(name="id")
	public int getID() {
		return m_id;
	}
	/**
	 * @param m_Id the m_Id to set
	 */
	public void setID(int string) {
		this.m_id = string;
	}

	@XmlAttribute (name="name", required=true)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@XmlElement(name="applicableWhen", required=true)
	public ApplicableWhen getApplicableWhen() {
		return applicableWhen;
	}
	public void setApplicableWhen(ApplicableWhen applicableWhen) {
		this.applicableWhen = applicableWhen;
	}
}


text:
Compiling/running unit tests
------------------------------------

Unit tests will be automatically compiled if dependencies were met in configure
and tests weren't explicitly disabled.

After configuring, they can be run with 'make check'.

To run the creditsd tests manually, launch src/test/test_credits .

To add more creditsd tests, add `BOOST_AUTO_TEST_CASE` functions to the existing
.cpp files in the test/ directory or add new .cpp files that
implement new BOOST_AUTO_TEST_SUITE sections.

To run the credits-qt tests manually, launch src/qt/test/credits-qt_test

To add more credits-qt tests, add them to the `src/qt/test/` directory and
the `src/qt/test/test_main.cpp` file.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration (PMD 5.0.0 API)
</TITLE>

<META NAME="date" CONTENT="2012-05-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
net.sourceforge.pmd.lang.java.ast.ASTConstructorDeclaration

Packages that use ASTConstructorDeclaration

net.sourceforge.pmd.lang.java.ast

net.sourceforge.pmd.lang.java.dfa

net.sourceforge.pmd.lang.java.rule

net.sourceforge.pmd.lang.java.rule.codesize

net.sourceforge.pmd.lang.java.rule.design

net.sourceforge.pmd.lang.java.rule.optimizations

net.sourceforge.pmd.lang.java.rule.strictexception

net.sourceforge.pmd.lang.java.rule.sunsecure

net.sourceforge.pmd.lang.java.rule.unusedcode

net.sourceforge.pmd.lang.java.symboltable

net.sourceforge.pmd.lang.java.typeresolution.rules

net.sourceforge.pmd.util.designer

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.ast

Methods in net.sourceforge.pmd.lang.java.ast with parameters of type ASTConstructorDeclaration

 Object
JavaParserVisitor.visit(ASTConstructorDeclaration node,
      Object data)

 Object
JavaParserVisitorAdapter.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.dfa

Methods in net.sourceforge.pmd.lang.java.dfa with parameters of type ASTConstructorDeclaration

 void
VariableAccessVisitor.compute(ASTConstructorDeclaration node)

 Object
DataFlowFacade.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule

Methods in net.sourceforge.pmd.lang.java.rule with parameters of type ASTConstructorDeclaration

 Object
AbstractJavaRule.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule.codesize

Methods in net.sourceforge.pmd.lang.java.rule.codesize with parameters of type ASTConstructorDeclaration

 Object
CyclomaticComplexityRule.visit(ASTConstructorDeclaration node,
      Object data)

 Object
NcssTypeCountRule.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule.design

Methods in net.sourceforge.pmd.lang.java.rule.design with parameters of type ASTConstructorDeclaration

 Object
AccessorClassGenerationRule.visit(ASTConstructorDeclaration node,
      Object data)

          Store all target constructors

 Object
ConstructorCallsOverridableMethodRule.visit(ASTConstructorDeclaration node,
      Object data)

          Non-private constructor's methods are added to a list for later safety
 evaluation.

 Object
AvoidReassigningParametersRule.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule.optimizations

Methods in net.sourceforge.pmd.lang.java.rule.optimizations with parameters of type ASTConstructorDeclaration

 Object
MethodArgumentCouldBeFinalRule.visit(ASTConstructorDeclaration constructor,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule.strictexception

Methods in net.sourceforge.pmd.lang.java.rule.strictexception with parameters of type ASTConstructorDeclaration

 Object
SignatureDeclareThrowsExceptionRule.visit(ASTConstructorDeclaration constructorDeclaration,
      Object o)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule.sunsecure

Methods in net.sourceforge.pmd.lang.java.rule.sunsecure with parameters of type ASTConstructorDeclaration

 Object
ArrayIsStoredDirectlyRule.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.rule.unusedcode

Methods in net.sourceforge.pmd.lang.java.rule.unusedcode with parameters of type ASTConstructorDeclaration

 Object
UnusedFormalParameterRule.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.symboltable

Methods in net.sourceforge.pmd.lang.java.symboltable with parameters of type ASTConstructorDeclaration

 Object
ScopeAndDeclarationFinder.visit(ASTConstructorDeclaration node,
      Object data)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.lang.java.typeresolution.rules

Methods in net.sourceforge.pmd.lang.java.typeresolution.rules with parameters of type ASTConstructorDeclaration

 Object
SignatureDeclareThrowsException.visit(ASTConstructorDeclaration constructorDeclaration,
      Object o)

Uses of ASTConstructorDeclaration in net.sourceforge.pmd.util.designer

Methods in net.sourceforge.pmd.util.designer that return types with arguments of type ASTConstructorDeclaration

 List<ASTConstructorDeclaration>
DFAGraphRule.getConstructors()

Methods in net.sourceforge.pmd.util.designer with parameters of type ASTConstructorDeclaration

 Object
DFAGraphRule.visit(ASTConstructorDeclaration node,
      Object data)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2002-2012 InfoEther. All Rights Reserved.


text:
package com.adaptris.core.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

import com.adaptris.sftp.ConfigBuilder;
import com.adaptris.sftp.HostConfig;
import com.adaptris.sftp.PerHostConfigBuilder;

public class PerHostConfigRepositoryBuilder extends InlineConfigRepositoryBuilder {
  private List<String> knownHosts = new ArrayList<>();

  public PerHostConfigRepositoryBuilder(File known_hosts, boolean strict) throws IOException {
    super(strict);
    try (InputStream in = new FileInputStream(known_hosts)) {
      List<String> lines = IOUtils.readLines(in);
      for (String line : lines) {
        String[] parts=line.split("\\s");
        knownHosts.add(parts[0]);
        System.err.println("[" + parts[0] + "]");
      }
    }
  }

  @Override
  public ConfigBuilder build() {
    PerHostConfigBuilder repo = new PerHostConfigBuilder();
    repo.getDefaultConfiguration().addAll(config());
    for (String host : knownHosts) {
      HostConfig cfg = new HostConfig();
      cfg.setHostname(host);
      cfg.getConfig().addAll(config());
      repo.getHosts().add(cfg);
    }
    return repo;
  }
}


text:
package tests.purchase;

import agents.EconomicAgent;
import goods.*;
import agents.firm.Firm;
import agents.firm.purchases.PurchasesDepartment;
import agents.firm.purchases.inventoryControl.DailyInventoryControl;
import agents.firm.purchases.inventoryControl.FixedInventoryControl;
import agents.firm.purchases.inventoryControl.InventoryControl;
import agents.firm.purchases.inventoryControl.Level;
import agents.firm.purchases.prediction.PricingPurchasesPredictor;
import agents.firm.purchases.pricing.BidPricingStrategy;
import agents.firm.purchases.pricing.decorators.LookAtTheMarketBidPricingDecorator;
import agents.firm.sales.exploration.BuyerSearchAlgorithm;
import agents.firm.sales.exploration.SellerSearchAlgorithm;
import agents.firm.utilities.NumberOfPlantsListener;
import ec.util.MersenneTwisterFast;
import financial.market.Market;
import financial.market.OrderBookBlindMarket;
import financial.market.OrderBookMarket;
import financial.utilities.Quote;
import model.MacroII;
import model.utilities.dummies.DummySeller;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;

/**
 *
Description

 *

 *

 *

 *
Notes

 * Created with IntelliJ
 *

 *

 *
References

 *
 * @author Ernesto
 * @version 2012-08-18
 * @see
 */
public class PurchasesDepartmentTest {

    @Test
    public void testGetPurchasesDepartmentIntegrated() throws Exception {

    }

    @Test
    public void testGetPurchasesDepartment() throws Exception {

        Firm firm = mock(Firm.class);
        MacroII model = new MacroII(1);
        when(firm.getRandom()).thenReturn(new MersenneTwisterFast());
        when(firm.getModel()).thenReturn(model);

        //make sure stuff gets generated at random!
        for(int i=0; i < 10; i++)
        {
            final Market mock = mock(Market.class);
            when(mock.getGoodType()).thenReturn(UndifferentiatedGoodType.GENERIC);
            PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(1000,firm, mock,
                    (Class<? extends InventoryControl>) null,null,null,null).getDepartment();

            Field field = PurchasesDepartment.class.getDeclaredField("control");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof InventoryControl); //so we can start it!
            assertTrue(!(field.get(dept) instanceof BidPricingStrategy)); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("pricingStrategy");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BidPricingStrategy); //so we can start it!
            assertTrue(!(field.get(dept) instanceof InventoryControl)); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("opponentSearch");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BuyerSearchAlgorithm); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("supplierSearch");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof SellerSearchAlgorithm); //so we can start it!

        }

        //make sure stuff gets generated at random with integrated stuff!
        for(int i=0; i < 10; i++)
        {
            final Market mock = mock(Market.class);
            when(mock.getGoodType()).thenReturn(UndifferentiatedGoodType.GENERIC);
            PurchasesDepartment dept = PurchasesDepartment.
                    getPurchasesDepartmentIntegrated(1000,firm,mock,null,null,null).getDepartment() ;

            Field field = PurchasesDepartment.class.getDeclaredField("control");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BidPricingStrategy); //should be inheriting from both!
            assertTrue(field.get(dept) instanceof InventoryControl);

            field = PurchasesDepartment.class.getDeclaredField("pricingStrategy");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BidPricingStrategy); //should be inheriting from both!
            assertTrue(field.get(dept) instanceof InventoryControl);

            field = PurchasesDepartment.class.getDeclaredField("opponentSearch");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BuyerSearchAlgorithm); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("supplierSearch");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof SellerSearchAlgorithm); //so we can start it!

        }

        //make sure stuff gets generated when the string name is correct
        for(int i=0; i < 10; i++)
        {
            final Market mock = mock(Market.class);
            when(mock.getGoodType()).thenReturn(UndifferentiatedGoodType.GENERIC);
            PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(1000, firm, mock, "FixedInventoryControl",
                    "SurveyMaxPricing", "SimpleBuyerSearch", "SimpleSellerSearch").getDepartment() ;

            Field field = PurchasesDepartment.class.getDeclaredField("control");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof InventoryControl); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("pricingStrategy");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BidPricingStrategy); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("opponentSearch");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof BuyerSearchAlgorithm); //so we can start it!

            field = PurchasesDepartment.class.getDeclaredField("supplierSearch");
            field.setAccessible(true);
            assertTrue(field.get(dept) != null); //so we can start it!
            assertTrue(field.get(dept) instanceof SellerSearchAlgorithm); //so we can start it!

        }

    }

    @Test
    public void testMaxPrice() throws Exception {
        Firm firm = mock(Firm.class);
        MacroII model = new MacroII(1);
        Market market = mock(Market.class); when(market.isBestSalePriceVisible()).thenReturn(true); when(market.getBestSellPrice()).thenReturn(-1); //stub market, price visible but no best price around!
        when(firm.getRandom()).thenReturn(new MersenneTwisterFast());
        when(firm.getModel()).thenReturn(model);

        final Market mock = mock(Market.class);
        when(mock.getGoodType()).thenReturn(UndifferentiatedGoodType.GENERIC);
        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(1,firm, mock,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();

        //addSalesDepartmentListener a stub pricing
        BidPricingStrategy pricingStrategy = mock(BidPricingStrategy.class);
        dept.setPricingStrategy(new LookAtTheMarketBidPricingDecorator(pricingStrategy,market));   //addSalesDepartmentListener it as new strategy

        when(pricingStrategy.maxPrice((Good) any())).thenReturn(100); //this always prices at 100!
        when(pricingStrategy.maxPrice((GoodType) any())).thenReturn(100); //this always prices at 100!

        assertEquals(dept.maxPrice(DifferentiatedGoodType.CAPITAL, market), 100); //bounded by pricing choice
        when(market.getBestSellPrice()).thenReturn(30);
        assertEquals(dept.maxPrice(DifferentiatedGoodType.CAPITAL, market), 30); //bounded by best visible price

    }

    @Test
    public void testReactToFilledQuote() throws Exception {

        for (int i = 0; i < 100; i++) {

            MacroII model = new MacroII(System.currentTimeMillis());
            model.start();
            Firm firm = new Firm(model);
            firm.receiveMany(UndifferentiatedGoodType.MONEY, 100000);
            Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);
            market.start(model);

            PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(100000, firm, market,
                    FixedInventoryControl.class, null, null, null).getDepartment();

            firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
            dept.buy(); //place a bid or whatever
            model.schedule.step(model);
            Field field = PurchasesDepartment.class.getDeclaredField("quotePlaced");
            field.setAccessible(true);
            Quote q = (Quote) field.get(dept);
            assertTrue(q != null);
            assertTrue(q.getPriceQuoted() >= 0);

            //if I put in a bad quote it should throw an exception
            try {
                dept.reactToFilledQuote(Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL, firm, 10), 10, null);
                fail();
            } catch (AssertionError e) {
            }

            DummySeller seller = new DummySeller(model, 0);
            market.registerSeller(seller);
            Good good = Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL, firm, 10);
            seller.receive(good, null);
            market.submitSellQuote(seller, 0, good);
            model.schedule.step(model);

            field = PurchasesDepartment.class.getDeclaredField("quotePlaced");
            field.setAccessible(true);
            Quote newQuote = (Quote) field.get(dept);
            assertTrue(newQuote != null); //a new quote is needed.
            assertTrue(q != newQuote);

        }

    }

    @Test
    public void testShop() throws Exception {

        MacroII model = new MacroII(1);
        model.start();
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        Market market = new OrderBookBlindMarket(DifferentiatedGoodType.CAPITAL);
        market.start(model);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                FixedInventoryControl.class,null,null,null).getDepartment();

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        BidPricingStrategy pricingStrategy = mock(BidPricingStrategy.class);//i am going to force the dept to offer maxPrice = 150
        when(pricingStrategy.maxPrice(any(GoodType.class))).thenReturn(150);
        dept.setPricingStrategy(pricingStrategy);

        DummySeller seller1 = new DummySeller(model,100*(1),market);
        market.registerSeller(seller1);
        Good good = Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL,firm,10);
        seller1.receive(good,null );
        assert seller1.has(good);
        assert seller1.hasAny(good.getType());
        //     market.submitSellQuote(seller1,5,good);   //even though it places a quote for 0, it will answer "100" when the shopper asks him

        DummySeller seller2 = new DummySeller(model,100*(2));
        market.registerSeller(seller2);
        Good good2 = Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL,firm,10);
        seller2.receive(good2,null );

        dept.shop(); //shop should find and trade with the seller1
        model.schedule.step(model);

        assertTrue(firm.has(good));
        assertTrue(!firm.has(good2));
        //should have paid 125!
        assertEquals(firm.hasHowMany(UndifferentiatedGoodType.MONEY), 1000 - 125);

    }

    @Test
    public void testBuy() throws Exception {

        MacroII model = new MacroII(1);
        model.start();
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);
        market.start(model);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(2000,firm,market,
                FixedInventoryControl.class,null,null,null).getDepartment();

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        BidPricingStrategy pricingStrategy = mock(BidPricingStrategy.class);//i am going to force the dept to offer maxPrice = 150
        when(pricingStrategy.maxPrice(any(GoodType.class))).thenReturn(150);
        dept.setPricingStrategy(pricingStrategy);

        for(int i=0; i<10; i++)
        {
            final DummySeller seller = new DummySeller(model,75 * (i)){
                @Override
                public void reactToFilledAskedQuote(Quote quoteFilled, Good g, int price, EconomicAgent agent) {
                    market.deregisterSeller(this);

                }
            };

            market.registerSeller(seller);
            Good good =Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL,seller,0);
            seller.receive(good,null);
            market.submitSellQuote(seller,seller.saleQuote,good);

        }

        assertEquals(firm.hasHowMany(DifferentiatedGoodType.CAPITAL), 0);

        //now cascade!
        dept.buy();

        model.schedule.step(model);

        assertEquals(firm.hasHowMany(DifferentiatedGoodType.CAPITAL), 3);
        assertEquals(market.getBestSellPrice(), 75 * 3);
        assertEquals(market.getBestBuyPrice(), 150);

    }

    @Test
    public void testGetGoodType() throws Exception {

        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
        assertEquals(dept.getGoodType(), market.getGoodType());
        market.deregisterBuyer(firm);
        dept = PurchasesDepartment.getPurchasesDepartmentIntegrated(200,firm,market,
                null,null,null).getDepartment();
        assertEquals(dept.getGoodType(), market.getGoodType());
        market.deregisterBuyer(firm);
        dept = PurchasesDepartment.getPurchasesDepartment(1000, firm,market, "FixedInventoryControl",
                "SurveyMaxPricing", "SimpleBuyerSearch", "SimpleSellerSearch").getDepartment();
        assertEquals(dept.getGoodType(), market.getGoodType());

    }

    @Test
    public void testGetFirm() throws Exception {
        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
        assertEquals(dept.getFirm(), firm);
        market.deregisterBuyer(firm);
        dept = PurchasesDepartment.getPurchasesDepartmentIntegrated(200,firm,market,
                null,null,null).getDepartment();
        assertEquals(dept.getFirm(), firm);
        market.deregisterBuyer(firm);
        dept = PurchasesDepartment.getPurchasesDepartment(1000, firm,market, "FixedInventoryControl",
                "SurveyMaxPricing", "SimpleBuyerSearch", "SimpleSellerSearch").getDepartment();
        assertEquals(dept.getFirm(), firm);
    }

    @Test
    public void testSetInventoryControl() throws Exception {
        //make sure you set the right thing and kill off listeners
        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
        for(int i=0; i <100; i++)
        {
            InventoryControl control = new DailyInventoryControl(dept);
            dept.setControl(control);
            Field field = PurchasesDepartment.class.getDeclaredField("control");
            field.setAccessible(true);
            assertEquals(control, field.get(dept));
        }

        //check the listeners now
        Field field = Firm.class.getDeclaredField("numberOfPlantsListeners");
        field.setAccessible(true);

        Set<NumberOfPlantsListener> listenerList = (Set<NumberOfPlantsListener>) field.get(firm);
        assertTrue(listenerList.size() == 1);
        assertTrue(listenerList.iterator().next() instanceof DailyInventoryControl);

        field = EconomicAgent.class.getDeclaredField("inventory");
        field.setAccessible(true);
        Inventory inventory = (Inventory) field.get(firm);
        field = Inventory.class.getDeclaredField("listeners");
        field.setAccessible(true);
        Set<InventoryListener> listeners = (Set<InventoryListener>) field.get(inventory);
        assertTrue(listeners.size() >= 1);
        boolean found = false;
        for(InventoryListener il : listeners)
            found = found || il instanceof DailyInventoryControl;
        assertTrue(found);

    }

    @Test
    public void testSetPricingStrategy() throws Exception {

        //make sure you set the right thing and kill off listeners
        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
        BidPricingStrategy stub = null;
        for(int i=0; i <100; i++)
        {

            BidPricingStrategy strategy = mock(BidPricingStrategy.class);

            dept.setPricingStrategy(strategy);
            if(stub != null)
                verify(stub).turnOff(); //make sure it was turned off

            stub = strategy;

            //make sure it's assigned correctly
            Field field = PurchasesDepartment.class.getDeclaredField("pricingStrategy");
            field.setAccessible(true);
            assertEquals(strategy, field.get(dept));
        }

    }

    @Test
    public void testSetOpponentSearch() throws Exception {

        //make sure you set the right thing and kill off listeners
        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
        BuyerSearchAlgorithm stub = null;
        for(int i=0; i <100; i++)
        {

            BuyerSearchAlgorithm searchAlgorithm = mock(BuyerSearchAlgorithm.class);

            dept.setOpponentSearch(searchAlgorithm);
            if(stub != null)
                verify(stub).turnOff(); //make sure it was turned off

            stub = searchAlgorithm;

            //make sure it's assigned correctly
            Field field = PurchasesDepartment.class.getDeclaredField("opponentSearch");
            field.setAccessible(true);
            assertEquals(searchAlgorithm, field.get(dept));
        }

    }

    @Test
    public void testSetSupplierSearch() throws Exception
    {

        //make sure you set the right thing and kill off listeners
        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
        SellerSearchAlgorithm stub = null;
        for(int i=0; i <100; i++)
        {

            SellerSearchAlgorithm searchAlgorithm = mock(SellerSearchAlgorithm.class);

            dept.setSupplierSearch(searchAlgorithm);
            if(stub != null)
                verify(stub).turnOff(); //make sure it was turned off

            stub = searchAlgorithm;

            //make sure it's assigned correctly
            Field field = PurchasesDepartment.class.getDeclaredField("supplierSearch");
            field.setAccessible(true);
            assertEquals(searchAlgorithm, field.get(dept));
        }

    }

    @Test
    public void testWeekEnd() throws Exception {

        //make sure you set the right thing and kill off listeners
        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();

        //make sure it's assigned correctly
        Field field = PurchasesDepartment.class.getDeclaredField("budgetSpent");
        field.setAccessible(true);
        field.set(dept,100);
        assertTrue(dept.getAvailableBudget() == 100);
        dept.weekEnd(1);
        //should adjust the budget
        assertTrue(dept.getAvailableBudget() == 100);
        assertEquals(field.get(dept), 0);
        field = PurchasesDepartment.class.getDeclaredField("budgetGiven");
        field.setAccessible(true);
        assertEquals(100, field.get(dept));
    }

    @Test
    public void testUpdatePrices() throws Exception
    {

        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);
        market.start(model);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                FixedInventoryControl.class,null,null,null).getDepartment();
        dept.setPredictor(new PricingPurchasesPredictor());

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        BidPricingStrategy pricingStrategy = mock(BidPricingStrategy.class);//i am going to force the dept to offer maxPrice = 150
        when(pricingStrategy.maxPrice(any(GoodType.class))).thenReturn(150);
        dept.setPricingStrategy(pricingStrategy);

        dept.start(model);
        model.start();
        model.schedule.step(model);

        assertEquals(market.getBestBuyPrice(), 150);
        when(pricingStrategy.maxPrice(any(GoodType.class))).thenReturn(75);
        assertEquals(market.getBestBuyPrice(), 150);
        dept.updateOfferPrices();
        model.getPhaseScheduler().step(model);

        assertEquals(market.getBestBuyPrice(), 75);

    }

    @Test
    public void testGetAvailableBudgetShop() throws Exception
    {

        //this is a copy of shop, after it's done we make sure the budget was updated

        MacroII model = new MacroII(1);
        model.start();
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        Market market = new OrderBookBlindMarket(DifferentiatedGoodType.CAPITAL);
        market.start(model);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(200,firm,market,
                FixedInventoryControl.class,null,null,null).getDepartment();

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        BidPricingStrategy pricingStrategy = mock(BidPricingStrategy.class);//i am going to force the dept to offer maxPrice = 150
        when(pricingStrategy.maxPrice(any(GoodType.class))).thenReturn(150);
        dept.setPricingStrategy(pricingStrategy);

        DummySeller seller1 = new DummySeller(model,100*(1),market);
        market.registerSeller(seller1);
        Good good = Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL,firm,10);
        seller1.receive(good,null );
        assert seller1.has(good);
        assert seller1.hasAny(good.getType());
        //     market.submitSellQuote(seller1,5,good);   //even though it places a quote for 0, it will answer "100" when the shopper asks him

        DummySeller seller2 = new DummySeller(model,100*(2));
        market.registerSeller(seller2);
        Good good2 =Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL,firm,10);
        seller2.receive(good2,null );

        dept.shop(); //shop should find and trade with the seller1
        model.schedule.step(model);

        assertEquals(firm.hasHowMany(DifferentiatedGoodType.CAPITAL),1);
        //should have paid 125!
        assertEquals(firm.hasHowMany(UndifferentiatedGoodType.MONEY), 1000 - 125);

        assertEquals(dept.getAvailableBudget(), 75);

    }

    @Test
    public void testGetAvailableBudgetBid() throws Exception
    {

        //this is a copy of testbuy

        MacroII model = new MacroII(1);
        model.start();

        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);
        market.start(model);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(2000,firm,market,
                FixedInventoryControl.class,null,null,null).getDepartment();

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        BidPricingStrategy pricingStrategy = mock(BidPricingStrategy.class);//i am going to force the dept to offer maxPrice = 150
        when(pricingStrategy.maxPrice(any(GoodType.class))).thenReturn(150);
        dept.setPricingStrategy(new LookAtTheMarketBidPricingDecorator(pricingStrategy,market));   //addSalesDepartmentListener it as new strategy

        for(int i=0; i<10; i++)
        {
            final DummySeller seller = new DummySeller(model,75 * (i)){
                @Override
                public void reactToFilledAskedQuote(Quote quoteFilled, Good g, int price, EconomicAgent agent) {
                    market.deregisterSeller(this);

                }
            };

            market.registerSeller(seller);
            Good good =Good.getInstanceOfDifferentiatedGood(DifferentiatedGoodType.CAPITAL,seller,0);
            seller.receive(good,null);
            market.submitSellQuote(seller,seller.saleQuote,good);

        }

        assertEquals(firm.hasHowMany(DifferentiatedGoodType.CAPITAL), 0);

        //now cascade!
        dept.buy();
        model.schedule.step(model);

        assertEquals(firm.hasHowMany(DifferentiatedGoodType.CAPITAL), 3);
        assertEquals(market.getBestSellPrice(), 75 * 3);
        assertEquals(market.getBestBuyPrice(), 150);

        //new check
        assertEquals(dept.getAvailableBudget(), 2000 - (150 + 75));

    }

    @Test
    public void testRateInventoryLevel() throws Exception {

        //this is a copy of testbuy

        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(2000,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        InventoryControl control = mock(InventoryControl.class);//i am going to force the dept to offer maxPrice = 150
        //make sure it asks inventory control
        when(control.rateCurrentLevel()).thenReturn(Level.DANGER);
        dept.setControl(control);
        assertEquals(dept.rateCurrentLevel(), Level.DANGER);
        when(control.rateCurrentLevel()).thenReturn(Level.BARELY);
        assertEquals(dept.rateCurrentLevel(), Level.BARELY);
        when(control.rateCurrentLevel()).thenReturn(Level.ACCEPTABLE);
        assertEquals(dept.rateCurrentLevel(), Level.ACCEPTABLE);

    }

    @Test
    public void testGetMarket() throws Exception {
        //this is a copy of testbuy

        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(2000,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();

        assertEquals(dept.getMarket(), market);

    }

    @Test
    public void testCanBuy() throws Exception {

        //this is a copy of testbuy

        MacroII model = new MacroII(1);
        Firm firm = new Firm(model);
        firm.receiveMany(UndifferentiatedGoodType.MONEY,1000);
        final Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);

        PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(2000,firm,market,
                (Class<? extends InventoryControl>) null,null,null,null).getDepartment();

        firm.registerPurchasesDepartment(dept, DifferentiatedGoodType.CAPITAL);
        InventoryControl control = mock(InventoryControl.class);
        //make sure it asks inventory control
        when(control.canBuy()).thenReturn(true);
        dept.setControl(control);
        assertEquals(dept.canBuy(), true);
        when(control.canBuy()).thenReturn(false);
        assertEquals(dept.canBuy(), false);
    }

    @Test
    public void testTurnOff() throws Exception {

        Firm firm = mock(Firm.class);
        MacroII model = new MacroII(1);
        Market market = new OrderBookMarket(DifferentiatedGoodType.CAPITAL);
        when(firm.getRandom()).thenReturn(new MersenneTwisterFast());
        when(firm.getModel()).thenReturn(model);
        final Set<InventoryListener> inventoryListenersRegistered = new HashSet<>();
        final Set<InventoryListener> inventoryListenersDeregistered = new HashSet<>();
        final Set<NumberOfPlantsListener> plantListenersRegistered  = new HashSet<>();
        final Set<NumberOfPlantsListener> plantListenersDeregistered = new HashSet<>();

        /*****************  ****************************************************************
         * INVENTORY LISTENERS
         *************************************************************************************/
        doAnswer(new Answer<Object>() {        //put the listeners in the the big set
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                inventoryListenersRegistered.add((InventoryListener) invocation.getArguments()[0]);

                return null;
            }}).when(firm).addInventoryListener(any(InventoryListener.class));

        //when removing the method is boolean, not void so we have to use this different syntax.
        when(firm.removeInventoryListener(any(InventoryListener.class))).then(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                inventoryListenersDeregistered.add((InventoryListener) invocation.getArguments()[0]);

                return true;
            }
        });
        /*****************  ****************************************************************
         * plant listeners
         *************************************************************************************/
        doAnswer(new Answer<Object>() {        //put the listeners in the the big set
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                plantListenersRegistered.add((NumberOfPlantsListener) invocation.getArguments()[0]);

                return null;
            }}).when(firm).addPlantCreationListener(any(NumberOfPlantsListener.class));

        //when removing the method is boolean, not void so we have to use this different syntax.
        when(firm.removePlantCreationListener(any(NumberOfPlantsListener.class))).then(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                plantListenersDeregistered.add((NumberOfPlantsListener) invocation.getArguments()[0]);

                return true;
            }
        });

        //we are going to count how many times listeners get registered and hopefully it matches the number of times they get deregistered
        for(int i=0; i < 100; i++){
            PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartment(2000,firm,market,
                    (Class<? extends InventoryControl>) null,null,null,null).getDepartment();
            dept.turnOff();
        }
        for(int i=0; i < 100; i++){
            PurchasesDepartment dept = PurchasesDepartment.getPurchasesDepartmentIntegrated(2000,firm,market,
                    null,null,null).getDepartment();
            dept.turnOff();
        }

        //make sure every inventory listener registered is deregistered
        assertTrue(inventoryListenersDeregistered.size() > 0);
        assertTrue(inventoryListenersRegistered.size() > 0);
        assertTrue(inventoryListenersDeregistered.containsAll(inventoryListenersRegistered));
        assertTrue(inventoryListenersRegistered.containsAll(inventoryListenersDeregistered));
        //make sure every plant creation registered is deregistered
        assertTrue(plantListenersRegistered.size() > 0);
        assertTrue(plantListenersDeregistered.size() > 0);
        assertTrue(plantListenersRegistered.containsAll(plantListenersDeregistered));
        assertTrue(plantListenersDeregistered.containsAll(plantListenersRegistered));

    }

    @Test
    public void testGetRandom() throws Exception {

    }

    @Test
    public void testGetBestSupplierFound() throws Exception {

    }

    @Test
    public void testGetBestOpponentFound() throws Exception {

    }

    @Test
    public void testSupplierSearchFailure() throws Exception {

    }

    @Test
    public void testSupplierSearchSuccess() throws Exception {

    }

    @Test
    public void testOpponentSearchFailure() throws Exception {

    }

    @Test
    public void testOpponentSearchSuccess() throws Exception {

    }

    @Test
    public void testGetBestOpponent() throws Exception {

    }

    @Test
    public void testStart() throws Exception {

    }
}


text:
import sys

def greetName(name):
	print("Hello " + name + ", how are you?")

def readName():
	name = input("What is your name?: ")
	greetName(name)

if __name__ == '__main__':
	readName()


text:
namespace Google.Cloud.NetworkConnectivity.V1.Snippets
{
    // [START networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_async_flattened]
    using Google.Cloud.NetworkConnectivity.V1;
    using System.Threading.Tasks;

    public sealed partial class GeneratedPolicyBasedRoutingServiceClientSnippets
    {
        /// <summary>Snippet for GetPolicyBasedRouteAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task GetPolicyBasedRouteAsync()
        {
            // Create client
            PolicyBasedRoutingServiceClient policyBasedRoutingServiceClient = await PolicyBasedRoutingServiceClient.CreateAsync();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/[LOCATION]/global/PolicyBasedRoutes/[POLICY_BASED_ROUTE]";
            // Make the request
            PolicyBasedRoute response = await policyBasedRoutingServiceClient.GetPolicyBasedRouteAsync(name);
        }
    }
    // [END networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_async_flattened]
}


text:
title: Migrating from v2.x to v3.x
path: "/docs/migration/v3"
---

# Migrating from v2.x to v3.x

<!-- MarkdownTOC depth=1 autolink=true bracket=round -->

- [RxJS imports](#rxjs-imports)
- [Lodash imports](#lodash-imports)
- [Webpack builds](#webpack-builds)
- [frint-store](#frint-store)
- [frint-model](#frint-model)
- [frint-compat](#frint-compat)

<!-- /MarkdownTOC -->

## RxJS imports

All RxJS modules are now imported individually, resulting in smaller bundle sizes in your applications.

This also means, the observables returned by FrintJS packages will not have the operators (like `map`, `filter`, etc) built in any more, and they need to be imported manually too if you need them.

### Before

We can take an example from `frint-store`:

```js
const todos$ = store.getState$()
  .filter(state => state.showTodos === true)
  .map(state => state.todos);

todos$.subscribe(todos => console.log(todos));
```

### After

```js
import { filter } from 'rxjs/operator/filter';
import { map } from 'rxjs/operator/map';

const todos$ = store.getState$()
  ::filter(state => state.showTodos === true)
  ::map(state => state.todos);

todos$.subscribe(todos => console.log(todos));
```

The syntax above is written using the [bind-operator](https://github.com/tc39/proposal-bind-operator).

It could also have been written like this:

```js
import { filter } from 'rxjs/operator/filter';
import { map } from 'rxjs/operator/map';

const todos$ = map.call(
  filter.call(
    store.getState$(),
    state => state.showTodos === true
  ),
  state => state.todos
);

todos$.subscribe(todos => console.log(todos));
```

## Lodash imports

All lodash imports have also been updated to import only the modules that are needed.

If you want to take benefit of reduced bundle size in your applications, then you can follow the same approach.

### Before

```js
import _ from 'lodash';

_.isPlainObject({});
```

### After

```js
import isPlainObject from 'lodash/isPlainObject';

isPlainObject({});
```

## Webpack builds

If your application is set up in a way like this:

* `vendors.js`: All third party libraries (RxJS, Lodash, Frint, etc)
* `app.js`: Your custom code for Frint App(s)

Or you are loading the vendors directly from CDN via `<script>` tags, then you risk loading some RxJS and Lodash modules twice.

To help avoid that, we are shipping a new `frint-config` package that has information about the list of external dependencies, that you can map accordingly.

### Before

```js
// webpack.config.js
module.exports = {
  entry: __dirname + '/src/index.js',
  output: {
    path: __dirname + '/build'
  },
  externals: {
    'lodash': '_', // window._
    'rxjs': 'Rx', // window.Rx

    // other libraries
    'react': 'React',
    'react-dom': 'ReactDOM',
  },
}
```

### After

```js
// webpack.js

// all RxJS and Lodash imports
// are mapped to global `window._` and `window.Rx`
const externals = require('frint-config').externals;

module.exports = {
  entry: __dirname + '/src/index.js',
  output: {
    path: __dirname + '/build'
  },
  externals: Object.assign(
    {},

    // RxJS and Lodash
    externals,

    // other libraries
    {
      'react': 'React',
      'react-dom': 'ReactDOM',
    }
  ),
}
```

## frint-store

`thunkArgument` option has been renamed to `deps`.

### Before

```js
import { createStore } from 'frint-store';

const Store = createStore({
  thunkArgument: {},
});
```

### After

```js
import { createStore } from 'frint-store';

const Store = createStore({
  deps: {},
});
```

## frint-model

Deprecated and will be completely removed when v4.0 gets released. Use `frint-data` instead.

### Before

```js
import { createModel } from 'frint-model';

const Todo = createModel({
  getTitle() {
    return this.get('title');
  },
  setTitle(newTitle) {
    this.set('title', newTitle);
  },
});

const todo = new Todo({
  title: 'Hello World',
  completed: false,
});

const title = todo.getTitle();
todo.setTitle('Updated title');
```

### After

```js
import { Types, createModel } from 'frint-data';

const Todo = createModel({
  schema: {
    title: Types.string, // or, Types.string.required
    completed: Types.bool, // or, Types.bool.defaults(false),
  },
  setTitle(newTitle) {
    this.title = newTitle;
  },
});

const todo = new Todo({
  title: 'Hello World',
  completed: false,
});

const title = todo.title;
todo.setTitle('Updated title');
```

## frint-compat

Completely emptied, and `v0.x` is no longer supported in any way.


text:
package org.apache.sis.internal.jaxb.code;

import javax.xml.bind.annotation.XmlElement;
import org.opengis.metadata.distribution.MediumFormat;
import org.apache.sis.internal.jaxb.cat.CodeListAdapter;
import org.apache.sis.internal.jaxb.cat.CodeListUID;
import org.apache.sis.xml.Namespaces;

/**
 * JAXB adapter for {@link MediumFormat}
 * in order to wrap the value in an XML element as specified by ISO 19115-3 standard.
 * See package documentation for more information about the handling of {@code CodeList} in ISO 19115-3.
 *
 * @author  Cédric Briançon (Geomatys)
 * @version 1.0
 * @since   0.3
 * @module
 */
public final class MD_MediumFormatCode extends CodeListAdapter<MD_MediumFormatCode, MediumFormat> {
    /**
     * Empty constructor for JAXB only.
     */
    public MD_MediumFormatCode() {
    }

    /**
     * Creates a new adapter for the given value.
     */
    private MD_MediumFormatCode(final CodeListUID value) {
        super(value);
    }

    /**
     * {@inheritDoc}
     *
     * @return the wrapper for the code list value.
     */
    @Override
    protected MD_MediumFormatCode wrap(final CodeListUID value) {
        return new MD_MediumFormatCode(value);
    }

    /**
     * {@inheritDoc}
     *
     * @return the code list class.
     */
    @Override
    protected Class<MediumFormat> getCodeListClass() {
        return MediumFormat.class;
    }

    /**
     * Invoked by JAXB on marshalling.
     *
     * @return the value to be marshalled.
     */
    @Override
    @XmlElement(name = "MD_MediumFormatCode", namespace = Namespaces.MRD)
    public CodeListUID getElement() {
        return identifier;
    }

    /**
     * Invoked by JAXB on unmarshalling.
     *
     * @param  value  the unmarshalled value.
     */
    public void setElement(final CodeListUID value) {
        identifier = value;
    }
}


text:
package com.manywho.microservices.reporting.entities;

import java.util.UUID;

public class StateEvent extends FlowEvent {
    private UUID state;

    public UUID getState() {
        return state;
    }
}


text:
import {BaseIfc} from "./BaseIfc"

// http://www.buildingsmart-tech.org/ifc/IFC4/final/html/link/ifcplanarforcemeasure.htm
export type IfcPlanarForceMeasure = number