text:
module API
  class ProjectPackages < Grape::API::Instance
    include PaginationParams

    before do
      authorize_packages_access!(user_project)
    end

    helpers ::API::Helpers::PackagesHelpers

    params do
      requires :id, type: String, desc: 'The ID of a project'
    end
    resource :projects, requirements: API::NAMESPACE_OR_PROJECT_REQUIREMENTS do
      desc 'Get all project packages' do
        detail 'This feature was introduced in GitLab 11.8'
        success ::API::Entities::Package
      end
      params do
        use :pagination
        optional :order_by, type: String, values: %w[created_at name version type], default: 'created_at',
                            desc: 'Return packages ordered by `created_at`, `name`, `version` or `type` fields.'
        optional :sort, type: String, values: %w[asc desc], default: 'asc',
                        desc: 'Return packages sorted in `asc` or `desc` order.'
        optional :package_type, type: String, values: Packages::Package.package_types.keys,
                                desc: 'Return packages of a certain type'
        optional :package_name, type: String,
                                desc: 'Return packages with this name'
      end
      get ':id/packages' do
        packages = ::Packages::PackagesFinder.new(
          user_project,
          declared_params.slice(:order_by, :sort, :package_type, :package_name)
        ).execute

        present paginate(packages), with: ::API::Entities::Package, user: current_user
      end

      desc 'Get a single project package' do
        detail 'This feature was introduced in GitLab 11.9'
        success ::API::Entities::Package
      end
      params do
        requires :package_id, type: Integer, desc: 'The ID of a package'
      end
      get ':id/packages/:package_id' do
        package = ::Packages::PackageFinder
          .new(user_project, params[:package_id]).execute

        present package, with: ::API::Entities::Package, user: current_user
      end

      desc 'Remove a package' do
        detail 'This feature was introduced in GitLab 11.9'
      end
      params do
        requires :package_id, type: Integer, desc: 'The ID of a package'
      end
      delete ':id/packages/:package_id' do
        authorize_destroy_package!(user_project)

        package = ::Packages::PackageFinder
          .new(user_project, params[:package_id]).execute

        destroy_conditionally!(package)
      end
    end
  end
end


text:
<!DOCTYPE html
  PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>LightZone: ZoneMapper: Luminosity vs. RGB</title>
    <meta name="description"
      content="The difference between luminosity and RGB adjustments using the ZoneMapper."/>
    <link rel="stylesheet" type="text/css" href="Help.css" media="all"/>
    <link rel="stylesheet" type="text/css" href="Platform.css" media="all"/>

        LightZone Hjælp

        Indholdsfortegnelse

ZoneMapper: Luminosity vs. RGB

    7 of 8

      Each pixel in a digital photo is comprised
      of red, green, and blue (RGB) values.
      A pixel's luminosity ("brightness") value
      is a weighted average of those three values.

      Normally, adjustments using a ZoneMapper
      are done using luminosity values
      because there are virtually no unintended hue or saturation changes.

      However, on occasion, luminosity-based adjustments
      can result in problems such as color-clipping.

      For example,
      if your photo has saturated highlights
      such as a clear blue sky,
      then increasing brightness
      will clip colors in portions of the sky
      because pixels that are already saturated blue
      can't become more blue.

      Adjustments using the ZoneMapper
      can alternatively be done using RGB values directly
      to address problems such as color-clipping.

      For a given photo,
      it's best to experiment
      to see which type of adjustment looks better.

To make RGB rather than luminosity adjustments:

          Select the RGB radio button for a ZoneMapper tool.

redpajama_set_name: RedPajamaGithub


text:
<?php defined('SYSPATH') or die('No direct access allowed.');

class Upload {

	/**
	 * @var  boolean  remove spaces in uploaded files
	 */
	public static $remove_spaces = TRUE;

	/**
	 * @var  string  default upload directory
	 */
	public static $default_directory = 'upload';

	/**
	 * Save an uploaded file to a new location. If no filename is provided,
	 * the original filename will be used, with a unique prefix added.
	 *
	 * This method should be used after validating the $_FILES array:
	 *
	 *     if ($array->check())
	 *     {
	 *         // Upload is valid, save it
	 *         Upload::save($_FILES['file']);
	 *     }
	 *
	 * @param   array    uploaded file data
	 * @param   string   new filename
	 * @param   string   new directory
	 * @param   integer  chmod mask
	 * @return  string   on success, full path to new file
	 * @return  FALSE    on failure
	 */
	public static function save(array $file, $filename = NULL, $directory = NULL, $chmod = 0644)
	{
		if ( ! isset($file['tmp_name']) OR ! is_uploaded_file($file['tmp_name']))
		{
			// Ignore corrupted uploads
			return FALSE;
		}

		if ($filename === NULL)
		{
			// Use the default filename, with a timestamp pre-pended
			$filename = uniqid().$file['name'];
		}

		if (Upload::$remove_spaces === TRUE)
		{
			// Remove spaces from the filename
			$filename = preg_replace('/\s+/', '_', $filename);
		}

		if ($directory === NULL)
		{
			// Use the pre-configured upload directory
			$directory = Upload::$default_directory;
		}

		if ( ! is_dir($directory) OR ! is_writable(realpath($directory)))
		{
			throw new Kohana_Exception('Directory :dir must be writable',
				array(':dir' => Kohana::debug_path($directory)));
		}

		// Make the filename into a complete path
		$filename = realpath($directory).DIRECTORY_SEPARATOR.$filename;

		if (move_uploaded_file($file['tmp_name'], $filename))
		{
			if ($chmod !== FALSE)
			{
				// Set permissions on filename
				chmod($filename, $chmod);
			}

			// Return new file path
			return $filename;
		}

		return FALSE;
	}

	/**
	 * Tests if upload data is valid, even if no file was uploaded. If you
	 * _do_ require a file to be uploaded, add the [Upload::not_empty] rule
	 * before this rule.
	 *
	 *     $array->rule('file', 'Upload::valid')
	 *
	 * @param   array  $_FILES item
	 * @return  bool
	 */
	public static function valid($file)
	{
		return (isset($file['error'])
			AND isset($file['name'])
			AND isset($file['type'])
			AND isset($file['tmp_name'])
			AND isset($file['size']));
	}

	/**
	 * Tests if a successful upload has been made.
	 *
	 *     $array->rule('file', 'Upload::not_empty');
	 *
	 * @param   array    $_FILES item
	 * @return  bool
	 */
	public static function not_empty(array $file)
	{
		return (isset($file['error'])
			AND isset($file['tmp_name'])
			AND $file['error'] === UPLOAD_ERR_OK
			AND is_uploaded_file($file['tmp_name'])
		);
	}

	/**
	 * Test if an uploaded file is an allowed file type, by extension.
	 *
	 *     $array->rule('file', 'Upload::type', array(array('jpg', 'png', 'gif')));
	 *
	 * @param   array    $_FILES item
	 * @param   array    allowed file extensions
	 * @return  bool
	 */
	public static function type(array $file, array $allowed)
	{
		if ($file['error'] !== UPLOAD_ERR_OK)
			return TRUE;

		$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

		return in_array($ext, $allowed);
	}

	/**
	 * Validation rule to test if an uploaded file is allowed by file size.
	 * File sizes are defined as: SB, where S is the size (1, 15, 300, etc) and
	 * B is the byte modifier: (B)ytes, (K)ilobytes, (M)egabytes, (G)igabytes.
	 *
	 *     $array->rule('file', 'Upload::size', array('1M'))
	 *
	 * @param   array    $_FILES item
	 * @param   string   maximum file size
	 * @return  bool
	 */
	public static function size(array $file, $size)
	{
		if ($file['error'] === UPLOAD_ERR_INI_SIZE)
		{
			// Upload is larger than PHP allowed size
			return FALSE;
		}

		if ($file['error'] !== UPLOAD_ERR_OK)
		{
			// The upload failed, no size to check
			return TRUE;
		}

		// Only one size is allowed
		$size = strtoupper(trim($size));

		if ( ! preg_match('/^[0-9]++[BKMG]$/', $size))
		{
			throw new Kohana_Exception('Size does not contain a digit and a byte value: :size', array(
				':size' => $size,
			));
		}

		// Make the size into a power of 1024
		switch (substr($size, -1))
		{
			case 'G': $size = intval($size) * pow(1024, 3); break;
			case 'M': $size = intval($size) * pow(1024, 2); break;
			case 'K': $size = intval($size) * pow(1024, 1); break;
			default:  $size = intval($size);                break;
		}

		// Test that the file is under or equal to the max size
		return ($file['size'] <= $size);
	}

} // End upload


text:
module Torque
  module PostgreSQL
    module Adapter
      module Quoting

        Name = ActiveRecord::ConnectionAdapters::PostgreSQL::Name
        Column = ActiveRecord::ConnectionAdapters::PostgreSQL::Column
        ColumnDefinition = ActiveRecord::ConnectionAdapters::ColumnDefinition

        # Quotes type names for use in SQL queries.
        def quote_type_name(string, schema = nil)
          name_schema, table = string.to_s.scan(/[^".\s]+|"[^"]*"/)
          if table.nil?
            table = name_schema
            name_schema = nil
          end

          schema = schema || name_schema || 'public'
          Name.new(schema, table).quoted
        end

        def quote_default_expression(value, column)
          return super unless value.class <= Array || value.class <= Set

          type =
            if column.is_a?(ColumnDefinition) && column.options.try(:[], :array)
              # This is the general way
              lookup_cast_type(column.sql_type)
            elsif column.is_a?(Column) && column.array?
              # When using +change_column_default+
              lookup_cast_type_from_column(column)
            end

          type.nil? ? super : quote(type.serialize(value.to_a))
        end
      end
    end
  end
end


text:
from PyQt4 import QtGui, QtCore

def get_step_groupbox():
# function get_step_groupbox() from module SubUi.py
# #Returns the groupbox GUI element conformed by the fields:
# "Start, Step, Steps, Compliance" used when "Voltage Step" or "Current Step" are selected for a SMU

    step_groupbox = QtGui.QGroupBox()
    step_groupbox.setGeometry(QtCore.QRect(20, 20, 301, 171))
    step_groupbox.setTitle("")
    step_groupbox.setObjectName("step_groupbox")

    start_lineedit = QtGui.QLineEdit(step_groupbox)
    start_lineedit.setGeometry(QtCore.QRect(100, 30, 171, 25))
    start_lineedit.setObjectName("start_lineedit")

    step_lineedit = QtGui.QLineEdit(step_groupbox)
    step_lineedit.setGeometry(QtCore.QRect(100, 60, 171, 25))
    step_lineedit.setObjectName("step_lineedit")

    steps_lineedit = QtGui.QLineEdit(step_groupbox)
    steps_lineedit.setGeometry(QtCore.QRect(100, 90, 171, 25))
    steps_lineedit.setObjectName("steps_lineedit")

    compliance_lineedit = QtGui.QLineEdit(step_groupbox)
    compliance_lineedit.setGeometry(QtCore.QRect(100, 120, 171, 25))
    compliance_lineedit.setObjectName("compliance_lineedit")

    start_label = QtGui.QLabel(step_groupbox)
    start_label.setGeometry(QtCore.QRect(20, 30, 53, 14))
    start_label.setObjectName("start_label")

    step_label = QtGui.QLabel(step_groupbox)
    step_label.setGeometry(QtCore.QRect(20, 60, 53, 14))
    step_label.setObjectName("step_label")
    steps_label = QtGui.QLabel(step_groupbox)
    steps_label.setGeometry(QtCore.QRect(20, 90, 53, 14))
    steps_label.setObjectName("steps_label")

    compliance_label = QtGui.QLabel(step_groupbox)
    compliance_label.setGeometry(QtCore.QRect(20, 120, 71, 16))
    compliance_label.setObjectName("compliance_label")

    start_label.setText("Start:")
    step_label.setText("Step:")
    steps_label.setText("Steps:")
    compliance_label.setText("Compliance:")

    return step_groupbox

def get_sweep_groupbox():
# function get_sweep_groupbox() from module SubUi.py
# #Returns the groupbox GUI element conformed by the fields: "Initial value, Final value, Compliance, Step"
# and the combobox with the options "Linear, Log10, Log25, Log50" used when "Voltage Sweep"
# or "Current Sweep" are selected for a SMU

    sweep_groupbox = QtGui.QGroupBox()
    sweep_groupbox.setGeometry(QtCore.QRect(30, 20, 271, 140))
    sweep_groupbox.setTitle("")
    sweep_groupbox.setObjectName("sweep_groupbox")

    sweep_type_label = QtGui.QLabel(sweep_groupbox)
    sweep_type_label.setGeometry(QtCore.QRect(6, 10, 81, 20))
    sweep_type_label.setObjectName("sweep_type_label")

    combobox = QtGui.QComboBox(sweep_groupbox)
    combobox.setGeometry(QtCore.QRect(100, 10, 161, 25))
    combobox.setObjectName("sweep_type_combobox")
    combobox.addItem("Linear")
    combobox.addItem("Log10")
    combobox.addItem("Log25")
    combobox.addItem("Log50")

    value_stop = QtGui.QLabel(sweep_groupbox)
    value_stop.setGeometry(QtCore.QRect(10, 90, 71, 16))
    value_stop.setObjectName("value_stop")
    value_stop.setText("Valor final: ")

    value_init = QtGui.QLabel(sweep_groupbox)
    value_init.setGeometry(QtCore.QRect(10, 50, 71, 16))
    value_init.setObjectName("value_init")
    value_init.setText("Valor inicio: ")

    val_inicio_field = QtGui.QLineEdit(sweep_groupbox)
    val_inicio_field.setGeometry(QtCore.QRect(100, 50, 161, 25))
    val_inicio_field.setObjectName("val_inicio_field")

    val_stop_field = QtGui.QLineEdit(sweep_groupbox)
    val_stop_field.setGeometry(QtCore.QRect(100, 80, 161, 25))
    val_stop_field.setObjectName("val_stop_field")

    compliance_label = QtGui.QLabel(sweep_groupbox)
    compliance_label.setGeometry(QtCore.QRect(10, 120, 80, 16))
    compliance_label.setObjectName("compliance_label")
    compliance_label.setText("Compliance: ")

    compliance_field = QtGui.QLineEdit(sweep_groupbox)
    compliance_field.setObjectName("compliance_field")
    compliance_field.setGeometry(QtCore.QRect(100, 110, 161, 25))

    step_label = QtGui.QLabel(sweep_groupbox)
    step_label.setGeometry(QtCore.QRect(10, 150, 80, 16))
    step_label.setObjectName("step_label")
    step_label.setText("Step: ")

    step_field = QtGui.QLineEdit(sweep_groupbox)
    step_field.setObjectName("step_field")
    step_field.setGeometry(QtCore.QRect(100, 140, 161, 25))

    return sweep_groupbox

def get_constant_groupbox():
# function get_constant_groupbox() from module SubUi.py
# #Returns the groupbox GUI element conformed by the fields: "Value, Compliance" used when "Voltage Constant"
# or "Current Constant" are selected for a SMU

    constant_groupbox = QtGui.QGroupBox()
    constant_groupbox.setGeometry(QtCore.QRect(10, 10, 181, 140))
    constant_groupbox.setTitle("")
    constant_groupbox.setObjectName("constant_groupbox")
    constant_label = QtGui.QLabel(constant_groupbox)
    constant_label.setGeometry(QtCore.QRect(10, 30, 61, 14))
    constant_label.setObjectName("constant_label")
    constant_textbox = QtGui.QLineEdit(constant_groupbox)
    constant_textbox.setGeometry(QtCore.QRect(100, 25, 113, 22))
    constant_textbox.setObjectName("constant_textbox")
    constant_label.setText("Valor: ")
    compliance_label = QtGui.QLabel(constant_groupbox)
    compliance_label.setGeometry(QtCore.QRect(10, 70, 90, 14))
    compliance_label.setText("Compliance: ")
    compliance_label.setObjectName("compliance_label")
    compliance_textbox = QtGui.QLineEdit(constant_groupbox)
    compliance_textbox.setGeometry(QtCore.QRect(100, 70, 113, 22))
    compliance_textbox.setObjectName("compliance_textbox")
    return constant_groupbox

def get_list_groupbox():
# function get_list_groupbox() from module SubUi.py
# #Returns the groupbox GUI element conformed by the text-edition box and its corresponding label
# used when "Voltage List Sweep" or "Current List Sweep" are selected for a SMU

    list_groupbox = QtGui.QGroupBox()
    textEdit = QtGui.QTextEdit(list_groupbox)
    textEdit.setGeometry(QtCore.QRect(20, 30, 250, 140))
    textEdit.setObjectName("list_textedit")
    label = QtGui.QLabel(list_groupbox)
    label.setGeometry(QtCore.QRect(20, 5, 250, 19))
    label.setObjectName("label_description")
    label.setText("Lista de valores separados por comas")
    return list_groupbox

def get_start_stop_ui():
# function get_start_stop_ui() from module SubUi.py
# #Returns the groupbox GUI element conformed by the fields "Initial frecuency, Final frecuency, Range"
# and the label "Frecuency" used when the "Start-Stop"type of medition is selected

    freq_groupbox = QtGui.QGroupBox()
    freq_groupbox.setGeometry(QtCore.QRect(20, 20, 250, 140))
    freq_groupbox.setObjectName("freq_groupbox")
    verticalLayoutWidget = QtGui.QWidget(freq_groupbox)
    verticalLayoutWidget.setGeometry(QtCore.QRect(20, 20, 250, 107))
    verticalLayoutWidget.setObjectName("verticalLayoutWidget")
    verticalLayout = QtGui.QVBoxLayout(verticalLayoutWidget)
    verticalLayout.setMargin(0)
    verticalLayout.setObjectName("verticalLayout")
    horizontalLayout_6 = QtGui.QHBoxLayout()
    horizontalLayout_6.setObjectName("horizontalLayout_6")
    freqstart_label = QtGui.QLabel(verticalLayoutWidget)
    freqstart_label.setObjectName("freqstart_label")
    horizontalLayout_6.addWidget(freqstart_label)
    freqstart_field = QtGui.QLineEdit(verticalLayoutWidget)
    freqstart_field.setObjectName("freqstart_field")
    horizontalLayout_6.addWidget(freqstart_field)
    verticalLayout.addLayout(horizontalLayout_6)
    horizontalLayout_4 = QtGui.QHBoxLayout()
    horizontalLayout_4.setObjectName("horizontalLayout_4")
    freqstop_label = QtGui.QLabel(verticalLayoutWidget)
    freqstop_label.setObjectName("freqstop_label")
    horizontalLayout_4.addWidget(freqstop_label)
    freqstop_field = QtGui.QLineEdit(verticalLayoutWidget)
    freqstop_field.setObjectName("freqstop_field")
    horizontalLayout_4.addWidget(freqstop_field)
    verticalLayout.addLayout(horizontalLayout_4)
    horizontalLayout_5 = QtGui.QHBoxLayout()
    horizontalLayout_5.setObjectName("horizontalLayout_5")
    range_label = QtGui.QLabel(verticalLayoutWidget)
    range_label.setObjectName("range_label")
    horizontalLayout_5.addWidget(range_label)
    range_field = QtGui.QLineEdit(verticalLayoutWidget)
    range_field.setObjectName("range_field")
    horizontalLayout_5.addWidget(range_field)
    verticalLayout.addLayout(horizontalLayout_5)
    freq_groupbox.setTitle("Frecuencia")
    freqstart_label.setText("Frecuencia inicial")
    freqstop_label.setText("Frecuencia final")
    range_label.setText("Rango")
    return freq_groupbox

def get_center_span_ui():
# function get_center_span_ui() from module SubUi.py
# #Returns the groupbox GUI element conformed by the fields "Center, Span" and the label "Frecuency"
# used when the "Center-Span" type of medition is selected

    freq_groupbox = QtGui.QGroupBox()
    freq_groupbox.setGeometry(QtCore.QRect(20, 20, 250, 148))
    freq_groupbox.setObjectName("freq_groupbox")
    verticalLayoutWidget = QtGui.QWidget(freq_groupbox)
    verticalLayoutWidget.setGeometry(QtCore.QRect(20, 20, 250, 107))
    verticalLayoutWidget.setObjectName("verticalLayoutWidget")
    verticalLayout = QtGui.QVBoxLayout(verticalLayoutWidget)
    verticalLayout.setMargin(0)
    verticalLayout.setObjectName("verticalLayout")
    horizontalLayout_6 = QtGui.QHBoxLayout()
    horizontalLayout_6.setObjectName("horizontalLayout_6")
    center_label = QtGui.QLabel(verticalLayoutWidget)
    center_label.setObjectName("center_label")
    horizontalLayout_6.addWidget(center_label)
    center_field = QtGui.QLineEdit(verticalLayoutWidget)
    center_field.setObjectName("center_field")
    horizontalLayout_6.addWidget(center_field)
    verticalLayout.addLayout(horizontalLayout_6)
    horizontalLayout_4 = QtGui.QHBoxLayout()
    horizontalLayout_4.setObjectName("horizontalLayout_4")
    span_label = QtGui.QLabel(verticalLayoutWidget)
    span_label.setObjectName("span_label")
    horizontalLayout_4.addWidget(span_label)
    span_field = QtGui.QLineEdit(verticalLayoutWidget)
    span_field.setObjectName("span_field")
    horizontalLayout_4.addWidget(span_field)
    verticalLayout.addLayout(horizontalLayout_4)
    freq_groupbox.setTitle("Frecuencia")
    center_label.setText("Centro")
    span_label.setText("Span")
    return freq_groupbox


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Zirpl.AppEngine.Model;
using Zirpl.AppEngine.Model.Customization;

namespace Zirpl.Examples.CodeGeneration.VS2013.Commerce.Model.Orders
{
    public partial class OrderChargeStatusType  : DictionaryEntityBase<byte, OrderChargeStatusTypeEnum>
    {
    }
}


text:
from django.urls import reverse_lazy

from oscar.core.loading import get_model

from oscar.test.factories import create_product, WishListFactory
from oscar.test.testcases import WebTestCase

WishList = get_model('wishlists', 'WishList')

class WishListTestMixin(object):
    is_anonymous = False

    def setUp(self):
        super().setUp()
        self.product = create_product()

class TestProductDetailPage(WishListTestMixin, WebTestCase):

    def test_allows_a_product_to_be_added_to_wishlist(self):
        # Click add to wishlist button
        detail_page = self.get(self.product.get_absolute_url())
        form = detail_page.forms['add_to_wishlist_form']
        response = form.submit()
        self.assertIsRedirect(response)

        # Check a wishlist has been created
        wishlists = self.user.wishlists.all()
        self.assertEqual(1, len(wishlists))

        lines = wishlists[0].lines.all()
        self.assertEqual(1, len(lines))
        self.assertEqual(self.product, lines[0].product)

class TestMoveProductToAnotherWishList(WishListTestMixin, WebTestCase):
    def setUp(self):
        super().setUp()
        self.wishlist1 = WishListFactory(owner=self.user)
        self.wishlist2 = WishListFactory(owner=self.user)

    def test_move_product_to_another_wishlist_already_containing_it(self):
        self.wishlist1.add(self.product)
        line1 = self.wishlist1.lines.get(product=self.product)
        self.wishlist2.add(self.product)
        url = reverse_lazy('customer:wishlists-move-product-to-another', kwargs={'key': self.wishlist1.key,
                                                                                'line_pk': line1.pk,
                                                                                'to_key': self.wishlist2.key})
        self.get(url)
        self.assertEqual(self.wishlist1.lines.filter(product=self.product).count(), 1)
        self.assertEqual(self.wishlist2.lines.filter(product=self.product).count(), 1)

    def test_move_product_to_another_wishlist(self):
        self.wishlist1.add(self.product)
        line1 = self.wishlist1.lines.get(product=self.product)
        url = reverse_lazy('customer:wishlists-move-product-to-another', kwargs={'key': self.wishlist1.key,
                                                                                'line_pk': line1.pk,
                                                                                'to_key': self.wishlist2.key})
        self.get(url)
        self.assertEqual(self.wishlist1.lines.filter(product=self.product).count(), 0)
        self.assertEqual(self.wishlist2.lines.filter(product=self.product).count(), 1)


text:
package org.restler.http;

public class HttpStatus {

    public final int code;
    public final String line;

    public HttpStatus(int code, String line) {
        this.code = code;
        this.line = line;
    }

    @Override public String toString() {
        return "HttpStatus{" +
                "code=" + code +
                ", line='" + line + '\'' +
                '}';
    }
}


text:
using System;
using System.Collections.Generic;
using AutoMapper;
using Nimrod.Events.DataAccess.EF;
using Nimrod.Events.DomainModel;
using Nimrod.Events.Services.Actions.Base;

namespace Nimrod.Events.Services.Actions
{
    public class SessionActions : EventActions, ISessionActions
    {
        private readonly IMapper _mapper;

        public SessionActions(IMapper mapper, EventsDb db) : base(db)
        {
            _mapper = mapper;
        }

        public Session Update(Session session)
        {
            try
            {
                Session entity = _db.Sessions.Find(session.Id);
                _mapper.Map(session, entity);
                _db.SaveChanges();
                return entity;
            }
            catch (InvalidOperationException)
            {
                throw new KeyNotFoundException();
            }
        }

        public Session Add(Session session)
        {
            _db.Sessions.Add(session);
            _db.SaveChanges();
            return session;
        }

        public void Delete(int id)
        {
            try
            {
                Session session = _db.Sessions.Find(id);
                _db.Sessions.Remove(session);
                _db.SaveChanges();

            }
            catch (InvalidOperationException)
            {
                throw new KeyNotFoundException();
            }
        }
    }
}


text:
streamworks
===========

![streamworks logo](https://github.com/binocarlos/streamworks/raw/master/graphics/stream.jpg "streamworks Logo")

![Build status](https://api.travis-ci.org/binocarlos/streamworks.png)

Combine merge and pipe streams into stream architectures that can bend packets to your will.

## merge stream

![merge stream diagram](https://github.com/binocarlos/streamworks/raw/master/graphics/merge.png "merge stream diagram")

A merge stream will duplicate the input across all members and merge the output from all members (based on [combine-stream](https://github.com/deoxxa/combine-stream).

## pipe stream

![pipe stream diagram](https://github.com/binocarlos/streamworks/raw/master/graphics/pipe.png "pipe stream diagram")

A pipe stream will pass the output from each member as the input to the next (based on [stream-combiner](https://github.com/dominictarr/stream-combiner).

## combo streams

![combo stream diagram](https://github.com/binocarlos/streamworks/raw/master/graphics/combo.png "combo stream diagram")

Both types accepts streams in their list - you can combine merge and pipes with each other - it's stream inception!

## installation

```
$ npm install streamworks
```

## usage

There are 2 main methods:

 * merge
 * pipe

Create each type of stream by passing an array of either:

 * functions - these are turned into streams using [through2](https://github.com/rvagg/through2)
 * streams - these are used as is

## example

```js
var from = require('from');
var streamworks = require('streamworks');

// a merge is a stream that splits the input across each function and merges the output back into one stream
var mergestream = streamworks.merge([

	// order lots
	function(chunk, enc, callback){
		this.push(chunk + ':10')
		callback()
	},

	// order some
	function(chunk, enc, callback){
		this.push(chunk + ':2')
		callback()
	}
])

// a pipe is a stream that passes values through each function
var pipestream = streamworks.pipe([

	// filter anything that does not start with p
	function(chunk, enc, callback){
		if(chunk.toString().indexOf('p')!=0){
			this.push(chunk);
		}
		callback();
	},

	// uppercase to input
	function(chunk, enc, callback){

		this.push(chunk.toString().toUpperCase())
	}
])

// run some data through the merge stream (which will duplicate it) and then through the pipe stream (which will filter it)
from(['apple', 'pie', 'custard'])
	.pipe(mergestream)
	.pipe(pipestream)
	.pipe(process.stdout)
```

## nested streams

Because streamworks streams are, umm, streams - you can create complex nested stream-structures:

```js

var bigAssStream = streamworks.pipe([
  function(chunk, enc, callback){
    if(chunk!='world'){
      this.push(chunk);
    }
    callback();
  },

  streamworks.merge([
    function(chunk, enc, callback){
      this.push('A1:' + chunk);
      callback();
    },
    function(chunk, enc, callback){
      this.push('A2:' + chunk);
      callback();
    },
    function(chunk, enc, callback){
      this.push('A3:' + chunk);
      callback();
    }
  ]),

  streamworks.pipe([

    function(chunk, enc, callback){
      if(chunk.toString().indexOf('A2')!=0){
        this.push(chunk);
      }
      callback();
    },
    streamworks.merge([
      function(chunk, enc, callback){
        this.push('sub1:' + chunk);
        callback();
      },
      function(chunk, enc, callback){
        this.push('sub2:' + chunk);
        callback();
      }
    ]),
    function(chunk, enc, callback){
      if(chunk.toString().indexOf('sub2:A1:')!=0){
        this.push(chunk);
      }

      callback()
    },
  ])
])

var arr = [];

from(['hello','world','apple']).pipe(bigAssStream)
.on('data', function(chunk){
  arr.push(chunk.toString())
}).on('end', function(){
	console.dir(arr);
})

/*

sub1:A1:hello
sub1:A3:hello
sub2:A3:hello
sub1:A1:apple
sub1:A3:apple
sub2:A3:apple

*/

```

## object streams

If you pass true or:

```js
{
	objectMode:true
}
```

as the first argument to pipe or merge - the stream will be in object mode.

this means that the 'chunks' will be what you sent and not buffers/strings.

You can also use:

 * pipeObjects
 * mergeObjects

Which are shortcuts for:

 * pipe(true, [])
 * merge(true, [])

## api

#### `streamworks.pipe([objectMode], fns)`

create a new readable/writable stream that will pipe each value through the array of streams/functions

#### `streamworks.pipeObjects(fns)`

shorthand for pipe(true, [])

#### `streamworks.merge([objectMode], fns)`

create a new readable/writable stream that will duplicate each value into each of the streams/functions and merge the results back into the output

#### `streamworks.mergeObjects(fns)`

shorthand for merge(true, [])

## license

MIT


text:
require 'spec_helper'

describe 'Merge request > User posts diff notes', :js do
  include MergeRequestDiffHelpers

  let(:merge_request) { create(:merge_request) }
  let(:project) { merge_request.source_project }
  let(:user) { project.creator }
  let(:comment_button_class) { '.add-diff-note' }
  let(:notes_holder_input_class) { 'js-temp-notes-holder' }
  let(:notes_holder_input_xpath) { './following-sibling::*[contains(concat(" ", @class, " "), " notes_holder ")]' }
  let(:test_note_comment) { 'this is a test note!' }

  before do
    set_cookie('sidebar_collapsed', 'true')

    project.add_developer(user)
    sign_in(user)
  end

  context 'when hovering over a parallel view diff file' do
    before do
      visit diffs_project_merge_request_path(project, merge_request, view: 'parallel')
    end

    context 'with an old line on the left and no line on the right' do
      it 'allows commenting on the left side' do
        should_allow_commenting(find('[id="6eb14e00385d2fb284765eb1cd8d420d33d63fc9_23_22"]').find(:xpath, '..'), 'left')
      end

      it 'does not allow commenting on the right side' do
        should_not_allow_commenting(find('[id="6eb14e00385d2fb284765eb1cd8d420d33d63fc9_23_22"]').find(:xpath, '..'), 'right')
      end
    end

    context 'with no line on the left and a new line on the right' do
      it 'does not allow commenting on the left side' do
        should_not_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_15_15"]').find(:xpath, '..'), 'left')
      end

      it 'allows commenting on the right side' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_15_15"]').find(:xpath, '..'), 'right')
      end
    end

    context 'with an old line on the left and a new line on the right' do
      it 'allows commenting on the left side' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_9_9"]').find(:xpath, '..'), 'left')
      end

      it 'allows commenting on the right side' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_9_9"]').find(:xpath, '..'), 'right')
      end
    end

    context 'with an unchanged line on the left and an unchanged line on the right' do
      it 'allows commenting on the left side' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_7_7"]', match: :first).find(:xpath, '..'), 'left')
      end

      it 'allows commenting on the right side' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_7_7"]', match: :first).find(:xpath, '..'), 'right')
      end
    end

    context 'with a match line' do
      it 'does not allow commenting on the left side' do
        line_holder = find('.match', match: :first).find(:xpath, '..')
        match_should_not_allow_commenting(line_holder)
      end

      it 'does not allow commenting on the right side' do
        line_holder = find('.match', match: :first).find(:xpath, '..')
        match_should_not_allow_commenting(line_holder)
      end
    end

    context 'with an unfolded line' do
      before do
        find('.js-unfold', match: :first).click
        wait_for_requests
      end

      # The first `.js-unfold` unfolds upwards, therefore the first
      # `.line_holder` will be an unfolded line.
      let(:line_holder) { first('#a5cc2925ca8258af241be7e5b0381edf30266302 .line_holder') }

      it 'allows commenting on the left side' do
        should_allow_commenting(line_holder, 'left')
      end

      it 'allows commenting on the right side' do
        # Automatically shifts comment box to left side.
        should_allow_commenting(line_holder, 'right')
      end
    end
  end

  context 'when hovering over an inline view diff file' do
    before do
      visit diffs_project_merge_request_path(project, merge_request, view: 'inline')
    end

    context 'after deleteing a note' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_10_9"]'))

        accept_confirm do
          first('button.more-actions-toggle').click
          first('.js-note-delete').click
        end

        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_10_9"]'))
      end
    end

    context 'with a new line' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_10_9"]'))
      end
    end

    context 'with an old line' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="6eb14e00385d2fb284765eb1cd8d420d33d63fc9_22_22"]'))
      end
    end

    context 'with an unchanged line' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_7_7"]'))
      end
    end

    context 'with a match line' do
      it 'does not allow commenting' do
        match_should_not_allow_commenting(find('.match', match: :first))
      end
    end

    context 'with an unfolded line' do
      before do
        find('.js-unfold', match: :first).click
        wait_for_requests
      end

      # The first `.js-unfold` unfolds upwards, therefore the first
      # `.line_holder` will be an unfolded line.
      let(:line_holder) { first('.line_holder[id="a5cc2925ca8258af241be7e5b0381edf30266302_1_1"]') }

      it 'allows commenting' do
        should_allow_commenting line_holder
      end
    end

    context 'when hovering over a diff discussion' do
      before do
        visit diffs_project_merge_request_path(project, merge_request, view: 'inline')
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_7_7"]'))
        visit project_merge_request_path(project, merge_request)
      end

      it 'does not allow commenting' do
        should_not_allow_commenting(find('.line_holder', match: :first))
      end
    end
  end

  context 'when cancelling the comment addition' do
    before do
      visit diffs_project_merge_request_path(project, merge_request, view: 'inline')
    end

    context 'with a new line' do
      it 'allows dismissing a comment' do
        should_allow_dismissing_a_comment(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_10_9"]'))
      end
    end
  end

  describe 'with multiple note forms' do
    before do
      visit diffs_project_merge_request_path(project, merge_request, view: 'inline')
      click_diff_line(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_10_9"]'))
      click_diff_line(find('[id="6eb14e00385d2fb284765eb1cd8d420d33d63fc9_22_22"]'))
    end

    describe 'posting a note' do
      it 'adds as discussion' do
        should_allow_commenting(find('[id="6eb14e00385d2fb284765eb1cd8d420d33d63fc9_22_22"]'), asset_form_reset: false)
        expect(page).to have_css('.notes_holder .note.note-discussion', count: 1)
        expect(page).to have_button('Reply...')
      end
    end
  end

  context 'when the MR only supports legacy diff notes' do
    before do
      merge_request.merge_request_diff.update(start_commit_sha: nil)
      visit diffs_project_merge_request_path(project, merge_request, view: 'inline')
    end

    context 'with a new line' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_10_9"]'))
      end
    end

    context 'with an old line' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="6eb14e00385d2fb284765eb1cd8d420d33d63fc9_22_22"]'))
      end
    end

    context 'with an unchanged line' do
      it 'allows commenting' do
        should_allow_commenting(find('[id="2f6fcd96b88b36ce98c38da085c795a27d92a3dd_7_7"]'))
      end
    end

    context 'with a match line' do
      it 'does not allow commenting' do
        match_should_not_allow_commenting(find('.match', match: :first))
      end
    end
  end

  def should_allow_commenting(line_holder, diff_side = nil, asset_form_reset: true)
    write_comment_on_line(line_holder, diff_side)

    click_button 'Comment'

    wait_for_requests

    assert_comment_persistence(line_holder, asset_form_reset: asset_form_reset)
  end

  def should_allow_dismissing_a_comment(line_holder, diff_side = nil)
    write_comment_on_line(line_holder, diff_side)

    find('.js-close-discussion-note-form').click

    assert_comment_dismissal(line_holder)
  end

  def should_not_allow_commenting(line_holder, diff_side = nil)
    line = get_line_components(line_holder, diff_side)
    line[:content].hover
    expect(line[:num]).not_to have_css comment_button_class
  end

  def match_should_not_allow_commenting(line_holder)
    expect(line_holder).not_to have_css comment_button_class
  end

  def write_comment_on_line(line_holder, diff_side)
    click_diff_line(line_holder, diff_side)

    notes_holder_input = line_holder.find(:xpath, notes_holder_input_xpath)

    expect(notes_holder_input[:class]).to include(notes_holder_input_class)

    notes_holder_input.fill_in 'note[note]', with: test_note_comment
  end

  def assert_comment_persistence(line_holder, asset_form_reset:)
    notes_holder_saved = line_holder.find(:xpath, notes_holder_input_xpath)

    expect(notes_holder_saved[:class]).not_to include('note-edit-form')
    expect(notes_holder_saved).to have_content test_note_comment

    assert_form_is_reset if asset_form_reset
  end

  def assert_comment_dismissal(line_holder)
    expect(line_holder).not_to have_xpath notes_holder_input_xpath
    expect(page).not_to have_content test_note_comment

    assert_form_is_reset
  end

  def assert_form_is_reset
    expect(page).to have_no_css('.note-edit-form')
  end
end


text:
<?php
	/**
	 * Created by PhpStorm.
	 * User: marksimonds
	 * Date: 2/1/16
	 * Time: 4:18 PM
	 */

	require_once('../config.php');

	try
	{
		/* initialize whatcounts */
		$whatcounts = new ZayconWhatCounts\WhatCounts( WC_REALM, WC_PASSWORD );

		$campaign_name = "test_automation_campaign";

		$subscriber_id = 123456;
		$subscriber = $whatcounts->showSubscriber($subscriber_id);

		$updated_subscriber = $whatcounts->addSubscriberToLifecycleCampaign($subscriber, $campaign_name);
		if (class_exists('Kint')) {
			Kint::dump($updated_subscriber);
		} else {
			var_dump($updated_subscriber);
		}
	}
	catch ( ZayconWhatCounts\Exception $e )
	{
		if (class_exists('Kint')) {
			Kint::dump($e);
		} else {
			var_dump($e);
		}
	}


text:
```
PS> Install-WindowsFeature -Name Hyper-V -IncludeManagementTools -Restart
```

- [ ] Tester le role Hyper V et les outils de gestion `RSAT`

```
PS> Get-WindowsFeature *Hyper*

Display Name                                            Name                       Install State
------------                                            ----                       -------------
[X] Hyper-V                                             Hyper-V                        Installed
        [X] Hyper-V Management Tools                    RSAT-Hyper-V-Tools             Installed
            [X] Hyper-V Module for Windows PowerShell   Hyper-V-PowerShell             Installed
```

:bulb: Si non installé par la commande globale

- [ ] Installer les modules individuellement

```
PS> Install-WindowsFeature -Name Hyper-V-PowerShell

PS> # Install Hyper-V Manager and the PowerShell module (HVM only available on GUI systems)
PS> Install-WindowsFeature -Name RSAT-Hyper-V-Tools

PS> # Install the Hyper-V hypervisor and all tools (method #1)
PS> Install-WindowsFeature -Name Hyper-V -IncludeManagementTools

PS> # Install the Hyper-V hypervisor and all tools (method #2)
PS> Install-WindowsFeature -Name Hyper-V, RSAT-Hyper-V-Tools
```

- [ ] Lister les modules Hyper-V

```
PS> Get-Module -ListAvailable *Hyper*

    Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules

ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Binary     2.0.0.0    Hyper-V                             {Add-VMAssignableDevice, Add-VMDvdDrive, Add-VMFibreChan...
Binary     1.1        Hyper-V                             {Add-VMDvdDrive, Add-VMFibreChannelHba, Add-VMHardDiskDr...

```

## :b: Voir les commandes Powershell pour le role Hyper V

```
PS> Get-Command -Module Hyper-V
```

## :ab: Virtual Switch

- [ ] Create Virtual Switch

:round_pushpin: Visualiser vos Switch Virtuels

```
PS> Get-VMSwitch  * | Format-Table Name
```

:round_pushpin: Visualiser vos cartes ethernets

```
PS> Get-NetAdapter

Name                      InterfaceDescription                    ifIndex Status       MacAddress             LinkSpeed
----                      --------------------                    ------- ------       ----------             ---------
Ethernet                  QLogic BCM5709C Gigabit Ethernet ...#47      10 Up           1C-C1-DE-F3-0D-44        10 Mbps
vEthernet (nat)           Hyper-V Virtual Ethernet Adapter             12 Up           00-15-5D-DB-3C-DE        10 Gbps
...
```

:round_pushpin: Creer la Switch Virtuelle pour le driver HyperV

:bulb: Le nom doit être `Primary Virtual Switch` par défaut

```
PS> $net = Get-NetAdapter -Name 'Ethernet'
PS> New-VMSwitch -Name "Primary Virtual Switch" -AllowManagementOS $True -NetAdapterName $net.Name
```

# References

https://www.altaro.com/hyper-v/install-hyper-v-powershell-module/

https://techthoughts.info/home-lab-setup/


text:
#pragma once

#include <vector>
#include "../interface/math/smatrix.h"

namespace nntl {

	//this is to define some flags for each epoch (currently it is whether to launch nn evaluation after an epoch or not)
	class vector_conditions {
	public:
		//using numel_cnt_t = math::smatrix_td::numel_cnt_t;
		typedef vector_conditions self_t;

		//////////////////////////////////////////////////////////////////////////
		//members
	protected:
		//TODO: vector may throw exceptions...
		::std::vector<bool> m_flgEvalPerf;

	public:
		~vector_conditions()noexcept {}
		vector_conditions()noexcept {}
		vector_conditions(numel_cnt_t maxEpoch, const bool& defVal=true)noexcept:m_flgEvalPerf(maxEpoch, defVal) {
			NNTL_ASSERT(maxEpoch > 0);
			verbose(maxEpoch - 1);
		}
		vector_conditions(numel_cnt_t maxEpoch,numel_cnt_t stride)noexcept : m_flgEvalPerf(maxEpoch, false) {
			NNTL_ASSERT(maxEpoch > 0 && stride>0);
			verbose(stride, maxEpoch, stride);
			verbose(maxEpoch - 1);
		}
		vector_conditions(numel_cnt_t maxEpoch, numel_cnt_t startsAt, numel_cnt_t stride)noexcept : m_flgEvalPerf(maxEpoch, false) {
			NNTL_ASSERT(maxEpoch > 0 && startsAt <= maxEpoch && stride > 0);
			verbose(startsAt, maxEpoch, stride);
			verbose(maxEpoch - 1);
		}
		vector_conditions(vector_conditions&& src)noexcept : m_flgEvalPerf(::std::move(src.m_flgEvalPerf)) {}

		//!! copy constructor not needed
		vector_conditions(const vector_conditions& other)noexcept = delete;
		//!!assignment is not needed
		vector_conditions& operator=(const vector_conditions& rhs) noexcept = delete;

		self_t& resize(numel_cnt_t maxEpoch, const bool& defVal = false)noexcept {
			m_flgEvalPerf.resize(maxEpoch, defVal);
			return *this;
		}
		self_t& clear()noexcept {
			m_flgEvalPerf.clear();
			return *this;
		}

		numel_cnt_t size()const noexcept { return conform_sign(m_flgEvalPerf.size()); }
		numel_cnt_t maxEpoch()const noexcept { return size(); }

		//using () instead of [] because can't (and don't need to) return reference
		const bool operator()(numel_cnt_t e)const noexcept { return m_flgEvalPerf[e]; }

		self_t& set(numel_cnt_t i, const bool v)noexcept { m_flgEvalPerf[i] = v; return *this; }
		self_t& set(const numel_cnt_t _beg, const numel_cnt_t _end, const numel_cnt_t stride, const bool v)noexcept {
			NNTL_ASSERT(stride > 0 && _beg > 0 && _end >= _beg);
			for (numel_cnt_t i = _beg - 1; i < _end; i += stride) m_flgEvalPerf[i] = v;
			return *this;
		}

		self_t& verbose(numel_cnt_t i)noexcept { return set(i, true); }
		self_t& verbose(numel_cnt_t _beg, numel_cnt_t _end, numel_cnt_t stride = 1)noexcept { return set(_beg, _end, stride, true); }

		self_t& silence(numel_cnt_t i)noexcept { return set(i, false); }
		self_t& silence(numel_cnt_t _beg, numel_cnt_t _end, numel_cnt_t stride = 1)noexcept { return set(_beg, _end, stride, false); }
	};

}


text:
package com.olavz.report;

import com.olavz.TestCriteria;
import com.olavz.TestPage;
import com.olavz.TestProfile;

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

public class Report {

    private String title = "Generic Selenium test";
    private List<TestProfile> profileList = new ArrayList<>();
    private boolean reportHasFailure = false;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void addTestProfile(TestProfile testProfile) {
        profileList.add(testProfile);

        // Check for failure each time we add a test profile.
        if(testProfile.hasFailure()) {
            reportHasFailure = true;
        }
    }

    private String getStatusImage(boolean hasFailed) {
        String source;
        if(hasFailed) {
            source = "img/failure.png";
        } else {
            source = "img/success.png";
        }
        return "";
    }
    private String getStatusImage(String status) {
        if(status.equalsIgnoreCase("SUCCESS")) {
            return getStatusImage(false);
        } else {
            return getStatusImage(true);
        }
    }

    public String processReportAndProduceOutcome() {
        StringBuilder sb = new StringBuilder();

        for (TestProfile testProfile : profileList) {
            sb.append("
");
            sb.append("
Profile: " + testProfile.getTitle() + "
");
            for (TestPage testPage : testProfile.getTestPages()) {
                sb.append("
");
                sb.append("
" +
                        "
" + getStatusImage(testPage.hasFailed()) + testPage.getDescription() + "
 " +
                        "
" + testPage.getUrl() + "
" +
                        "
");
                sb.append("
");
                for (TestCriteria testCriteria : testPage.getTestCriteriasWithResult()) {
                    sb.append("
");
                    sb.append("
" +
                            "
" + getStatusImage(testCriteria.hasFailed()) + testCriteria.getReference() +"
" +
                            "
 " + testCriteria.getDescription() + "
" +
                            "
");

                    sb.append("
");
                    if(testCriteria.getListMultipleElementResults().isEmpty()) {
                        sb.append("
" +
                                "
No results. Not required?
" +
                                "
");
                    } else {
                        for (HashMap<String, String> singleElement : testCriteria.getListMultipleElementResults()) {
                            for (HashMap.Entry<String, String> entry : singleElement.entrySet()) {
                                String key = entry.getKey();
                                String value = entry.getValue();
                                sb.append("
" +
                                        "
" + getStatusImage(value) + "

" + key + "
" +
                                        "
");
                            }
                        }
                    }

                    sb.append("
");
                    sb.append("
");
                }
                sb.append("
");
                sb.append("
");
            }
            sb.append("
");
        }

        return sb.toString();
    }

    public boolean hasFailure() {
        return reportHasFailure;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Need a single page website for your business? I can help! Check out this example.">
    <meta name="author" content="Ricardo Maldonado">

        <title>Single Page Website | Ricardo M</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="../css/style.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Ricardo Maldonado

Ricardo M.

        HOME
        CONTACT ME

Single Page Website

Contact Me

Copyright © 2017 Ricardo Maldonado. All Rights Reserved


text:
<component name="libraryTable">
  <library name="percent-23.0.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/percent/23.0.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.android.support/percent/23.0.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
using Microsoft.Extensions.Logging;

public static partial class Extensions
{
    /// <summary>
    /// Creates a <see cref="LogBuilder"/> to build a trace level log entry.
    /// </summary>
    /// <param name="logger">The <see cref="ILogger"/> to write to.</param>
    /// <returns>The <see cref="LogBuilder"/> to build log entry.</returns>
    public static LogBuilder Trace(this ILogger logger)
    {
        return new LogBuilder(logger, LogLevel.Trace);
    }
}


text:
'use strict';

import _ from 'underscore';
import { API_UPDATE_USER_SUCCESS } from 'app/actions/auth';
import { CLEAR_SUCCESS_STATE } from 'app/actions/submitButton';

export default function navBarState(state = {}, action) {
  switch (action.type) {
    case API_UPDATE_USER_SUCCESS:
      return { ...state, success: true };
    case CLEAR_SUCCESS_STATE:
      return _.omit(state, 'success');
  }

  return state;
}


text:
using AVF.MemberManagement.StandardLibrary.Interfaces;
using AVF.MemberManagement.StandardLibrary.Tbo;
using AVF.StandardLibrary.Extensions;
using Microsoft.Extensions.Logging;
using Prism.Commands;
using Prism.Navigation;
using Prism.Services;
using System;
using System.Linq;
using System.Windows.Input;

namespace AVF.CourseParticipation.ViewModels
{
    public class TrainerSelectionPageViewModel : MemberSelectionPageViewModel
    {
        private readonly IPageDialogService _dialogService;

        public TrainerSelectionPageViewModel(INavigationService navigationService, IRepository<Mitglied> memberRepository, ILogger logger, IRepository<TrainerErnennung> trainerAppointmentsRepository, IRepository<Training> trainingsRepository, IRepository<TrainingsTeilnahme> trainingParticipationsRepository, IPageDialogService dialogService)
            : base(navigationService, memberRepository, logger, trainerAppointmentsRepository, trainingsRepository, trainingParticipationsRepository, dialogService)
        {
            CancelCommand = new DelegateCommand(Cancel, CanCancel);
            SaveCommand = new DelegateCommand(Save, CanSave);
            _dialogService = dialogService;
        }

        public override async void OnNavigatedTo(INavigationParameters parameters)
        {
            await OnNavigatedToAsync(parameters);

            if (parameters.ContainsKey("Training") && parameters["Training"] != null)
            {
                var training = (Training) parameters["Training"];

                AddSelectedMember(training.Trainer);
                AddCotrainer(training.Kotrainer1);
                AddCotrainer(training.Kotrainer2);
            }
            else
            {
                AddSelectedMember(SelectedCourseSelectionInfo.MemberId);

                foreach (var coTrainerMemberId in SelectedCourseSelectionInfo.ContrainerMemberIds)
                {
                    if (coTrainerMemberId == null || !(coTrainerMemberId > 0)) continue;

                    var memberId = (int)coTrainerMemberId;
                    AddSelectedMember(memberId);
                }
            }
        }

        private void AddCotrainer(int? memberId)
        {
            if (memberId != null && memberId != -1)
            {
                AddSelectedMember((int)memberId);
            }
        }

        private void AddSelectedMember(int memberId)
        {
            var member = Members.Single(m => m.MemberId == memberId);
            AddSelectedMember(member);
        }

        #region CancelCommand

        public ICommand CancelCommand { get; }

        internal async void Cancel()
        {
            var shouldCancel = await _dialogService.DisplayAlertAsync("Abbrechen", "Möchten Sie verlassen OHNE zu speichern?", "Ja", "Nein");

            if (shouldCancel)
            {
                await NavigationService.GoBackAsync();
            }
        }

        private bool CanCancel()
        {
            return true;
        }

        #endregion

        #region SaveCommand

        protected override async void Save()
        {
            base.Save();

            var trainingsRepository = TrainingsRepository;
            var selectedDate = SelectedDate;
            var courseId = SelectedCourseSelectionInfo.CourseId;

            var trainings = await trainingsRepository.GetAsync(courseId, selectedDate);

            Training training;

            if (trainings == null || trainings.Count == 0)
            {
                training = CreateNewTraining(SelectedCourseSelectionInfo.CourseId, SelectedDate);
            }
            else
            {
                training = trainings.Single();
            }

            //TODO: only update if really something changes
            training.DatensatzGeaendertAm = DateTime.Now;
            training.DatensatzGeaendertVon = (int)LoggedInMemberId;

            //Reset always and than apply new selected values
            training.Trainer = -1;
            training.Kotrainer1 = -1;
            training.Kotrainer2 = -1;

            var i = 0;
            foreach (var selectedMember in SelectedMembers)
            {
                switch (i)
                {
                    case 0:
                        training.Trainer = selectedMember.MemberId;
                        break;
                    case 1:
                        training.Kotrainer1 = selectedMember.MemberId;
                        break;
                    case 2:
                        training.Kotrainer2 = selectedMember.MemberId;
                        break;
                }

                i++;
            }

            if (training.Id == 0)
            {
                training.Id = await TrainingsRepository.CreateAsync(training);
            }
            else
            {
                await TrainingsRepository.UpdateAsync(training);
            }

            var parameters
                = new NavigationParameters { { nameof(Training), training } };
            await NavigationService.GoBackAsync(parameters);
        }

        private Training CreateNewTraining(int courseId, DateTime selectedDate)
        {
            Training newTraining = new Training();

            newTraining.Id = 0; //0 is the identifier for the proxy for auto generating an id, because -1 is an allowed value (for example if we want to use the negative ids later for some purposes)
            newTraining.Bemerkung = string.Empty;
            newTraining.DatensatzAngelegtAm = DateTime.Now;
            newTraining.DatensatzAngelegtVon = (int) LoggedInMemberId;
            newTraining.Kotrainer1 = -1; //erledigt, siehe oben
            newTraining.Kotrainer2 = -1; //erledigt, siehe oben
            newTraining.Trainer = -1; //erledigt, siehe oben
            //newTraining.DatensatzGeaendertAm //erledigt, siehe oben in training.Single
            //newTraining.DatensatzGeaendertVon = //erledigt, siehe oben in training.Single
            newTraining.DauerMinuten = Convert.ToInt32(SelectedCourseSelectionInfo.Duration.TotalMinutes);
            newTraining.Kindertraining = SelectedCourseSelectionInfo.ChildrensTraining;
            newTraining.KursID = courseId;
            newTraining.Termin = SelectedDate;
            //newTraining.VHS = false; //ignore until later update
            newTraining.Zeit = SelectedCourseSelectionInfo.From;
            newTraining.WochentagID = SelectedCourseSelectionInfo.DayOfWeekId;

            return newTraining;
        }

        protected override bool CanSave()
        {
            var baseCanSave = base.CanSave();

            return baseCanSave;
        }

        #endregion
    }
}


text:
'use strict'
const moment = require('moment')
const timeouts = require('../timeouts')

exports.info = {
  desc: 'Add a timeout to a user, giving them the Muted Role',
  usage: '<id> <minutes>',
  aliases: ['mute'],
  hidden: true,
  permissions: [],
}

exports.run = (client, msg, params = []) =>
  new Promise(async (resolve, reject) => {
    // command not allowed in DMs
    if (msg.channel.type === 'dm') {
      client.utils.dmDenied(msg).then(resolve).catch(reject)
      return
    }
    // delete any timeout command messages posted in ANY channel
    msg.delete()
    // allow command only from #mod-logs
    // this means only moderators can run this command
    // so no need to role check
    if (msg.channel.id !== '252275732628242432') return
    // return usage if not enough parameters are passed
    if (params.length < 2) {
      client.utils.usage(msg, exports.info).then(resolve).catch(reject)
      return
    }
    // extract the target id and the timeout duration
    const targetId = params[0]
    const duration = params[1]
    // get the target user
    const target = msg.guild.members.cache.get(targetId)
    // tell the author if the target is not found
    if (!target) {
      msg.channel
        .send('Nobody with that ID was found. Are you sure it is correct?')
        .then(resolve)
        .catch(reject)
      return
    }
    const minutes = parseInt(duration)
    // make sure the duration is an int
    if (isNaN(minutes)) {
      // tell the author if the duration is malformed
      msg.channel
        .send('The duration must be a whole number.')
        .then(resolve)
        .catch(reject)
      return
    }
    // give the muted role to the target user
    target.roles
      .add('706906565784895509')
      .then(() => {
        // notify the author that the role has been added
        const targetString = `**${target.user.username}#${target.user.discriminator}** (${target.user.id})`
        msg.channel.send(
          `${targetString} has been timed out for **${minutes}** minute(s) by ${msg.author.username}`,
        )
        // start the timer to remove the role later
        timeouts.startTimeout(target.id, 1000 * 60 * minutes)
        // create the database entry
        // eslint-disable-next-line new-cap
        const entry = new client.mongo.timeouts({
          discordId: targetId,
          expiresAt: moment().add(minutes, 'minutes'),
          username: targetString,
        })
        // save the entry to the database
        entry.save()
      })
      .catch(reject)
  })


text:
from otp.ai.AIBase import *
from BattleBase import *
from BattleCalculatorAI import *
from toontown.toonbase.ToontownBattleGlobals import *
from SuitBattleGlobals import *
import DistributedBattleBaseAI
from direct.task import Task
from direct.directnotify import DirectNotifyGlobal
import random

class DistributedBattleAI(DistributedBattleBaseAI.DistributedBattleBaseAI):
    notify = DirectNotifyGlobal.directNotify.newCategory('DistributedBattleAI')

    def __init__(self, air, battleMgr, pos, suit, toonId, zoneId, finishCallback = None, maxSuits = 4, tutorialFlag = 0, levelFlag = 0, interactivePropTrackBonus = -1):
        DistributedBattleBaseAI.DistributedBattleBaseAI.__init__(self, air, zoneId, finishCallback, maxSuits=maxSuits, tutorialFlag=tutorialFlag, interactivePropTrackBonus=interactivePropTrackBonus)
        self.battleMgr = battleMgr
        self.pos = pos
        self.initialSuitPos = suit.getConfrontPosHpr()[0]
        self.initialToonPos = suit.getConfrontPosHpr()[0]
        self.addSuit(suit)
        self.avId = toonId
        if levelFlag == 0:
            self.addToon(toonId)
        self.faceOffToon = toonId
        self.fsm.request('FaceOff')

    def generate(self):
        DistributedBattleBaseAI.DistributedBattleBaseAI.generate(self)
        toon = simbase.air.doId2do.get(self.avId)
        if toon:
            if hasattr(self, 'doId'):
                toon.b_setBattleId(self.doId)
            else:
                toon.b_setBattleId(-1)
        self.avId = None
        return

    def faceOffDone(self):
        toonId = self.air.getAvatarIdFromSender()
        if self.ignoreFaceOffDone == 1:
            self.notify.debug('faceOffDone() - ignoring toon: %d' % toonId)
            return
        elif self.fsm.getCurrentState().getName() != 'FaceOff':
            self.notify.warning('faceOffDone() - in state: %s' % self.fsm.getCurrentState().getName())
            return
        elif self.toons.count(toonId) == 0:
            self.notify.warning('faceOffDone() - toon: %d not in toon list' % toonId)
            return
        self.notify.debug('toon: %d done facing off' % toonId)
        self.handleFaceOffDone()

    def enterFaceOff(self):
        self.notify.debug('enterFaceOff()')
        self.joinableFsm.request('Joinable')
        self.runableFsm.request('Unrunable')
        self.suits[0].releaseControl()
        timeForFaceoff = self.calcFaceoffTime(self.pos, self.initialSuitPos) + FACEOFF_TAUNT_T + SERVER_BUFFER_TIME
        if self.interactivePropTrackBonus >= 0:
            timeForFaceoff += FACEOFF_LOOK_AT_PROP_T
        self.timer.startCallback(timeForFaceoff, self.__serverFaceOffDone)
        return None

    def __serverFaceOffDone(self):
        self.notify.debug('faceoff timed out on server')
        self.ignoreFaceOffDone = 1
        self.handleFaceOffDone()

    def exitFaceOff(self):
        self.timer.stop()
        return None

    def handleFaceOffDone(self):
        self.timer.stop()
        self.activeSuits.append(self.suits[0])
        if len(self.toons) == 0:
            self.b_setState('Resume')
        elif self.faceOffToon == self.toons[0]:
            self.activeToons.append(self.toons[0])
            self.sendEarnedExperience(self.toons[0])
        self.d_setMembers()
        self.b_setState('WaitForInput')

    def localMovieDone(self, needUpdate, deadToons, deadSuits, lastActiveSuitDied):
        if len(self.toons) == 0:
            self.d_setMembers()
            self.b_setState('Resume')
        elif len(self.suits) == 0:
            for toonId in self.activeToons:
                toon = self.getToon(toonId)
                if toon:
                    self.toonItems[toonId] = self.air.questManager.recoverItems(toon, self.suitsKilled, self.zoneId)
                    if toonId in self.helpfulToons:
                        self.toonMerits[toonId] = self.air.promotionMgr.recoverMerits(toon, self.suitsKilled, self.zoneId)
                    else:
                        self.notify.debug('toon %d not helpful, skipping merits' % toonId)

            self.d_setMembers()
            self.d_setBattleExperience()
            self.b_setState('Reward')
        else:
            if needUpdate == 1:
                self.d_setMembers()
                if len(deadSuits) > 0 and lastActiveSuitDied == 0 or len(deadToons) > 0:
                    self.needAdjust = 1
            self.setState('WaitForJoin')

    def enterReward(self):
        self.notify.debug('enterReward()')
        self.joinableFsm.request('Unjoinable')
        self.runableFsm.request('Unrunable')
        self.resetResponses()
        self.assignRewards()
        self.startRewardTimer()

    def startRewardTimer(self):
        self.timer.startCallback(REWARD_TIMEOUT, self.serverRewardDone)

    def exitReward(self):
        return None

    def enterResume(self):
        self.notify.debug('enterResume()')
        self.joinableFsm.request('Unjoinable')
        self.runableFsm.request('Unrunable')
        DistributedBattleBaseAI.DistributedBattleBaseAI.enterResume(self)
        if self.finishCallback:
            self.finishCallback(self.zoneId)
        self.battleMgr.destroy(self)


text:
function AnnotationsController(canvas_id, default_config) {
    this.canvas_id = canvas_id;
    this.x_offset = undefined;
    this.y_offset = undefined;
    this.canvas = undefined;
    this.shapes_cache = {};
    this.paper_scope = new paper.PaperScope();
    // geometries appearance default configuration
    if (typeof default_config === 'undefined') {
        // to prevent errors in the following lines
        console.debug('No configuration provided, using default values for shapes config');
        default_config = {};
    }
    this.default_fill_color = (typeof default_config.fill_color === 'undefined') ? '#ffffff' : default_config.fill_color;
    this.default_fill_alpha = (typeof default_config.fill_alpha === 'undefined') ? 1 : default_config.fill_alpha;
    this.default_stroke_color = (typeof default_config.stroke_color === 'undefined') ? '#000000' : default_config.stroke_color;
    this.default_stroke_alpha = (typeof default_config.stroke_alpha === 'undefined') ? 1 : default_config.stroke_alpha;
    this.default_stroke_width = (typeof default_config.stroke_width === 'undefined') ? 20 : default_config.stroke_width;

    this.buildAnnotationsCanvas = function (viewport_controller) {
        if (this.canvas === undefined) {
            this.x_offset = viewport_controller.getImageDimensions().width / 2;
            this.y_offset = viewport_controller.getImageDimensions().height / 2;
            this.image_mpp = viewport_controller.getImageMicronsPerPixel();

            var canvas = $("#" + this.canvas_id);
            if (canvas.length === 0) {
                console.debug('Creating a new canvas');
                // create a canvas that will be used by paper.js
                $("body").append("<canvas id='" + this.canvas_id + "'></canvas>");
                this.canvas = canvas[0];
            } else {
                console.debug('Using an existing canvas');
                this.canvas = canvas[0];
            }
            var canvas_size = viewport_controller.getCanvasSize();
            $(this.canvas).width(canvas_size.width)
                .height(canvas_size.height);

            this.paper_scope.setup(this.canvas);
            // clean the canvas
            this.clear();
        } else {
            console.warn("Canvas already initialized");
        }
    };

    this._activate_paper_scope = function() {
        this.paper_scope.activate();
    };

    this.enableMouseEvents = function() {
        this._activate_paper_scope();
        $("#" + this.canvas_id).css('pointer-events', 'auto');
    };

    this.disableMouseEvents = function() {
        $("#" + this.canvas_id).css('pointer-events', 'none');
    };

    var refresh = function(global_obj, auto_refresh) {
        var r = (typeof auto_refresh === 'undefined') ? true : auto_refresh;
        if (r) {
            global_obj.refreshView();
        }
    };

    this.refreshView = function() {
        this._activate_paper_scope();
        paper.view.draw();
    };

    this.getZoom = function() {
        return this.paper_scope.getView().zoom;
    };

    this.setZoom = function(zoom_level) {
        this._activate_paper_scope();
        paper.view.setZoom(zoom_level);
    };

    this.setCenter = function(center_x, center_y) {
        this._activate_paper_scope();
        var center = new paper.Point(
            center_x - this.x_offset,
            center_y - this.y_offset
        );
        paper.view.setCenter(center);
    };

    this.shapeIdAvailable = function(shape_id) {
        return !(shape_id in this.shapes_cache);
    };

    this.changeShapeId = function(shape_id, new_shape_id) {
        var shape = this.getShape(shape_id);
        if (typeof shape !== 'undefined') {
            shape.setId(new_shape_id);
            this.shapes_cache[new_shape_id] = shape;
            delete this.shapes_cache[shape_id];
        }
    };

    this.getFirstAvailableLabel = function(id_prefix) {
        var id_counter = 1;
        var shape_id = id_prefix + '_' + id_counter;
        while (!this.shapeIdAvailable(shape_id)) {
            id_counter += 1;
            shape_id = id_prefix + '_' + id_counter;
        }
        return shape_id;
    };

    this.addShapeToCache = function(shape) {
        if (! (shape.id in this.shapes_cache)) {
            this.shapes_cache[shape.id] = shape;
            return true;
        } else {
            console.error('ID ' + shape.id + ' already in use');
            return false;
        }
    };

    this.getShape = function(shape_id) {
        if (shape_id in this.shapes_cache) {
            return this.shapes_cache[shape_id];
        } else {
            return undefined;
        }
    };

    this.getShapes = function(shapes_id) {
        var shapes = [];
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                if (shapes_id[index] in this.shapes_cache) {
                    shapes.push(this.shapes_cache[shapes_id[index]]);
                } else {
                    console.warn('There is no shape with ID ' + shapes_id[index]);
                }
            }
        } else {
            for (var sh in this.shapes_cache) {
                shapes.push(this.shapes_cache[sh]);
            }
        }
        return shapes;
    };

    this.getShapeJSON = function(shape_id) {
        if (shape_id in this.shapes_cache) {
            return this.shapes_cache[shape_id].toJSON(this.x_offset, this.y_offset);
        } else {
            return undefined;
        }
    };

    this.getShapesJSON = function(shapes_id) {
        var shapes_json = [];
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                if (shapes_id[index] in this.shapes_cache) {
                    shapes_json.push(this.getShapeJSON(shapes_id[index]));
                } else {
                    console.warn('There is no shape with ID ' + shapes_id[index]);
                }
            }
        } else {
            for (var sh in this.shapes_cache) {
                shapes_json.push(this.getShapeJSON(sh));
            }
        }
        return shapes_json;
    };

    this.getShapeDimensions = function(shape_id, decimal_digits) {
        if (shape_id in this.shapes_cache) {
            return {
                'area': this.shapes_cache[shape_id].getArea(this.image_mpp, decimal_digits),
                'perimeter': this.shapes_cache[shape_id].getPerimeter(this.image_mpp, decimal_digits)
            }
        } else {
            return undefined;
        }
    };

    this.getShapesDimensions = function(shapes_id, decimal_digits) {
        var dimensions = {};
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                if (shapes_id[index] in this.shapes_cache) {
                    dimensions[shapes_id[index]] = this.getShapeDimensions(shapes_id[index], decimal_digits);
                } else {
                    console.warn('There is no shape with ID ' + shapes_id[index]);
                }
            }
        } else {
            for (var sh in this.shapes_cache) {
                dimensions[sh] = this.getShapeDimensions(sh);
            }
        }
        return dimensions;
    };

    this.getShapeCenter = function(shape_id, apply_offset) {
        var add_offset = (typeof apply_offset === 'undefined') ? true : apply_offset;
        var shape = this.getShape(shape_id);
        if (shape !== 'undefined') {
            var x_offset = (add_offset === true) ? this.x_offset : 0;
            var y_offset = (add_offset === true) ? this.y_offset : 0;
            var shape_center = shape.getCenter();
            return {
                'x': shape_center.x + x_offset,
                'y': shape_center.y + y_offset
            }
        } else {
            return undefined;
        }
    };

    this.selectShape = function(shape_id, clear_selected, refresh_view) {
        this._activate_paper_scope();
        var clear = (typeof clear_selected === 'undefined') ? false : clear_selected;
        if (clear === true) {
            this.deselectShapes();
        }
        if (shape_id in this.shapes_cache) {
            this.shapes_cache[shape_id].select();
        }
        refresh(this, refresh_view);
    };

    this.selectShapes = function(shapes_id, clear_selected, refresh_view) {
        this._activate_paper_scope();
        var clear = (typeof clear_selected === 'undefined') ? false : clear_selected;
        if (clear === true) {
            for (var index in this.shapes_cache) {
                this.deselectShape(shapes_id[index]);
            }
        }
        if (typeof shapes_id !== 'undefined') {
            for (var sh in shapes_id) {
                this.selectShape(sh, false, false);
            }
        } else {
            for (var sh in this.shapes_cache) {
                this.selectShape(sh, false, false);
            }
        }
        refresh(this, refresh_view);
    };

    this.enableEventsOnShapes = function(shapes_id, events) {
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                if (shapes_id[index] in this.shapes_cache) {
                    this.shapes_cache[shapes_id[index]].enableEvents(events);
                } else {
                    console.warn('There is no shape with ID ' + shapes_id[index]);
                }
            }
        } else {
            for (var sh in this.shapes_cache) {
                this.shapes_cache[sh].enableEvents(events);
            }
        }
    };

    this.disableEventsOnShapes = function(shapes_id, events) {
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                if (shapes_id[index] in this.shapes_cache) {
                    this.shapes_cache[shapes_id[index]].disableEvents(events);
                } else {
                    console.warn('There is no shape with ID ' + shapes_id[index]);
                }
            }
        } else {
            for (var sh in this.shapes_cache) {
                this.shapes_cache[sh].disableEvents(events);
            }
        }
    };

    this.deselectShape = function(shape_id, refresh_view) {
        this._activate_paper_scope();
        if (shape_id in this.shapes_cache) {
            this.shapes_cache[shape_id].deselect();
        }
        refresh(this, refresh_view);
    };

    this.deselectShapes = function (shapes_id, refresh_view) {
        this._activate_paper_scope();
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                this.deselectShape(shapes_id[index], false);
            }
        } else {
            for (var sh in this.shapes_cache) {
                this.deselectShape(sh, false);
            }
        }
        refresh(this, refresh_view);
    };

    this.showShape = function(shape_id, refresh_view) {
        this._activate_paper_scope();
        if (shape_id in this.shapes_cache) {
            this.shapes_cache[shape_id].show();
        }
        refresh(this, refresh_view);
    };

    this.showShapes = function(shapes_id, refresh_view) {
        this._activate_paper_scope();
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                this.showShape(shapes_id[index], false);
            }
        } else {
            for (var sh in this.shapes_cache) {
                this.showShape(sh, false);
            }
        }
        refresh(this, refresh_view);
    };

    this.hideShape = function(shape_id, refresh_view) {
        this._activate_paper_scope();
        if (shape_id in this.shapes_cache) {
            this.shapes_cache[shape_id].hide();
        }
        refresh(this, refresh_view);
    };

    this.hideShapes = function (shapes_id, refresh_view) {
        this._activate_paper_scope();
        if (typeof shapes_id !== 'undefined') {
            for (var index in shapes_id) {
                this.hideShape(shapes_id[index], false);
            }
        } else {
            for (var sh in this.shapes_cache) {
                this.hideShape(sh, false);
            }
        }
        refresh(this, refresh_view);
    };

    this.deleteShape = function(shape_id, refresh_view) {
        this._activate_paper_scope();
        if (shape_id in this.shapes_cache) {
            this.shapes_cache[shape_id].delete();
            delete this.shapes_cache[shape_id];
            var deleted = true;
        } else {
            var deleted = false;
        }
        refresh(this, refresh_view);
        return deleted;
    };

    this.deleteShapes = function(shapes_id, refresh_view) {
        if (typeof shapes_id !== 'undefined') {
            this._activate_paper_scope();
            for (var index in shapes_id) {
                this.deleteShape(shapes_id[index], false);
            }
            refresh(this, refresh_view);
        } else {
            this.clear(refresh_view);
        }
    };

    this.clear = function(refresh_view) {
        this._activate_paper_scope();
        for (var shape_id in this.shapes_cache) {
            this.deleteShape(shape_id, false);
        }
        refresh(this, refresh_view);
    };

    this.normalizeShapeConfig = function(conf) {
        if (typeof conf === 'undefined') {
            conf = {};
        }
        return {
            'fill_color': (typeof conf.fill_color === 'undefined') ? this.default_fill_color : conf.fill_color,
            'fill_alpha': (typeof  conf.fill_alpha === 'undefined') ? this.default_fill_alpha : conf.fill_alpha,
            'stroke_color': (typeof conf.stroke_color === 'undefined') ? this.default_stroke_color : conf.stroke_color,
            'stroke_alpha': (typeof conf.stroke_alpha === 'undefined') ? this.default_stroke_alpha : conf.stroke_alpha,
            'stroke_width': (typeof conf.stroke_width === 'undefined') ? this.default_stroke_width : conf.stroke_width
        };
    };

    this.drawShape = function(shape, shape_conf, refresh_view) {
        this._activate_paper_scope();
        var conf = this.normalizeShapeConfig(shape_conf);
        shape.toPaperShape();
        shape.configure(conf);
        // apply offset as a translation on the shape
        shape.transformShape(
            TransformMatrixHelper.getTranslationMatrix(-this.x_offset, -this.y_offset)
        );
        refresh(this, refresh_view);
    };

    this.drawRectangle = function(shape_id, top_left_x, top_left_y, width, height, transform,
                                  shape_conf, refresh_view) {
        var rect = new Rectangle(shape_id, top_left_x, top_left_y, width, height, transform);
        if (this.addShapeToCache(rect)) {
            this.drawShape(rect, shape_conf, refresh_view);
        }
    };

    this.drawEllipse = function(shape_id, center_x, center_y, radius_x, radius_y, transform,
                                shape_conf, refresh_view) {
        var ellipse = new Ellipse(shape_id, center_x, center_y, radius_x, radius_y, transform);
        if (this.addShapeToCache(ellipse)) {
            this.drawShape(ellipse, shape_conf, refresh_view);
        }
    };

    this.drawCircle = function(shape_id, center_x, center_y, radius, transform,
                               shape_conf, refresh_view) {
        var circle = new Circle(shape_id, center_x, center_y, radius, transform);
        if (this.addShapeToCache(circle)) {
            this.drawShape(circle, shape_conf, refresh_view);
        }
    };

    // keeping for backward compatibility
    this.drawLine = function(shape_id, from_x, from_y, to_x, to_y, transform,
                             shape_conf, refresh_view) {
        var points = [
            {'point': {'x': from_x, 'y': from_y}},
            {'point': {'x': to_x, 'y': to_y}}
        ];
        this.drawPolyline(shape_id, points, transform, shape_conf, refresh_view);
    };

    this.drawPolyline = function(shape_id, segments, transform, shape_conf, refresh_view) {
        var polyline = new Polyline(shape_id, segments, transform);
        if (this.addShapeToCache(polyline)) {
            this.drawShape(polyline, shape_conf, refresh_view);
        }
    };

    this.drawPolygon = function(shape_id, segments, transform, shape_conf, refresh_view) {
        var polygon = new Polygon(shape_id, segments, transform);
        if (this.addShapeToCache(polygon)) {
            this.drawShape(polygon, shape_conf, refresh_view);
        }
    };

    this.drawShapeFromJSON = function(shape_json, refresh_view) {
        var shape_conf = {
            'fill_color': shape_json.fill_color,
            'fill_alpha': shape_json.fill_alpha,
            'stroke_color': shape_json.stroke_color,
            'stroke_alpha': shape_json.stroke_alpha,
            'stroke_width': shape_json.stroke_width
        };
        switch (shape_json.type) {
            case 'rectangle':
                this.drawRectangle(
                    shape_json.shape_id, shape_json.origin_x, shape_json.origin_y, shape_json.width, shape_json.height,
                    TransformMatrixHelper.fromMatrixJSON(shape_json.transform), shape_conf, false
                );
                break;
            case 'ellipse':
                this.drawEllipse(
                    shape_json.shape_id, shape_json.center_x, shape_json.center_y, shape_json.radius_x, shape_json.radius_y,
                    TransformMatrixHelper.fromMatrixJSON(shape_json.transform), shape_conf, false
                );
                break;
            case 'circle':
                this.drawCircle(
                    shape_json.shape_id, shape_json.center_x, shape_json.center_y, shape_json.radius,
                    TransformMatrixHelper.fromMatrixJSON(shape_json.transform), shape_conf, false
                );
                break;
            // keeping for backward compatibility
            case 'line':
                this.drawLine(
                    shape_json.shape_id, shape_json.from_x, shape_json.from_y, shape_json.to_x, shape_json.to_y,
                    TransformMatrixHelper.fromMatrixJSON(shape_json.transform), shape_conf, false
                );
                break;
            case 'polyline':
                this.drawPolyline(
                    shape_json.shape_id, shape_json.segments,
                    TransformMatrixHelper.fromMatrixJSON(shape_json.transform), shape_conf, false
                );
                break;
            case 'polygon':
                this.drawPolygon(
                    shape_json.shape_id, shape_json.segments,
                    TransformMatrixHelper.fromMatrixJSON(shape_json.transform), shape_conf, false
                );
                break;
            default:
                console.warn('Item ' + shape_json + ' is not a JSON shape representation');
        }
        if (shape_json.hidden === true) {
            this.hideShape(shape_json.shape_id);
        }
        refresh(this, refresh_view);
    };

    this.drawShapesFromJSON = function(shapes_json, refresh_view) {
        var ac = this;
        $.each(shapes_json, function(index, shape) {
            ac.drawShapeFromJSON(shape, false);
        });
        refresh(this, refresh_view);
    };

    this._replaceShapePath = function(shape_id, path) {
        console.debug('SHAPE ID IS: ' + shape_id);
        var shape_json = this.getShapeJSON(shape_id);
        console.debug(shape_json);
        shape_json.segments = path;
        this.deleteShape(shape_id);
        this.drawShapeFromJSON(shape_json);
        this.refreshView();
    };

    this.intersectShapes = function(shape1, shape2, replace_shape_1, replace_shape_2,
                                    clear_intersection, filter_intersection) {
        if (
            shape1.intersectsShape(shape2) === true ||
            shape1.containsShape(shape2) === true ||
            shape2.containsShape(shape1) === true
        ) {
            var remove_intersection = typeof clear_intersection === 'undefined' ? true : clear_intersection;
            var keep_bigger_intersection = typeof filter_intersection === 'undefined' ? false : filter_intersection;
            var intersection = shape1.getIntersection(shape2 , !(remove_intersection));
            if (keep_bigger_intersection === true) {
                intersection = ShapeConverter.keepBiggerShape(intersection);
            }
            var intersection_path = ShapeConverter.extractPathSegments(intersection,
                this.x_offset, this.y_offset);
            if (replace_shape_1 === true) {
                this._replaceShapePath(shape1.id, intersection_path);
            } else if (replace_shape_2 === true) {
                this._replaceShapePath(shape2.id, intersection_path);
            }
        } else {
            console.warn('No intersection between the two shapes');
        }
    };
}


text:
const FileSystem = require('../support/file_system')
const process = require('process')
const fs = require('fs-extra')
const path = require('path')
const _ = require('lodash')
const os = require('os')

class ApplicationConfiguration {
  constructor () {
    this.__root = __dirname.replace(`${path.sep}bin${path.sep}configurations`, '')
    this.__configuration = {}
    this.__paths = {
      application: `${this.__root}/configuration`,
      global: os.homedir(),
      local: process.cwd()
    }
  }

  override (manifestJson) {
    this.__configuration = _.merge({}, this.__configuration, manifestJson)
  }

  initialize () {
    const currentFolder = process.cwd()

    let baseFolder = ''
    const parentPaths = _.map(_.compact(currentFolder.split(path.sep)), (aspect) => {
      baseFolder = `${baseFolder}${path.sep}${aspect}`
      return baseFolder
    })

    _([
      this.__paths.application,
      this.__paths.global,
      ...parentPaths,
      this.__paths.local
    ])
    .uniq()
    .map((configurationPath) => this.__vaultRCFile(configurationPath))
    .each((configurationPath) => this.__loadFile(configurationPath))

    return this
  }

  /**
   * this exists for parity in the initialize command, the ApplicationConfig is a singleton and initializes at the bottom of this file
   */
  initializeLocal () {
    // already initialized
  }

  saveLocal () {
    if (!this.hasLocalFile()) {
      this.saveLocalFile({
        sources: {},
        paths: {},
        rules: {}
      })
    }
  }

  saveGlobalFile (settings) {
    return this.saveFile(`global`, settings)
  }

  saveLocalFile (settings) {
    return this.saveFile(`local`, settings)
  }

  saveFile (type, settings) {
    const filename = this.__vaultRCFile(this.__paths[type])
    const configurationContent = this.__getFile(filename)

    return this._saveFile(filename, _.merge({}, configurationContent, settings))
  }

  _saveFile (filename, content) {
    FileSystem.writeFile(filename, JSON.stringify(content, null, 2))
    return this
  }

  hasLocalFile () {
    return fs.existsSync(this.__vaultRCFile(this.__paths['local']))
  }

  loadFile (type) {
    return this.__loadFile(this.__vaultRCFile(this.__paths[type]))
  }

  __loadFile (filename) {
    this.__configuration = _.merge(this.__configuration, this.__getFile(filename))
    return this
  }

  __vaultRCFile (configurationPath) {
    return `${configurationPath}${path.sep}.vaultrc`
  }

  __getFile (filename) {
    try {
      return JSON.parse(
        fs.readFileSync(filename).toString() || '{}'
      )
    } catch (e) {
      if (e instanceof SyntaxError) {
        console.error(`${filename} is malformed`)
      }

      return {}
    }
  }

  get (path, defaultValue = '') {
    return (path)
      ? _.get(this.__configuration, path, defaultValue)
      : this.__configuration
  }
}

module.exports = new ApplicationConfiguration().initialize()


text:
package com.alibaba.rocketmq.common.filter;

import java.util.List;

import junit.framework.Assert;

import org.junit.Test;

import com.alibaba.rocketmq.common.filter.impl.Op;
import com.alibaba.rocketmq.common.filter.impl.PolishExpr;

/**
 * @auther lansheng.zj@taobao.com
 */
public class PolishExprTest {

    private String expression = "tag1||(tag2&&tag3)&&tag4||tag5&&(tag6 && tag7)|| tag8    && tag9";
    private PolishExpr polishExpr;

    public void init() {
        polishExpr = new PolishExpr();
    }

    @Test
    public void testReversePolish() {
        List<Op> antiPolishExpression = polishExpr.reversePolish(expression);
        System.out.println(antiPolishExpression);
    }

    @Test
    public void testReversePolish_Performance() {
        // prepare
        for (int i = 0; i < 100000; i++) {
            polishExpr.reversePolish(expression);
        }

        long start = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            polishExpr.reversePolish(expression);
        }
        long cost = System.currentTimeMillis() - start;
        System.out.println(cost);
        // System.out.println(cost / 100000F);

        Assert.assertTrue(cost < 500);
    }

}


text:
.class Lcom/android/internal/telephony/gsm/GsmServiceStateTracker$4;
.super Landroid/database/ContentObserver;
.source "GsmServiceStateTracker.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;

# direct methods
.method constructor <init>(Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;Landroid/os/Handler;)V
    .locals 0
    .param p2, "x0"    # Landroid/os/Handler;

    .prologue
    .line 533
    iput-object p1, p0, Lcom/android/internal/telephony/gsm/GsmServiceStateTracker$4;->this$0:Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;

    invoke-direct {p0, p2}, Landroid/database/ContentObserver;-><init>(Landroid/os/Handler;)V

    return-void
.end method

# virtual methods
.method public onChange(Z)V
    .locals 2
    .param p1, "selfChange"    # Z

    .prologue
    .line 536
    const-string v0, "GsmServiceStateTracker"

    const-string v1, "Auto time zone state changed"

    invoke-static {v0, v1}, Landroid/telephony/Rlog;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 537
    iget-object v0, p0, Lcom/android/internal/telephony/gsm/GsmServiceStateTracker$4;->this$0:Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;

    # invokes: Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;->revertToNitzTimeZone()V
    invoke-static {v0}, Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;->access$1700(Lcom/android/internal/telephony/gsm/GsmServiceStateTracker;)V

    .line 538
    return-void
.end method


text:
<?php

namespace Indigo\Comparison;

use Codeception\TestCase\Test;

/**
 * Tests for Same
 *
 * @author Márk Sági-Kazár <mark.sagikazar@gmail.com>
 *
 * @coversDefaultClass Indigo\Type\Comparison\SameTrait
 */
class SameTest extends Test
{
    public function valueProvider()
    {
        return [
            0 => [0, 1, false],
            1 => [0, 0, true],
            2 => [1, 0, false],
            3 => [-2, -1, false],
            4 => [-1, -1, true],
            5 => [1, -1, false],
        ];
    }

    /**
     * @dataProvider valueProvider
     */
    public function testCompare($value, $other, $same)
    {
        $value = new DummyObject($value);
        $other = new DummyObject($other);

        $this->assertEquals($same, $value->isSame($other));

        if ($same) {
            $value->assertSame($other);
        }
    }

    /**
     * @expectedException Indigo\Comparison\AssertionFailedException
     */
    public function testAssertSameFail()
    {
        $value = new DummyObject(1);
        $other = new DummyObject(0);

        $value->assertSame($other);
    }
}


text:
Greater than
===
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Dependencies][dependencies-image]][dependencies-url]

> Validates if a value is greater than a comparator value.

## Installation

``` bash
$ npm install validate.io-greater-than
```

For use in the browser, use [browserify](https://github.com/substack/node-browserify).

## Usage

``` javascript
var isGreaterThan = require( 'validate.io-greater-than' );
```

#### isGreaterThan( value, comparator )

Validates if a `value` is greater than a `comparator` value.

``` javascript
var a = 10,
	b = 0;

var bool = isGreaterThan( a, b );
// returns true
```

__Note__: this method validates that both values are `numeric` before making the comparison. For non-numeric values, the method returns `false`.

## Examples

``` javascript
console.log( isGreaterThan( 2, 1 ) );
// returns true

console.log( isGreaterThan( 0, 1 ) );
// returns false
```

To run the example code from the top-level application directory,

``` bash
$ node ./examples/index.js
```

## Tests

### Unit

Unit tests use the [Mocha](http://mochajs.org) test framework with [Chai](http://chaijs.com) assertions. To run the tests, execute the following command in the top-level application directory:

``` bash
$ make test
```

All new feature development should have corresponding unit tests to validate correct functionality.

### Test Coverage

This repository uses [Istanbul](https://github.com/gotwarlost/istanbul) as its code coverage tool. To generate a test coverage report, execute the following command in the top-level application directory:

``` bash
$ make test-cov
```

Istanbul creates a `./reports/coverage` directory. To access an HTML version of the report,

``` bash
$ make view-cov
```

---
## License

[MIT license](http://opensource.org/licenses/MIT).

## Copyright

Copyright © 2014. Athan Reines.

[npm-image]: http://img.shields.io/npm/v/validate.io-greater-than.svg
[npm-url]: https://npmjs.org/package/validate.io-greater-than

[travis-image]: http://img.shields.io/travis/validate-io/greater-than/master.svg
[travis-url]: https://travis-ci.org/validate-io/greater-than

[coveralls-image]: https://img.shields.io/coveralls/validate-io/greater-than/master.svg
[coveralls-url]: https://coveralls.io/r/validate-io/greater-than?branch=master

[dependencies-image]: http://img.shields.io/david/validate-io/greater-than.svg
[dependencies-url]: https://david-dm.org/validate-io/greater-than

[dev-dependencies-image]: http://img.shields.io/david/dev/validate-io/greater-than.svg
[dev-dependencies-url]: https://david-dm.org/dev/validate-io/greater-than

[github-issues-image]: http://img.shields.io/github/issues/validate-io/greater-than.svg
[github-issues-url]: https://github.com/validate-io/greater-than/issues