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

package xfuzzy.xfedit;

import xfuzzy.lang.*;
import java.awt.*;

/**
 * Componente asociado a una variable (un punto) en la representación
 * gráfica de la estructura jerárquica de un sistema difuso
 *
 * @author Francisco José Moreno Velo
 *
 */
public class XfeditVariableDot {

	//----------------------------------------------------------------------------//
	//                            MIEMBROS PUBLICOS                               //
	//----------------------------------------------------------------------------//

	/**
	 * Componente de llamada al que pertenece la variable. Null si se trata de una
	 * variable global
	 */
	public XfeditCallComponent call;

	/**
	 * Variable asociada al componente
	 */
	public Variable sysvar;

	/**
	 * Posición horizontal del componente
	 */
	public int x;

	/**
	 * Posición vertical del componente
	 */
	public int y;

	/**
	 * Canal asignado para las conexiones
	 */
	public int channel;

	/**
	 * Nivel de profundidad
	 */
	public int level;

	//----------------------------------------------------------------------------//
	//                            MIEMBROS PRIVADOS                               //
	//----------------------------------------------------------------------------//

	/**
	 * Indice de la variable en el componente de llamada
	 */
	private int index;

	/**
	 * Indicador del caracter de la variable asociada (entrada o salida)
	 */
	private boolean input;

	/**
	 * Característica del tipo de letra
	 */
	private int descent;

	/**
	 * Tipo de letra para escribir el nombre
	 */
	private FontMetrics fm;

	//----------------------------------------------------------------------------//
	//                                CONSTRUCTOR                                 //
	//----------------------------------------------------------------------------//

	/**
	 * Constructor de un punto asociado a una variable de una llamada
	 */
	public XfeditVariableDot(XfeditStructure structure, XfeditCallComponent call,
			int index, int level, boolean input) {
		this.fm = structure.getFontMetrics(structure.getFont());
		this.descent = fm.getDescent();

		this.call = call;
		this.index = index;
		this.input = input;
		this.sysvar = (input ? call.call.getInputVariables()[index] :
			call.call.getOutputVariables()[index]);
		this.level = level;
		if(call != null && !input)
		{ this.channel = structure.counter; structure.counter++; }
		if(call == null && input)
		{ this.channel = structure.counter; structure.counter++; }
	}

	/**
	 * Constructor de un punto asociado a una variable global
	 */
	public XfeditVariableDot(XfeditStructure structure, Variable sysvar,
			int level, boolean input) {
		this.fm = structure.getFontMetrics(structure.getFont());
		this.descent = fm.getDescent();

		this.call = null;
		this.index = -1;
		this.input = input;
		this.sysvar = sysvar;
		this.level = level;
		if(call != null && !input)
		{ this.channel = structure.counter; structure.counter++; }
		if(call == null && input)
		{ this.channel = structure.counter; structure.counter++; }
	}

	//----------------------------------------------------------------------------//
	//                             MÉTODOS PÚBLICOS                               //
	//----------------------------------------------------------------------------//

	/**
	 *  Verifica si el punto corresponde a una variable global
	 */
	public boolean isGlobal() {
		return (call == null);
	}

	/**
	 * Verifica si el punto corresponde a una base de reglas
	 */
	public boolean isInternal() {
		return (call != null);
	}

	/**
	 * Verifica si el punto no está enlazado
	 */
	public boolean isNull() {
		return (sysvar == null || sysvar.equals("NULL"));
	}

	/**
	 * Verifica si el punto corresponde a una entrada
	 */
	public boolean isInput() {
		return input;
	}

	/**
	 * Verifica si el punto corresponde a una salida
	 */
	public boolean isOutput() {
		return !input;
	}

	/**
	 * Verifica si el punto puede ser origen de un enlace
	 */
	public boolean isOrigin() {
		return (call == null && input) ||
		(call != null && !input);
	}

	/**
	 * Verifica si el punto puede ser destino de un enlace
	 */
	public boolean isDestination() {
		return (call == null && !input) ||
		(call != null && input);
	}

	/**
	 *  Selecciona la variable de sistema del punto
	 */
	public void setSystemVariable(Variable var) {
		if(this.call == null) return;
		if(input) this.call.call.setInputVariable(index, var);
		if(!input) this.call.call.setOutputVariable(index, var);
		this.sysvar = var;
	}

	/**
	 * Selecciona la posición del punto
	 */
	public void setPoint(int x, int y) {
		this.x = x;
		this.y = y;
	}

	/**
	 * Verifica que la posición corresponde al punto
	 */
	public boolean include(int px, int py) {
		return (px>x - 5 && px<x + 5 && py>y - 2 && py<y + 5);
	}

	/**
	 * Dibuja el punto con su identificador
	 */
	public void paintDot(Graphics g) {
		String label = "";
		if(call == null) label = sysvar.toString();
		else if(call.call instanceof RulebaseCall) {
			RulebaseCall rbcall = (RulebaseCall) call.call;
			if(input) label = rbcall.getRulebase().getInputs()[index].toString();
			else label = rbcall.getRulebase().getOutputs()[index].toString();
		}
		int sw = fm.stringWidth(label);
		if(input) {
			g.drawString(label,x-sw-2,y-descent-4);
			g.fillRect(x-5,y-2,5,5);
		}
		else {
			g.drawString(label,x+2,y-descent-4);
			g.fillRect(x,y-2,5,5);
		}
	}
}


text:
import os.path
import yaml
from werkzeug import import_string
from werkzeug.serving import run_simple
from dextrose.http import Response
from dextrose.context import Context
from dextrose.events import EventManager
from dextrose.dispatcher import Dispatcher
from dextrose.utils import import_module, titlize

def load_config(package, environment):
    """Load configuration from <package_dir>/config/<environment>.yaml"""
    filename = os.path.join(os.path.dirname(package.__file__), 'config', '%s.yaml' % environment)
    config_file = file(filename, 'r')
    config = yaml.load(config_file)
    return config

def load_application(package_name, environment):
    """Import and instantiate the application object. By default, this is dextrose.application.Application,
    but it can be specified as the 'class' option in the configuration file."""
    module = import_module(package_name)
    config = load_config(module, environment)
    app_class_name = config.get('class', 'dextrose.application.Application')
    app_class = import_string(app_class_name)
    app = app_class(module, config)
    return app

class Application(object):
    def __init__(self, module, config):
        self.module = module
        self.module_name = module.__name__
        self.directory = os.path.dirname(self.module.__file__)
        self.config = config
        self.hooks = {}
        self.events = EventManager(self)
        self.dispatcher = Dispatcher(self)
        self.load_extensions()

    def wsgi(self, environ, start_response):
        """WSGI entry point, delegated to ``Dispatcher.dispatch``."""
        response = self.dispatcher.dispatch(environ)
        return response(environ, start_response)

    def open_file(self, filename, mode='r'):
        # FIXME: Use pkg_resources
        full_filename = os.path.join(self.directory, filename)
        f = open(full_filename, mode)
        return f

    def load_extensions(self):
        self.extensions = {}
        for extension_name, extension_config in self.config['extensions'].items():
            print "Loading extension %s" % extension_name
            module = import_module(extension_name)
            class_name = '%sExtension' % titlize(extension_name.rsplit('.', 1)[-1])
            extension_class = getattr(module, class_name, None)
            if extension_class is None:
                raise RuntimeError("Extension %s is missing a %s class" % (extension_name, class_name))
            extension = extension_class(self, extension_config)
            self.extensions[extension_name] = extension

    def register_hook_function(self, name, function):
        hooks = self.hooks.setdefault(name, [])
        hooks.append(function)

    def get_hook_functions(self, name):
        functions = self.hooks.get(name, [])
        return functions

redpajama_set_name: RedPajamaGithub


text:
#ifndef __CC3000_SPI_H__
#define __CC3000_SPI_H__

//*****************************************************************************
//
// If building with a C++ compiler, make all of the definitions in this header
// have a C binding.
//
//*****************************************************************************
#ifdef  __cplusplus
extern "C" {
#endif

typedef void (*gcSpiHandleRx)(void *p);
typedef void (*gcSpiHandleTx)(void);
extern unsigned char wlan_tx_buffer[];

//*****************************************************************************
//
// Prototypes for the APIs.
//
//*****************************************************************************

// the arguments must be of type pin_obj_t* and SPI_HandleTypeDef*
extern void SpiInit(void *spi, const void *pin_cs, const void *pin_en, const void *pin_irq);

extern void SpiOpen(gcSpiHandleRx pfRxHandler);
extern void SpiClose(void);
extern void SpiPauseSpi(void);
extern void SpiResumeSpi(void);
extern long SpiWrite(unsigned char *pUserBuffer, unsigned short usLength);
extern void SpiConfigureHwMapping(void);
extern void SpiCleanGPIOISR(void);
extern void SSIConfigure(unsigned long ulSSIFreq, unsigned long bForceGpioConfiguration, unsigned long uiReconfigureSysClock);
extern int init_spi(void);
extern long ReadWlanInterruptPin(void);
extern void WriteWlanPin(unsigned char val);
//*****************************************************************************
//
// Mark the end of the C bindings section for C++ compilers.
//
//*****************************************************************************
#ifdef  __cplusplus
}
#endif // __cplusplus

#endif


text:
package com.armadialogcreator.canvas;

import com.armadialogcreator.util.UpdateGroupListener;
import com.armadialogcreator.util.UpdateListenerGroup;
import javafx.animation.AnimationTimer;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.geometry.VPos;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.paint.ImagePattern;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

/**
 @author Kayler
 @since 05/11/2016. */
public abstract class UICanvas<N extends UINode> extends AnchorPane {

	/** javafx Canvas */
	protected final Canvas canvas;
	/** GraphicsContext for the canvas */
	protected final GraphicsContext gc;
	/** {@link CanvasContext} for the canvas */
	protected CanvasContext canvasContext = new CanvasContext();
	/** The timer that handles repainting */
	protected final CanvasAnimationTimer timer;

	protected final Resolution resolution;

	protected UINode rootNode;

	/** Background image of the canvas */
	protected ImagePattern backgroundImage = null;

	/** Background color of the canvas */
	protected Color backgroundColor = CanvasViewColors.EDITOR_BG;

	/** Mouse button that is currently down */
	protected final Point lastMousePosition = new Point(-1, -1);//last x and y positions of the mouse relative to the canvas

	protected Keys keys = new Keys();

	/** All components added */
	protected final ObservableList<CanvasComponent> components = FXCollections.observableArrayList(new ArrayList<>());

	private volatile boolean needPaint = false;
	/** A synchronization lock for {@link #needPaint} to help prevent data races */
	private final Object needPaintLock = new Object();
	/** Set to true if {@link #requestPaint()} is not necessary and will always paint when {@link #timer} wants to */
	protected boolean alwaysPaint = false;

	private final UpdateGroupListener renderUpdateGroupListener = (group, data) -> {
		requestPaint();
	};

	public UICanvas(@NotNull Resolution resolution, @NotNull UINode rootNode) {
		this.resolution = resolution;
		resolution.getUpdateGroup().addListener(new UpdateGroupListener<Resolution>() {
			@Override
			public void update(@NotNull UpdateListenerGroup<Resolution> group, @NotNull Resolution newResolution) {
				if (getCanvasHeight() != newResolution.getScreenHeight() || getCanvasWidth() != newResolution.getScreenWidth()) {
					canvas.setWidth(newResolution.getScreenWidth());
					canvas.setHeight(newResolution.getScreenHeight());
				}
				requestPaint();
			}
		});

		this.canvas = new Canvas(resolution.getScreenWidth(), resolution.getScreenHeight());
		this.gc = this.canvas.getGraphicsContext2D();

		this.getChildren().add(this.canvas);
		UICanvas.CanvasMouseEvent mouseEvent = new UICanvas.CanvasMouseEvent(this);

		this.setOnMousePressed(mouseEvent);
		this.setOnMouseReleased(mouseEvent);
		this.setOnMouseMoved(mouseEvent);
		this.setOnMouseDragged(mouseEvent);
		components.addListener(new ListChangeListener<CanvasComponent>() {
			@Override
			public void onChanged(Change<? extends CanvasComponent> c) {
				requestPaint();
			}
		});

		//do this last
		this.rootNode = rootNode;
		setUINodeListeners(true);

		timer = new CanvasAnimationTimer();
		timer.start();

	}

	@NotNull
	public UINode getRootNode() {
		return rootNode;
	}

	public int getCanvasWidth() {
		return (int) canvas.getWidth();
	}

	public int getCanvasHeight() {
		return (int) this.canvas.getHeight();
	}

	public void setRootNode(@NotNull UINode rootNode) {
		setUINodeListeners(false);
		this.rootNode = rootNode;
		setUINodeListeners(true);
		requestPaint();
	}

	@SuppressWarnings("unchecked")
	private void setUINodeListeners(boolean add) {
		if (add) {
			this.rootNode.renderUpdateGroup().addListener(renderUpdateGroupListener);
		} else {
			this.rootNode.renderUpdateGroup().removeListener(renderUpdateGroupListener);
		}
	}

	/** Adds a component to the canvas and repaints the canvas */
	public void addComponent(@NotNull CanvasComponent component) {
		this.components.add(component);
	}

	/**
	 Removes the given component from the canvas render and user interaction.

	 @param component component to remove
	 @return true if the component was removed, false if nothing was removed
	 */
	public boolean removeComponent(@NotNull CanvasComponent component) {
		return this.components.remove(component);
	}

	/**
	 Paint the canvas. Order of painting is:

background

{@link #getRootNode()}

components inserted via {@link #addComponent(CanvasComponent)}

	 */
	protected void paint() {
		gc.setTextBaseline(VPos.TOP); //we actually need to run this with each call for some reason
		gc.save();
		paintBackground();
		paintRootNode();
		paintComponents();
		for (Function<GraphicsContext, Void> f : canvasContext.getPaintLast()) {
			f.apply(gc);
		}
		canvasContext.getPaintLast().clear();
		gc.restore();
	}

	/**
	 Request a repaint.
	 The paint operation won't happen until {@link #getTimer()} discovers the paint request.
	 Therefore, multiple requests can be made and not have any performance impacts.

	 This method can be used across multiple threads.
	 */
	public void requestPaint() {
		synchronized (needPaintLock) {
			needPaint = true;
		}
	}

	/**
	 Paints all nodes in {@link #getRootNode()} and will iterate each child's child as well.
	 Each component will get an individual render space (GraphicsContext attributes will not bleed through each component).
	 */
	protected void paintRootNode() {
		paintNodes(rootNode);
	}

	private void paintNodes(@NotNull UINode node) {
		for (UINode child : node.deepIterateChildren()) {
			paintNode(rootNode);
			paintNodes(child);
		}
	}

	/**
	 Paints all components. Each component will get an individual render space
	 (GraphicsContext attributes will not bleed through each component).
	 Before the paint, the components are sorted with {@link CanvasComponent#RENDER_PRIORITY_COMPARATOR}
	 */
	protected void paintComponents() {
		this.components.sort(CanvasComponent.RENDER_PRIORITY_COMPARATOR);
		for (CanvasComponent component : components) {
			paintComponent(component);
		}
	}

	protected void paintBackground() {
		gc.setFill(backgroundColor);
		gc.fillRect(0, 0, this.canvas.getWidth(), this.canvas.getHeight());
		if (backgroundImage == null) {
			return;
		}
		gc.setFill(backgroundImage);
		gc.fillRect(0, 0, this.canvas.getWidth(), this.canvas.getHeight());
	}

	protected void paintNode(@NotNull UINode node) {
		if (node.getComponent() == null) {
			return;
		}
		paintComponent(node.getComponent());
	}

	protected void paintComponent(@NotNull CanvasComponent component) {
		if (component.isGhost()) {
			return;
		}
		gc.save();
		component.paint(gc, canvasContext);
		gc.restore();
	}

	/** Sets canvas background image and automatically repaints */
	public void setCanvasBackgroundImage(@Nullable ImagePattern background) {
		this.backgroundImage = background;
		requestPaint();
	}

	/** Sets canvas background color and repaints the canvas */
	public void setCanvasBackgroundColor(@NotNull Color color) {
		this.backgroundColor = color;
		requestPaint();
	}

	/** @return the background image, or null if not set */
	@Nullable
	public ImagePattern getBackgroundImage() {
		return backgroundImage;
	}

	/** @return the background color */
	@NotNull
	public Color getBackgroundColor() {
		return backgroundColor;
	}

	/**
	 This is called when the mouse listener is invoked and a mouse press was the event.
	 Default implementation does nothing.

	 @param mousex x position of mouse relative to canvas
	 @param mousey y position of mouse relative to canvas
	 @param mb mouse button that was pressed
	 */
	protected void mousePressed(int mousex, int mousey, @NotNull MouseButton mb) {
	}

	/**
	 This is called when the mouse listener is invoked and a mouse release was the event.
	 Default implementation does nothing.

	 @param mousex x position of mouse relative to canvas
	 @param mousey y position of mouse relative to canvas
	 @param mb mouse button that was released
	 */
	protected void mouseReleased(int mousex, int mousey, @NotNull MouseButton mb) {
	}

	/**
	 This is called when the mouse is moved and/or dragged inside the canvas. Default implementation does nothing.

	 @param mousex x position of mouse relative to canvas
	 @param mousey y position of mouse relative to canvas
	 */
	protected void mouseMoved(int mousex, int mousey) {
	}

	/**
	 This should be called when any mouse event occurs (press, release, drag, move, etc)

	 @param shiftDown true if the shift key is down, false otherwise
	 @param ctrlDown true if the ctrl key is down, false otherwise
	 @param altDown true if alt key is down, false otherwise
	 */
	public void keyEvent(String key, boolean keyIsDown, boolean shiftDown, boolean ctrlDown, boolean altDown) {
		keys.update(key, keyIsDown, shiftDown, ctrlDown, altDown);
		requestPaint();
	}

	/**
	 This is called after mouseMove is called.
	 This will ensure that no matter how mouse move exits, the last mouse position will be updated
	 */
	private void setLastMousePosition(int mousex, int mousey) {
		lastMousePosition.set(mousex, mousey);
	}

	@NotNull
	public CanvasAnimationTimer getTimer() {
		return timer;
	}

	@Override
	protected double computeMinWidth(double height) {
		return getCanvasWidth();
	}

	@Override
	protected double computeMinHeight(double width) {
		return getCanvasHeight();
	}

	@Override
	protected double computePrefWidth(double height) {
		return getCanvasWidth();
	}

	@Override
	protected double computePrefHeight(double width) {
		return getCanvasHeight();
	}

	@Override
	protected double computeMaxWidth(double height) {
		return super.computeMaxWidth(height);
	}

	@Override
	protected double computeMaxHeight(double width) {
		return super.computeMaxHeight(width);
	}

	@NotNull
	public Canvas getCanvas() {
		return canvas;
	}

	/** Clear any listeners attached to {@link #rootNode} */
	public void clearListeners() {
		setUINodeListeners(false);
	}

	/**
	 Created by Kayler on 05/13/2016.
	 */
	private static class CanvasMouseEvent implements EventHandler<MouseEvent> {
		private final UICanvas canvas;
		private boolean mouseDown = false;

		CanvasMouseEvent(UICanvas canvas) {
			this.canvas = canvas;
		}

		@Override
		public void handle(MouseEvent event) {
			MouseButton btn = event.getButton();
			if (!(event.getTarget() instanceof Canvas)) {
				return;
			}

			Canvas c = (Canvas) event.getTarget();
			Point2D p = c.sceneToLocal(event.getSceneX(), event.getSceneY());
			int mousex = (int) p.getX();
			int mousey = (int) p.getY();

			if (event.getEventType() == MouseEvent.MOUSE_MOVED || event.getEventType() == MouseEvent.MOUSE_DRAGGED) {
				canvas.mouseMoved(mousex, mousey);
				canvas.setLastMousePosition(mousex, mousey);
				if (mouseDown) {
					this.canvas.requestPaint();
				}
			} else {
				if (event.getEventType() == MouseEvent.MOUSE_PRESSED) {
					mouseDown = true;
					canvas.mousePressed(mousex, mousey, btn);
				} else if (event.getEventType() == MouseEvent.MOUSE_RELEASED) {
					canvas.mouseReleased(mousex, mousey, btn);
					mouseDown = false;
					canvas.requestPaint();
				}
			}

		}

	}

	public class CanvasAnimationTimer extends AnimationTimer {

		private final List<Runnable> runnables = new ArrayList<>();

		@Override
		public void handle(long now) {
			for (Runnable r : runnables) {
				r.run();
			}
			if (!alwaysPaint) {
				synchronized (needPaintLock) {
					//synchronize to prevent data race
					if (needPaint) {
						needPaint = false;
						paint();
					}
				}
			} else {
				paint();
			}
		}

		/** @return a list of runnables to run on each timer update */
		@NotNull
		public List<Runnable> getRunnables() {
			return runnables;
		}
	}

}


text:
package org.apache.spark.deploy

import scala.collection.immutable.List

import org.apache.spark.deploy.ExecutorState.ExecutorState
import org.apache.spark.deploy.master.{WorkerInfo, ApplicationInfo}
import org.apache.spark.deploy.master.RecoveryState.MasterState
import org.apache.spark.deploy.worker.ExecutorRunner
import org.apache.spark.util.Utils

private[deploy] sealed trait DeployMessage extends Serializable

/** Contains messages sent between Scheduler actor nodes. */
private[deploy] object DeployMessages {

  // Worker to Master

  case class RegisterWorker(
      id: String,
      host: String,
      port: Int,
      cores: Int,
      memory: Int,
      webUiPort: Int,
      publicAddress: String)
    extends DeployMessage {
    Utils.checkHost(host, "Required hostname")
    assert (port > 0)
  }

  case class ExecutorStateChanged(
      appId: String,
      execId: Int,
      state: ExecutorState,
      message: Option[String],
      exitStatus: Option[Int])
    extends DeployMessage

  case class WorkerSchedulerStateResponse(id: String, executors: List[ExecutorDescription])

  case class Heartbeat(workerId: String) extends DeployMessage

  // Master to Worker

  case class RegisteredWorker(masterUrl: String, masterWebUiUrl: String) extends DeployMessage

  case class RegisterWorkerFailed(message: String) extends DeployMessage

  case class KillExecutor(masterUrl: String, appId: String, execId: Int) extends DeployMessage

  case class LaunchExecutor(
      masterUrl: String,
      appId: String,
      execId: Int,
      appDesc: ApplicationDescription,
      cores: Int,
      memory: Int,
      sparkHome: String)
    extends DeployMessage

  // Client to Master

  case class RegisterApplication(appDescription: ApplicationDescription)
    extends DeployMessage

  case class MasterChangeAcknowledged(appId: String)

  // Master to Client

  case class RegisteredApplication(appId: String, masterUrl: String) extends DeployMessage

  // TODO(matei): replace hostPort with host
  case class ExecutorAdded(id: Int, workerId: String, hostPort: String, cores: Int, memory: Int) {
    Utils.checkHostPort(hostPort, "Required hostport")
  }

  case class ExecutorUpdated(id: Int, state: ExecutorState, message: Option[String],
    exitStatus: Option[Int])

  case class ApplicationRemoved(message: String)

  // Internal message in Client

  case object StopClient

  // Master to Worker & Client

  case class MasterChanged(masterUrl: String, masterWebUiUrl: String)

  // MasterWebUI To Master

  case object RequestMasterState

  // Master to MasterWebUI

  case class MasterStateResponse(host: String, port: Int, workers: Array[WorkerInfo],
    activeApps: Array[ApplicationInfo], completedApps: Array[ApplicationInfo],
    status: MasterState) {

    Utils.checkHost(host, "Required hostname")
    assert (port > 0)

    def uri = "spark://" + host + ":" + port
  }

  //  WorkerWebUI to Worker

  case object RequestWorkerState

  // Worker to WorkerWebUI

  case class WorkerStateResponse(host: String, port: Int, workerId: String,
    executors: List[ExecutorRunner], finishedExecutors: List[ExecutorRunner], masterUrl: String,
    cores: Int, memory: Int, coresUsed: Int, memoryUsed: Int, masterWebUiUrl: String) {

    Utils.checkHost(host, "Required hostname")
    assert (port > 0)
  }

  // Actor System to Worker

  case object SendHeartbeat
}


text:
.class public Landroid/support/constraint/solver/widgets/Helper;
.super Landroid/support/constraint/solver/widgets/ConstraintWidget;
.source "Helper.java"

# instance fields
.field protected mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

.field protected mWidgetsCount:I

# direct methods
.method public constructor <init>()V
    .registers 2

    .line 8
    invoke-direct {p0}, Landroid/support/constraint/solver/widgets/ConstraintWidget;-><init>()V

    .line 9
    const/4 v0, 0x4

    new-array v0, v0, [Landroid/support/constraint/solver/widgets/ConstraintWidget;

    iput-object v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

    .line 10
    const/4 v0, 0x0

    iput v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgetsCount:I

    return-void
.end method

# virtual methods
.method public add(Landroid/support/constraint/solver/widgets/ConstraintWidget;)V
    .registers 4
    .param p1, "widget"    # Landroid/support/constraint/solver/widgets/ConstraintWidget;

    .line 18
    iget v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgetsCount:I

    add-int/lit8 v0, v0, 0x1

    iget-object v1, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

    array-length v1, v1

    if-le v0, v1, :cond_18

    .line 19
    iget-object v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

    iget-object v1, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

    array-length v1, v1

    mul-int/lit8 v1, v1, 0x2

    invoke-static {v0, v1}, Ljava/util/Arrays;->copyOf([Ljava/lang/Object;I)[Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Landroid/support/constraint/solver/widgets/ConstraintWidget;

    iput-object v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

    .line 21
    :cond_18
    iget-object v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgets:[Landroid/support/constraint/solver/widgets/ConstraintWidget;

    iget v1, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgetsCount:I

    aput-object p1, v0, v1

    .line 22
    iget v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgetsCount:I

    add-int/lit8 v0, v0, 0x1

    iput v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgetsCount:I

    .line 23
    return-void
.end method

.method public removeAllIds()V
    .registers 2

    .line 29
    const/4 v0, 0x0

    iput v0, p0, Landroid/support/constraint/solver/widgets/Helper;->mWidgetsCount:I

    .line 30
    return-void
.end method


text:
class CreateTerm < ActiveRecord::Migration[5.1]
  def change
    create_table :terms do |t|
      t.string  :name
      t.string  :taxonomy
      t.integer :posts_count, default: 0
    end
  end
end


text:
export module a {
    export enum weekend {
        Friday,
        Saturday,
        Sunday
    }
}

export module c {
    export import b = a.weekend;
    export var bVal: b = b.Sunday;
}


text:
package net.mindengine.galen.tests.parser;

import static java.util.Arrays.asList;
import static net.mindengine.galen.specs.page.Locator.css;
import static net.mindengine.galen.specs.page.Locator.id;
import static net.mindengine.galen.specs.page.Locator.xpath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import net.mindengine.galen.parser.GalenPageActionReader;
import net.mindengine.galen.specs.page.Locator;
import net.mindengine.galen.suite.GalenPageAction;
import net.mindengine.galen.suite.actions.*;
import net.mindengine.galen.suite.actions.GalenPageActionWait.UntilType;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class GalenPageActionReaderTest {

    @Test(dataProvider="provideGoodSamples") public void shouldParse_action_successfully(String actionText, GalenPageAction expectedAction) {
        GalenPageAction realAction = GalenPageActionReader.readFrom(actionText);
        assertThat(realAction, is(expectedAction));
    }

    @DataProvider public Object[][] provideGoodSamples() {
        return new Object[][]{
            {"inject javascript.js", new GalenPageActionInjectJavascript("javascript.js")},
            {"inject   /usr/bin/john/scripts/javascript.js", new GalenPageActionInjectJavascript("/usr/bin/john/scripts/javascript.js")},
            {"inject   \"/usr/bin/john/scripts/javascript.js\"", new GalenPageActionInjectJavascript("/usr/bin/john/scripts/javascript.js")},

            {"run script.js \"{name: 'john'}\"", new GalenPageActionRunJavascript("script.js").withJsonArguments("{name: 'john'}")},
            {"run script.js \"\"", new GalenPageActionRunJavascript("script.js").withJsonArguments("")},
            {"run script.js \"\\\"john\\\"", new GalenPageActionRunJavascript("script.js").withJsonArguments("\"john\"")},
            {"run script.js", new GalenPageActionRunJavascript("script.js").withJsonArguments(null)},

            {"check page1.spec", new GalenPageActionCheck().withSpecs(asList("page1.spec"))},
            {"check page1.spec --include mobile --exclude debug", new GalenPageActionCheck()
                .withSpecs(asList("page1.spec"))
                .withIncludedTags(asList("mobile"))
                .withExcludedTags(asList("debug"))},
            {"check page1.spec --include mobile,tablet --exclude nomobile,debug", new GalenPageActionCheck()
                .withSpecs(asList("page1.spec"))
                .withIncludedTags(asList("mobile", "tablet"))
                .withExcludedTags(asList("nomobile", "debug"))},
            {"check page1.spec page2.spec page3.spec --include mobile,tablet --exclude nomobile,debug", new GalenPageActionCheck()
                .withSpecs(asList("page1.spec", "page2.spec", "page3.spec"))
                .withIncludedTags(asList("mobile", "tablet"))
                .withExcludedTags(asList("nomobile", "debug"))},
            {"cookie \"somecookie1\" \"somecookie2\" \"somecookie3\"", new GalenPageActionCookie().withCookies("somecookie1", "somecookie2", "somecookie3")},
            {"cookie \"somecookie1\"", new GalenPageActionCookie().withCookies("somecookie1")},
            {"wait 10s", new GalenPageActionWait().withTimeout(10000)},
            {"wait 2m", new GalenPageActionWait().withTimeout(120000)},
            {"wait 10s until visible \"css: div.list\" \"xpath: //div[@id='qwe']\"", new GalenPageActionWait()
                .withTimeout(10000)
                .withUntilElements(asList(visible(css("div.list")), visible(xpath("//div[@id='qwe']"))))},
            {"wait 10s until hidden \"css: div.list\" \"xpath: //div[@id='qwe']\"", new GalenPageActionWait()
                .withTimeout(10000)
                .withUntilElements(asList(hidden(css("div.list")), hidden(xpath("//div[@id='qwe']"))))},
            {"wait 10s until gone \"id: login\" \"xpath: //div[@id='qwe']\"", new GalenPageActionWait()
                .withTimeout(10000)
                .withUntilElements(asList(gone(id("login")), gone(xpath("//div[@id='qwe']"))))},
            {"wait 10s until exist \"id: login\" gone \"xpath: //div[@id='qwe']\"", new GalenPageActionWait()
                .withTimeout(10000)
                .withUntilElements(asList(exist(id("login")), gone(xpath("//div[@id='qwe']"))))},
            {"properties \"some-path-1/file.properties\" file2.properties", new GalenPageActionProperties()
                .withFiles(asList("some-path-1/file.properties", "file2.properties"))
            },
            {"dump page1.spec --name \"Home page dump\" --export /export/dir/path", new GalenPageActionDumpPage()
                .withSpecPath("page1.spec").withPageName("Home page dump").withPageDumpPath("/export/dir/path")
            },
            {"dump page1.spec --name \"Home page dump\" --export /export/dir/path --max-width 120 --max-height 240", new GalenPageActionDumpPage()
                .withSpecPath("page1.spec").withPageName("Home page dump").withPageDumpPath("/export/dir/path").withMaxWidth(120).withMaxHeight(240)
            }
        };
    }

    private static GalenPageActionWait.Until visible(Locator locator) {
        return new GalenPageActionWait.Until(UntilType.VISIBLE, locator);
    }

    private static GalenPageActionWait.Until hidden(Locator locator) {
        return new GalenPageActionWait.Until(UntilType.HIDDEN, locator);
    }

    private static GalenPageActionWait.Until exist(Locator locator) {
        return new GalenPageActionWait.Until(UntilType.EXIST, locator);
    }

    private static GalenPageActionWait.Until gone(Locator locator) {
        return new GalenPageActionWait.Until(UntilType.GONE, locator);
    }

    //TODO negative tests for action parser
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Thyrea plectopsora A. Massal.

### Remarks
null


text:
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.download;

import androidx.test.filters.SmallTest;

import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.chromium.base.test.util.Batch;
import org.chromium.base.test.util.Criteria;
import org.chromium.base.test.util.CriteriaHelper;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.test.ChromeBrowserTestRule;
import org.chromium.chrome.test.ChromeJUnit4ClassRunner;
import org.chromium.chrome.test.util.browser.Features;
import org.chromium.components.offline_items_collection.LegacyHelpers;
import org.chromium.components.offline_items_collection.OfflineItem;
import org.chromium.components.offline_items_collection.OfflineItemSchedule;
import org.chromium.components.offline_items_collection.OfflineItemState;
import org.chromium.content_public.browser.test.util.TestThreadUtils;

import java.util.UUID;

/**
 * Test class to validate that the {@link DownloadInfoBarController} correctly represents the state
 * of the downloads in the current chrome session.
 */
@RunWith(ChromeJUnit4ClassRunner.class)
@Features.EnableFeatures(ChromeFeatureList.DOWNLOAD_PROGRESS_INFOBAR)
@Features.DisableFeatures(ChromeFeatureList.DOWNLOAD_PROGRESS_MESSAGE)
@Batch(Batch.PER_CLASS)
public class DownloadInfoBarControllerTest {
    @Rule
    public final ChromeBrowserTestRule mBrowserTestRule = new ChromeBrowserTestRule();

    private static final String MESSAGE_SPEEDING_UP = "Speeding up your download.";
    private static final String MESSAGE_DOWNLOADING_FILE = "Downloading file.";
    private static final String MESSAGE_DOWNLOADING_TWO_FILES = "Downloading 2 files.";
    private static final String MESSAGE_TWO_DOWNLOAD_COMPLETE = "2 downloads complete.";
    private static final String MESSAGE_DOWNLOAD_FAILED = "1 download failed.";
    private static final String MESSAGE_TWO_DOWNLOAD_FAILED = "2 downloads failed.";
    private static final String MESSAGE_DOWNLOAD_PENDING = "1 download pending.";
    private static final String MESSAGE_TWO_DOWNLOAD_PENDING = "2 downloads pending.";
    private static final String MESSAGE_DOWNLOAD_SCHEDULED_WIFI =
            "You'll see a notification when this download starts on Wi-Fi.";
    private static final String MESSAGE_TWO_DOWNLOAD_SCHEDULED = "2 downloads scheduled.";

    private static final String TEST_FILE_NAME = "TestFile";
    private static final String MESSAGE_SINGLE_DOWNLOAD_COMPLETE = "TestFile.";
    private static final long TEST_TO_NEXT_STEP_DELAY = 100;

    private TestDownloadInfoBarController mTestController;

    @Before
    public void before() {
        TestThreadUtils.runOnUiThreadBlocking(
                () -> { mTestController = new TestDownloadInfoBarController(); });
    }

    static class TestDownloadInfoBarController extends DownloadInfoBarController {
        private DownloadProgressInfoBarData mInfo;

        public TestDownloadInfoBarController() {
            super(/*otrProfileID=*/null);
        }

        @Override
        protected void showInfoBar(
                @DownloadInfoBarState int state, DownloadProgressInfoBarData info) {
            mInfo = info;
            super.showInfoBar(state, info);
        }

        @Override
        protected void closePreviousInfoBar() {
            mInfo = null;
            super.closePreviousInfoBar();
        }

        @Override
        protected long getDelayToNextStep(boolean showAccelerating, int resultState) {
            return TEST_TO_NEXT_STEP_DELAY;
        }

        @Override
        protected boolean isSpeedingUpMessageEnabled() {
            return true;
        }

        public void onItemUpdated(OfflineItem item) {
            super.onItemUpdated(item.clone(), null);
        }

        void verify(String message) {
            Assert.assertNotNull(mInfo);
            Assert.assertEquals(message, mInfo.message);
        }

        void verifyInfoBarClosed() {
            Assert.assertNull(mInfo);
        }
    }

    private static DownloadItem createDownloadItem(OfflineItem offlineItem) {
        DownloadInfo downloadInfo = DownloadInfo.fromOfflineItem(offlineItem, null);
        return new DownloadItem(false, downloadInfo);
    }

    private static OfflineItem createOfflineItem(@OfflineItemState int state) {
        OfflineItem item = new OfflineItem();
        String uuid = UUID.randomUUID().toString();
        item.id = LegacyHelpers.buildLegacyContentId(true, uuid);
        item.state = state;
        if (item.state == OfflineItemState.COMPLETE) {
            markItemComplete(item);
        }
        return item;
    }

    private static void markItemComplete(OfflineItem item) {
        item.state = OfflineItemState.COMPLETE;
        item.title = TEST_FILE_NAME;
        item.receivedBytes = 10L;
        item.totalSizeBytes = 10L;
    }

    private void waitForMessage(String message) {
        CriteriaHelper.pollInstrumentationThread(() -> {
            Criteria.checkThat(mTestController.mInfo, Matchers.notNullValue());
            Criteria.checkThat(mTestController.mInfo.message, Matchers.is(message));
        });
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testOfflinePageDownloadStarted() {
        mTestController.onDownloadStarted();
        mTestController.verify(MESSAGE_DOWNLOADING_FILE);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testSingleOfflineItemComplete() {
        OfflineItem item = createOfflineItem(OfflineItemState.IN_PROGRESS);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOADING_FILE);

        markItemComplete(item);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testMultipleOfflineItemComplete() {
        OfflineItem item = createOfflineItem(OfflineItemState.IN_PROGRESS);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOADING_FILE);

        markItemComplete(item);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);

        OfflineItem item2 = createOfflineItem(OfflineItemState.COMPLETE);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_COMPLETE);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testSingleOfflineItemFailed() {
        OfflineItem item = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_FAILED);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testMultipleOfflineItemFailed() {
        OfflineItem item = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_FAILED);

        OfflineItem item2 = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_FAILED);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testSingleOfflineItemPending() {
        OfflineItem item = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testMultipleOfflineItemPending() {
        OfflineItem item = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        OfflineItem item2 = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_PENDING);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testSingleOfflineItemScheduled() {
        OfflineItem item = createOfflineItem(OfflineItemState.PENDING);
        item.schedule = new OfflineItemSchedule(true, 0);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_SCHEDULED_WIFI);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testMultipleOfflineItemScheduled() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.IN_PROGRESS);
        item1.schedule = new OfflineItemSchedule(true, 0);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_DOWNLOAD_SCHEDULED_WIFI);

        OfflineItem item2 = createOfflineItem(OfflineItemState.PENDING);
        item2.schedule = new OfflineItemSchedule(true, 0);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_SCHEDULED);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testNewDownloadShowsUpImmediately() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.COMPLETE);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);

        OfflineItem item2 = createOfflineItem(OfflineItemState.IN_PROGRESS);
        item2.isAccelerated = true;
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_SPEEDING_UP);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testPausedDownloadsAreIgnored() {
        OfflineItem item = createOfflineItem(OfflineItemState.IN_PROGRESS);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOADING_FILE);

        item.state = OfflineItemState.PAUSED;
        mTestController.onItemUpdated(item);
        mTestController.verifyInfoBarClosed();

        item.state = OfflineItemState.IN_PROGRESS;
        mTestController.onItemUpdated(item);
        mTestController.verifyInfoBarClosed();

        markItemComplete(item);
        mTestController.onItemUpdated(item);
        mTestController.verifyInfoBarClosed();
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testOnItemRemoved() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.IN_PROGRESS);
        OfflineItem item2 = createOfflineItem(OfflineItemState.IN_PROGRESS);
        mTestController.onItemUpdated(item1);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_DOWNLOADING_TWO_FILES);

        mTestController.onItemRemoved(item1.id);
        mTestController.verify(MESSAGE_DOWNLOADING_FILE);

        mTestController.onItemRemoved(item2.id);
        mTestController.verifyInfoBarClosed();
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testCancelledItemWillCloseInfoBar() {
        OfflineItem item = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        item.state = OfflineItemState.CANCELLED;
        mTestController.onItemUpdated(item);
        mTestController.verifyInfoBarClosed();
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testCompleteFailedComplete() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.COMPLETE);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);

        OfflineItem item2 = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);

        OfflineItem item3 = createOfflineItem(OfflineItemState.COMPLETE);
        mTestController.onItemUpdated(item3);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_COMPLETE);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testPendingFailedPending() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        OfflineItem item2 = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        OfflineItem item3 = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item3);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_PENDING);

        waitForMessage(MESSAGE_DOWNLOAD_FAILED);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testProgressCompleteFailedProgress() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.IN_PROGRESS);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_DOWNLOADING_FILE);

        OfflineItem item2 = createOfflineItem(OfflineItemState.COMPLETE);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);

        OfflineItem item3 = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item3);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);

        waitForMessage(MESSAGE_DOWNLOAD_FAILED);
        waitForMessage(MESSAGE_DOWNLOADING_FILE);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testCompleteShowsUpImmediately() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.FAILED);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_DOWNLOAD_FAILED);

        OfflineItem item2 = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_DOWNLOAD_FAILED);

        markItemComplete(item2);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_SINGLE_DOWNLOAD_COMPLETE);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testResumeFromPendingShowsUpImmediately() {
        OfflineItem item1 = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        OfflineItem item2 = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_TWO_DOWNLOAD_PENDING);

        item2.state = OfflineItemState.IN_PROGRESS;
        mTestController.onItemUpdated(item2);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        item1.state = OfflineItemState.IN_PROGRESS;
        mTestController.onItemUpdated(item1);
        mTestController.verify(MESSAGE_DOWNLOADING_TWO_FILES);
    }

    @Test
    @SmallTest
    @Feature({"Download"})
    public void testPausedAfterPendingWillCloseInfoBar() {
        OfflineItem item = createOfflineItem(OfflineItemState.PENDING);
        mTestController.onItemUpdated(item);
        mTestController.verify(MESSAGE_DOWNLOAD_PENDING);

        item.state = OfflineItemState.PAUSED;
        mTestController.onItemUpdated(item);
        mTestController.verifyInfoBarClosed();

        item.state = OfflineItemState.IN_PROGRESS;
        mTestController.onItemUpdated(item);
        mTestController.verifyInfoBarClosed();
    }
}


text:
package jGraphs.core;

public class MixedWeightedGraph {

}


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

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <tinyara/config.h>

#include <stdint.h>
#include <signal.h>
#include <queue.h>
#include <sched.h>
#include <errno.h>

#include "sched/sched.h"
#include "group/group.h"
#include "signal/signal.h"

/****************************************************************************
 * Definitions
 ****************************************************************************/

#define COPY_SIGACTION(t, f) \
	{ \
		(t)->sa_sigaction = (f)->sa_sigaction; \
		(t)->sa_mask      = (f)->sa_mask; \
		(t)->sa_flags     = (f)->sa_flags; \
	}

/****************************************************************************
 * Private Type Declarations
 ****************************************************************************/

/****************************************************************************
 * Global Variables
 ****************************************************************************/

/****************************************************************************
 * Private Variables
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: sig_allocateaction
 *
 * Description:
 *   Allocate a new element for a sigaction queue
 *
 ****************************************************************************/

static FAR sigactq_t *sig_allocateaction(void)
{
	FAR sigactq_t *sigact;

	/* Try to get the signal action structure from the free list */

	sigact = (FAR sigactq_t *)sq_remfirst(&g_sigfreeaction);

	/* Check if we got one. */

	if (!sigact) {
		/* Add another block of signal actions to the list */

		sig_allocateactionblock();

		/* And try again */

		sigact = (FAR sigactq_t *)sq_remfirst(&g_sigfreeaction);
		ASSERT(sigact);
	}

	return sigact;
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: sigaction
 *
 * Description:
 *   This function allows the calling process to examine and/or specify the
 *   action to be associated with a specific signal.
 *
 *   The structure sigaction, used to describe an action to be taken, is
 *   defined to include the following members:
 *
 *   - sa_u.sa_handler:  Pointer to a signal-catching function
 *   - sa_u.sa_sigaction:  Alternative form of the signal-catching function
 *   - sa_mask: An additional set of signals to be blocked during execution
 *       of a signal catching function
 *   - sa_flags.  Special flags to affect the behavior of a signal.
 *
 *   If the argument 'act' is not NULL, it points to a structure specifying
 *   the action to be associated with the specified signal.  If the argument
 *   'oact' is not NULL, the action previously associated with the signal
 *   is stored in the location pointed to by the argument 'oact.'
 *
 *   When a signal is caught by a signal-catching function installed by
 *   sigaction() function, a new signal mask is calculated and installed for
 *   the duration of the signal-catching function.  This mask is formed by
 *   taking the union of the current signal mask and the value of the
 *   sa_mask for the signal being delivered and then including the signal
 *   being delivered.  If and when the user's signal handler returns, the
 *   original signal mask is restored.
 *
 *   Once an action is installed for a specific signal, it remains installed
 *   until another action is explicitly requested by another call to sigaction().
 *
 * Parameters:
 *   sig - Signal of interest
 *   act - Location of new handler
 *   oact - Location to store only handler
 *
 * Return Value:
 *   0 (OK), or -1 (ERROR) if the signal number is invalid.
 *   (errno is not set)
 *
 * Assumptions:
 *
 * POSIX Compatibility:
 * - There are no default actions so the special value SIG_DFL is treated
 *   like SIG_IGN.
 * - All sa_flags in struct sigaction of act input are ignored (all
 *   treated like SA_SIGINFO). The one exception is if CONFIG_SCHED_CHILDSTATUS
 *   is defined; then SA_NOCLDWAIT is supported but only for SIGCHLD
 *
 ****************************************************************************/

int sigaction(int signo, FAR const struct sigaction *act, FAR struct sigaction *oact)
{
	FAR struct tcb_s *rtcb = this_task();
	FAR sigactq_t *sigact;

	/* Since sigactions can only be installed from the running thread of
	 * execution, no special precautions should be necessary.
	 */

	/* Verify the signal number */

	if (!GOOD_SIGNO(signo)) {
		set_errno(EINVAL);
		return ERROR;
	}

	/* Find the signal in the sigactionq */

	sigact = sig_findaction(rtcb, signo);

	/* Return the old sigaction value if so requested */

	if (oact) {
		if (sigact) {
			COPY_SIGACTION(oact, &sigact->act);
		} else {
			/* There isn't an old value */

			oact->sa_u._sa_handler = NULL;
			oact->sa_mask = NULL_SIGNAL_SET;
			oact->sa_flags = 0;
		}
	}

	/* If the argument act is a null pointer, signal handling is unchanged;
	 * thus, the call can be used to enquire about the current handling of
	 * a given signal.
	 */

	if (!act) {
		return OK;
	}
#if defined(CONFIG_SCHED_HAVE_PARENT) && defined(CONFIG_SCHED_CHILD_STATUS)

	/* Handle a special case.  Retention of child status can be suppressed
	 * if signo == SIGCHLD and sa_flags == SA_NOCLDWAIT.
	 *
	 * POSIX.1 leaves it unspecified whether a SIGCHLD signal is generated
	 * when a child process terminates.  In TinyAra, a SIGCHLD signal is
	 * generated in this case; but in some other implementations, it may not
	 * be.
	 */

	if (signo == SIGCHLD && (act->sa_flags & SA_NOCLDWAIT) != 0) {
		irqstate_t flags;

		/* We do require a critical section to muck with the TCB values that
		 * can be modified by the child thread.
		 */

		flags = irqsave();

		/* Mark that status should be not be retained */

		rtcb->group->tg_flags |= GROUP_FLAG_NOCLDWAIT;

		/* Free all pending exit status */

		group_removechildren(rtcb->group);
		irqrestore(flags);
	}
#endif

	/* Handle the case where no sigaction is supplied (SIG_IGN) */

	if (act->sa_u._sa_handler == SIG_IGN) {
		/* Do we still have a sigaction container from the previous setting? */

		if (sigact) {
			/* Yes.. Remove it from sigactionq */

			sq_rem((FAR sq_entry_t *)sigact, &rtcb->sigactionq);

			/* And deallocate it */

			sig_releaseaction(sigact);
		}
	}

	/* A sigaction has been supplied */

	else {
		/* Do we still have a sigaction container from the previous setting?
		 * If so, then re-use for the new signal action.
		 */

		if (!sigact) {
			/* No.. Then we need to allocate one for the new action. */

			sigact = sig_allocateaction();

			/* An error has occurred if we could not allocate the sigaction */

			if (!sigact) {
				set_errno(ENOMEM);
				return ERROR;
			}

			/* Put the signal number in the queue entry */

			sigact->signo = (uint8_t)signo;

			/* Add the new sigaction to sigactionq */

			sq_addlast((FAR sq_entry_t *)sigact, &rtcb->sigactionq);
		}

		/* Set the new sigaction */

		COPY_SIGACTION(&sigact->act, act);
	}

	return OK;
}

/****************************************************************************
 * Name: sig_releaseaction
 *
 * Description:
 *   Deallocate a sigaction Q entry
 *
 ****************************************************************************/

void sig_releaseaction(FAR sigactq_t *sigact)
{
	/* Just put it back on the free list */

	sq_addlast((FAR sq_entry_t *)sigact, &g_sigfreeaction);
}


text:
import six
from tempest_lib import exceptions as lib_exc

from tempest.api.baremetal.admin import base
from tempest.common.utils import data_utils
from tempest import test

class TestPorts(base.BaseBaremetalTest):
    """Tests for ports."""

    def setUp(self):
        super(TestPorts, self).setUp()

        _, self.chassis = self.create_chassis()
        _, self.node = self.create_node(self.chassis['uuid'])
        _, self.port = self.create_port(self.node['uuid'],
                                        data_utils.rand_mac_address())

    def _assertExpected(self, expected, actual):
        # Check if not expected keys/values exists in actual response body
        for key, value in six.iteritems(expected):
            if key not in ('created_at', 'updated_at'):
                self.assertIn(key, actual)
                self.assertEqual(value, actual[key])

    @test.idempotent_id('83975898-2e50-42ed-b5f0-e510e36a0b56')
    def test_create_port(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()

        _, port = self.create_port(node_id=node_id, address=address)

        _, body = self.client.show_port(port['uuid'])

        self._assertExpected(port, body)

    @test.idempotent_id('d1f6b249-4cf6-4fe6-9ed6-a6e84b1bf67b')
    def test_create_port_specifying_uuid(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        uuid = data_utils.rand_uuid()

        _, port = self.create_port(node_id=node_id,
                                   address=address, uuid=uuid)

        _, body = self.client.show_port(uuid)
        self._assertExpected(port, body)

    @test.idempotent_id('4a02c4b0-6573-42a4-a513-2e36ad485b62')
    def test_create_port_with_extra(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        extra = {'str': 'value', 'int': 123, 'float': 0.123,
                 'bool': True, 'list': [1, 2, 3], 'dict': {'foo': 'bar'}}

        _, port = self.create_port(node_id=node_id, address=address,
                                   extra=extra)

        _, body = self.client.show_port(port['uuid'])
        self._assertExpected(port, body)

    @test.idempotent_id('1bf257a9-aea3-494e-89c0-63f657ab4fdd')
    def test_delete_port(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        _, port = self.create_port(node_id=node_id, address=address)

        self.delete_port(port['uuid'])

        self.assertRaises(lib_exc.NotFound, self.client.show_port,
                          port['uuid'])

    @test.idempotent_id('9fa77ab5-ce59-4f05-baac-148904ba1597')
    def test_show_port(self):
        _, port = self.client.show_port(self.port['uuid'])
        self._assertExpected(self.port, port)

    @test.idempotent_id('7c1114ff-fc3f-47bb-bc2f-68f61620ba8b')
    def test_show_port_by_address(self):
        _, port = self.client.show_port_by_address(self.port['address'])
        self._assertExpected(self.port, port['ports'][0])

    @test.idempotent_id('bd773405-aea5-465d-b576-0ab1780069e5')
    def test_show_port_with_links(self):
        _, port = self.client.show_port(self.port['uuid'])
        self.assertIn('links', port.keys())
        self.assertEqual(2, len(port['links']))
        self.assertIn(port['uuid'], port['links'][0]['href'])

    @test.idempotent_id('b5e91854-5cd7-4a8e-bb35-3e0a1314606d')
    def test_list_ports(self):
        _, body = self.client.list_ports()
        self.assertIn(self.port['uuid'],
                      [i['uuid'] for i in body['ports']])
        # Verify self links.
        for port in body['ports']:
            self.validate_self_link('ports', port['uuid'],
                                    port['links'][0]['href'])

    @test.idempotent_id('324a910e-2f80-4258-9087-062b5ae06240')
    def test_list_with_limit(self):
        _, body = self.client.list_ports(limit=3)

        next_marker = body['ports'][-1]['uuid']
        self.assertIn(next_marker, body['next'])

    @test.idempotent_id('8a94b50f-9895-4a63-a574-7ecff86e5875')
    def test_list_ports_details(self):
        node_id = self.node['uuid']

        uuids = [
            self.create_port(node_id=node_id,
                             address=data_utils.rand_mac_address())
            [1]['uuid'] for i in range(0, 5)]

        _, body = self.client.list_ports_detail()

        ports_dict = dict((port['uuid'], port) for port in body['ports']
                          if port['uuid'] in uuids)

        for uuid in uuids:
            self.assertIn(uuid, ports_dict)
            port = ports_dict[uuid]
            self.assertIn('extra', port)
            self.assertIn('node_uuid', port)
            # never expose the node_id
            self.assertNotIn('node_id', port)
            # Verify self link.
            self.validate_self_link('ports', port['uuid'],
                                    port['links'][0]['href'])

    @test.idempotent_id('8a03f688-7d75-4ecd-8cbc-e06b8f346738')
    def test_list_ports_details_with_address(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        self.create_port(node_id=node_id, address=address)
        for i in range(0, 5):
            self.create_port(node_id=node_id,
                             address=data_utils.rand_mac_address())

        _, body = self.client.list_ports_detail(address=address)
        self.assertEqual(1, len(body['ports']))
        self.assertEqual(address, body['ports'][0]['address'])

    @test.idempotent_id('9c26298b-1bcb-47b7-9b9e-8bdd6e3c4aba')
    def test_update_port_replace(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        extra = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

        _, port = self.create_port(node_id=node_id, address=address,
                                   extra=extra)

        new_address = data_utils.rand_mac_address()
        new_extra = {'key1': 'new-value1', 'key2': 'new-value2',
                     'key3': 'new-value3'}

        patch = [{'path': '/address',
                  'op': 'replace',
                  'value': new_address},
                 {'path': '/extra/key1',
                  'op': 'replace',
                  'value': new_extra['key1']},
                 {'path': '/extra/key2',
                  'op': 'replace',
                  'value': new_extra['key2']},
                 {'path': '/extra/key3',
                  'op': 'replace',
                  'value': new_extra['key3']}]

        self.client.update_port(port['uuid'], patch)

        _, body = self.client.show_port(port['uuid'])
        self.assertEqual(new_address, body['address'])
        self.assertEqual(new_extra, body['extra'])

    @test.idempotent_id('d7e7fece-6ed9-460a-9ebe-9267217e8580')
    def test_update_port_remove(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        extra = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

        _, port = self.create_port(node_id=node_id, address=address,
                                   extra=extra)

        # Removing one item from the collection
        self.client.update_port(port['uuid'],
                                [{'path': '/extra/key2',
                                 'op': 'remove'}])
        extra.pop('key2')
        _, body = self.client.show_port(port['uuid'])
        self.assertEqual(extra, body['extra'])

        # Removing the collection
        self.client.update_port(port['uuid'], [{'path': '/extra',
                                               'op': 'remove'}])
        _, body = self.client.show_port(port['uuid'])
        self.assertEqual({}, body['extra'])

        # Assert nothing else was changed
        self.assertEqual(node_id, body['node_uuid'])
        self.assertEqual(address, body['address'])

    @test.idempotent_id('241288b3-e98a-400f-a4d7-d1f716146361')
    def test_update_port_add(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()

        _, port = self.create_port(node_id=node_id, address=address)

        extra = {'key1': 'value1', 'key2': 'value2'}

        patch = [{'path': '/extra/key1',
                  'op': 'add',
                  'value': extra['key1']},
                 {'path': '/extra/key2',
                  'op': 'add',
                  'value': extra['key2']}]

        self.client.update_port(port['uuid'], patch)

        _, body = self.client.show_port(port['uuid'])
        self.assertEqual(extra, body['extra'])

    @test.idempotent_id('5309e897-0799-4649-a982-0179b04c3876')
    def test_update_port_mixed_ops(self):
        node_id = self.node['uuid']
        address = data_utils.rand_mac_address()
        extra = {'key1': 'value1', 'key2': 'value2'}

        _, port = self.create_port(node_id=node_id, address=address,
                                   extra=extra)

        new_address = data_utils.rand_mac_address()
        new_extra = {'key1': 0.123, 'key3': {'cat': 'meow'}}

        patch = [{'path': '/address',
                  'op': 'replace',
                  'value': new_address},
                 {'path': '/extra/key1',
                  'op': 'replace',
                  'value': new_extra['key1']},
                 {'path': '/extra/key2',
                  'op': 'remove'},
                 {'path': '/extra/key3',
                  'op': 'add',
                  'value': new_extra['key3']}]

        self.client.update_port(port['uuid'], patch)

        _, body = self.client.show_port(port['uuid'])
        self.assertEqual(new_address, body['address'])
        self.assertEqual(new_extra, body['extra'])


text:
module PackageReport
  VERSION = "0.0.5"
end


text:
namespace TABS_UserControls.usercontrols {

    public partial class recentlyviewed {

        /// <summary>
        /// check_1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox check_1;

        /// <summary>
        /// check_2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox check_2;

        /// <summary>
        /// check_3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox check_3;

        /// <summary>
        /// check_4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox check_4;

        /// <summary>
        /// check_5 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox check_5;

        /// <summary>
        /// buttonCompare control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ImageButton buttonCompare;
    }
}


text:
using UIKit;
using Foundation;

namespace MetalPerformanceShadersHelloWorld {

	[Register ("AppDelegate")]
	public class AppDelegate : UIApplicationDelegate {

		public override UIWindow Window {
			get;
			set;
		}

		// There is no need for a FinishedLaunching method here as the
		// Main.storyboard is automagically loaded since it is specified
		// in the Info.plist -> <key>UIMainStoryboardFile~ipad</key>
    }
}


text:
import unittest
import sys
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)

from back.console import Console

class BluePTest(unittest.TestCase):

    def test_console(self):
        console = Console(sys.stdout, sys.stderr, './')
        self.assertNotEqual(console, None)

        console.eval_command("TEST_VAR=\"TEST_VALUE\"")
        print_result = console.eval_command("print(TEST_VAR)")
        self.assertEqual("TEST_VALUE\n", print_result)

        console.eval_command("from front.edge import Edge")
        console.eval_command("test_edge = Edge(None, None)")

        console.refresh_instance_list()
        self.assertEqual(True, "Edge" in console.instances)

        console.flush_console()
        self.assertEqual(False, "Edge" in console.instances)

if __name__ == '__main__':
    unittest.main()


text:
using System.Threading.Tasks;
using ITLibrium.Hexagon.App.Queries;

namespace ITLibrium.Hexagon.App.Decorators
{
    public abstract class FinderDecorator<TResult> : IFinder<TResult>, IDecorator
    {
        protected abstract ExecutionOrder ExecutionOrder { get; }

        private readonly IFinder<TResult> _decorated;
        object IDecorator.Decorated => _decorated;

        protected FinderDecorator(IFinder<TResult> decorated)
        {
            _decorated = decorated;
        }

        public Task<TResult> FindAsync()
        {
            return DecoratorExctensions.Execute(ExecutionOrder, _decorated.FindAsync, DecorateAsync);
        }

        protected abstract Task DecorateAsync();
    }

    public abstract class FinderDecorator<TResult, TCriteria> : IFinder<TResult, TCriteria>, IDecorator
    {
        protected abstract ExecutionOrder ExecutionOrder { get; }

        private readonly IFinder<TResult, TCriteria> _decorated;
        object IDecorator.Decorated => _decorated;

        protected FinderDecorator(IFinder<TResult, TCriteria> decorated)
        {
            _decorated = decorated;
        }

        public Task<TResult> FindAsync(TCriteria criteria)
        {
            return DecoratorExctensions.Execute(criteria, ExecutionOrder, _decorated.FindAsync, DecorateAsync);
        }

        protected abstract Task DecorateAsync(TCriteria criteria);
    }
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['addmoredimensions'] = 'Espacios en blanco para {$a} afirmaciones más';
$string['configgrade0'] = 'Palabra por defecto que describe la evaluación negativa de una afirmación.';
$string['configgrade1'] = 'Palabra por defecto que describe la evaluación positiva de una afirmación.';
$string['dimensioncomment'] = 'Comentario';
$string['dimensiondescription'] = 'Descripción';
$string['dimensiongrade'] = 'Calificación';
$string['dimensionnumber'] = 'Afirmación {$a}';
$string['dimensionweight'] = 'Ponderación';
$string['grade0'] = 'Palabra para el error';
$string['grade0default'] = 'No';
$string['grade1'] = 'Palabra para el éxito';
$string['grade1default'] = 'Sí';
$string['grademapping'] = 'Tabla de mapeo de calificaciones';
$string['maperror'] = 'El número ponderado de errores es menor o igual';
$string['mapgrade'] = 'Calificación del envío';
$string['percents'] = '{$a} %';
$string['pluginname'] = 'Número de errores';


text:
import java.util.concurrent.TimeUnit;

public class StopWatch {
    long elapsed;
    long startTime;

    public void start() {
        this.startTime = System.nanoTime();
    }

    public void reset() {
        this.elapsed = 0;
        this.startTime = -1;
    }

    public void stop() {
        if(startTime < 0) {
            throw new RuntimeException("Stop watch must be started first!");
        }
        elapsed = System.nanoTime() - startTime;
    }

    public long getTimeInMillis() {
        return TimeUnit.NANOSECONDS.toMillis(elapsed);
    }

    public long getTimeInNanos() {
        return elapsed;
    }
}


text:
#ifndef LIEF_MACHO_EXPORTS_TRIE_H
#define LIEF_MACHO_EXPORTS_TRIE_H
#include <iostream>
#include <vector>
#include <string>
#include <memory>

namespace LIEF {
class BinaryStream;
namespace MachO {
class ExportInfo;
using exports_list_t = std::vector<std::unique_ptr<ExportInfo>>;
void show_trie(std::ostream& output, std::string output_prefix,
               BinaryStream& stream, uint64_t start, uint64_t end, const std::string& prefix);

std::vector<uint8_t> create_trie(const exports_list_t& exports, size_t pointer_size);
}
}
#endif


text:
package org.apache.samoa.core;

import java.io.Serializable;

import com.github.javacliparser.Configurable;

/**
 * An EntranceProcessor is a specific kind of processor dedicated to providing events to inject in the topology. It can
 * be connected to a single output stream.
 */
public interface EntranceProcessor extends Serializable, Configurable, Processor {

  /**
   * Initializes the Processor. This method is called once after the topology is set up and before any call to the
   * {@link nextTuple} method.
   *
   * @param the
   *          identifier of the processor.
   */
  public void onCreate(int id);

  /**
   * Checks whether the source stream is finished/exhausted.
   */
  public boolean isFinished();

  /**
   * Checks whether a new event is ready to be processed.
   *
   * @return true if the EntranceProcessor is ready to provide the next event, false otherwise.
   */
  public boolean hasNext();

  /**
   * Provides the next tuple to be processed by the topology. This method is the entry point for external events into
   * the topology.
   *
   * @return the next event to be processed.
   */
  public ContentEvent nextEvent();

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">

    <!-- 지식정보제공/지식정보요청 -->
    <bean name="egovRequestOfferIdGnrService" class="egovframework.rte.fdl.idgnr.impl.EgovTableIdGnrServiceImpl" destroy-method="destroy">
        <property name="dataSource" ref="egov.dataSource" />
        <property name="strategy"   ref="egovRequestOfferIdMsgtrategy" />
        <property name="blockSize"  value="10"/>
        <property name="table"      value="COMTECOPSEQ"/>
        <property name="tableName"  value="KNO_ID2"/>
    </bean>
    <bean name="egovRequestOfferIdMsgtrategy" class="egovframework.rte.fdl.idgnr.impl.strategy.EgovIdGnrStrategyImpl">
        <property name="prefix"   value="KNO_ID2" />
        <property name="cipers"   value="13" />
        <property name="fillChar" value="0" />
    </bean>

</beans>


text:
package org.typemeta.funcj.codec.bytes.io;

import org.typemeta.funcj.codec.bytes.ByteTypes;
import org.typemeta.funcj.codec.utils.CodecException;

import java.io.*;

public final class OutputImpl implements ByteTypes.OutStream {
    private final DataOutput output;

    public OutputImpl(DataOutput output) {
        this.output = output;
    }

    @Override
    public void close() {
    }

    @Override
    public OutputImpl writeBoolean(boolean v) {
        try {
            output.writeBoolean(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeByte(byte v) {
        try {
            output.writeByte(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeChar(char v) {
        try {
            output.writeChar(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeShort(short v) {
        try {
            output.writeShort(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeInt(int v) {
        try {
            output.writeInt(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeLong(long v) {
        try {
            output.writeLong(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeFloat(float v) {
        try {
            output.writeFloat(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeDouble(double v) {
        try {
            output.writeDouble(v);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }

    @Override
    public OutputImpl writeString(String s) {
        try {
            output.writeInt(s.length());
            output.writeChars(s);
            return this;
        } catch (IOException ex) {
            throw new CodecException(ex);
        }
    }
}


text:
namespace Microsoft.Graph
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;

    /// <summary>
    /// The type GeoCoordinates.
    /// </summary>
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    [JsonConverter(typeof(DerivedTypeConverter))]
    public partial class GeoCoordinates
    {

        /// <summary>
        /// Gets or sets altitude.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "altitude", Required = Required.Default)]
        public double? Altitude { get; set; }

        /// <summary>
        /// Gets or sets latitude.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "latitude", Required = Required.Default)]
        public double? Latitude { get; set; }

        /// <summary>
        /// Gets or sets longitude.
        /// </summary>
        [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "longitude", Required = Required.Default)]
        public double? Longitude { get; set; }

        /// <summary>
        /// Gets or sets additional data.
        /// </summary>
        [JsonExtensionData(ReadData = true)]
        public IDictionary<string, object> AdditionalData { get; set; }

    }
}


text:
using System;
using Csla;
using MyVote.BusinessObjects.Contracts;
using MyVote.BusinessObjects.Core;
using MyVote.BusinessObjects.Attributes;

#if !NETFX_CORE && !MOBILE
using System.Collections.Generic;
using System.Linq;
using MyVote.Data.Entities;
#endif

namespace MyVote.BusinessObjects
{
	[System.Serializable]
	internal sealed class PollComment
		: BusinessBaseScopeCore<PollComment>, IPollComment
	{
		[RunLocal]
		private void Child_Create(int userId, string userName)
		{
			this.UserID = userId;
			this.UserName = userName;
			this.CommentDate = DateTime.UtcNow;
			this.Comments = this.pollCommentsFactory.CreateChild();
		}

#if !NETFX_CORE && !MOBILE
        private void Child_Fetch(PollCommentData commentData, List<PollCommentData> commentsData)
		{
			using (this.BypassPropertyChecks)
			{
				var comment = commentData.Comment;
				this.CommentDate = comment.CommentDate;
				this.CommentText = comment.CommentText;
				this.PollCommentID = comment.PollCommentID;
				this.UserID = comment.UserID;
				this.UserName = commentData.UserName;
				this.Comments = this.pollCommentsFactory.FetchChild();

				foreach (var childComment in
					(from c in commentsData
					 where c.Comment.ParentCommentID == comment.PollCommentID
					 select c).ToList())
				{
					this.Comments.Add(this.pollCommentFactory.FetchChild(childComment, commentsData));
				}
			}
		}

		private void Child_Insert(int pollId, int? parentCommentId)
		{
			var entity = new MVPollComment();
			entity.CommentDate = this.CommentDate;
			entity.CommentText = this.CommentText;
			entity.ParentCommentID = parentCommentId;
			entity.PollID = pollId;
			entity.UserID = this.UserID;

			this.Entities.MVPollComments.Add(entity);
			this.Entities.SaveChanges();
			this.PollCommentID = entity.PollCommentID;

			this.FieldManager.UpdateChildren(pollId, this.PollCommentID);
		}

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "parentCommentId")]
		private void Child_Update(int pollId, int? parentCommentId)
		{
			this.FieldManager.UpdateChildren(pollId, this.PollCommentID);
		}
#endif

		public static PropertyInfo<DateTime?> CommentDateProperty =
			PollComment.RegisterProperty<DateTime?>(_ => _.CommentDate);
		public DateTime? CommentDate
		{
			get { return this.ReadProperty(PollComment.CommentDateProperty); }
			private set { this.LoadProperty(PollComment.CommentDateProperty, value); }
		}

		public static PropertyInfo<IPollCommentCollection> CommentsProperty =
			PollComment.RegisterProperty<IPollCommentCollection>(_ => _.Comments);
		public IPollCommentCollection Comments
		{
			get { return this.ReadProperty(PollComment.CommentsProperty); }
			private set { this.LoadProperty(PollComment.CommentsProperty, value); }
		}

		public static PropertyInfo<string> CommentTextProperty =
			PollComment.RegisterProperty<string>(_ => _.CommentText);
		public string CommentText
		{
			get { return this.GetProperty(PollComment.CommentTextProperty); }
			set { this.SetProperty(PollComment.CommentTextProperty, value); }
		}

		public static PropertyInfo<int?> PollCommentIDProperty =
			PollComment.RegisterProperty<int?>(_ => _.PollCommentID);
		public int? PollCommentID
		{
			get { return this.ReadProperty(PollComment.PollCommentIDProperty); }
			private set { this.LoadProperty(PollComment.PollCommentIDProperty, value); }
		}

		public static PropertyInfo<int> UserIDProperty =
			PollComment.RegisterProperty<int>(_ => _.UserID);
		public int UserID
		{
			get { return this.ReadProperty(PollComment.UserIDProperty); }
			private set { this.LoadProperty(PollComment.UserIDProperty, value); }
		}

		public static readonly PropertyInfo<string> UserNameProperty =
			PollComment.RegisterProperty<string>(_ => _.UserName);
		public string UserName
		{
			get { return this.ReadProperty(PollComment.UserNameProperty); }
			private set { this.LoadProperty(PollComment.UserNameProperty, value); }
		}

#if !NETFX_CORE && !MOBILE
        [NonSerialized]
#endif
		private IObjectFactory<IPollCommentCollection> pollCommentsFactory;
		[Dependency]
		public IObjectFactory<IPollCommentCollection> PollCommentsFactory
		{
			get { return this.pollCommentsFactory; }
			set { this.pollCommentsFactory = value; }
		}

#if !NETFX_CORE && !MOBILE
        [NonSerialized]
		private IObjectFactory<IPollComment> pollCommentFactory;
		[Dependency]
		public IObjectFactory<IPollComment> PollCommentFactory
		{
			get { return this.pollCommentFactory; }
			set { this.pollCommentFactory = value; }
		}
#endif
	}
}


text:
mongo-supervisor
================

mongo-supervisor aims at providing a simple but flexible supervisor for Docker containers running mongodb.

It runs mongodb, and provides a rest api that can be called from any http client, for instance with basic curl,
to start/stop mongo, create a backup with mongodump, and restore a backup with mongorestore.

Building
========

a build.js script file provides several targets:

- package: copies a minimal version of mongo-supervisor in a directory, along with its start script. You may find it
useful to copy it in your own container.

- docker-create: creates a docker image based on the docker/Dockerfile recipe. It uses the default mongodb configuration
 file, so you may want to tune that part.

- docker-run: creates a docker image, and run it. The docker container is temporary, as soon as the script ends, it is
killed and removed.

Possible options:
 --open-api -O : Open rest api (no security check) [docker]
 --sec-headers -h HEAD:VALUE : define security header and value [docker]
 --tag -t tag : user this tag as the image name [docker]
 --sudo-docker -s : docker needs to be run with sudo [docker]
 --location -l : directory where to create the package [package only]

Example:

* node build docker-run -O
 creates and runs a docker container with mongo-supervisor, until you ctrl-c.

Security
========
The security can be configured in the configuration file (namely mongosupervisor.yaml) or during the build.
The security options are:

- open api: just no security at all. The default is no access, so you need to be explicit if you want to make it
 widely open.
 In the build script: use the --open-api or -O flag.
 In the configuration file: change the security part to be
security:
  open: true

- Headers: mongo-supervisors checks that a given http header is provided with a given value. This is typically
useful for clients using a TLS connection.
 In the build script: use the --open-api or -O flag.
 In the configuration file: change the security part to be
```
    security:
        header-key-name: "SomeHeaderName"
        header-key-value: "some secret value"
```

  for instance:
```    security:
        header-key-name: "X-ACCESS"
        header-key-value: "efb92b97a659bf04ac599bac68e36559fec30eafd63381bf19513c82b290c765"
```