text:
"""
Volume manager manages creating, attaching, detaching, and persistent storage.

Persistant storage volumes keep their state independent of instances.  You can
attach to an instance, terminate the instance, spawn a new instance (even
one from a different image) and re-attach the volume with the same data
intact.

**Related Flags**

:volume_topic:  What :mod:`rpc` topic to listen to (default: `volume`).
:volume_manager:  The module name of a class derived from
                  :class:`manager.Manager` (default:
                  :class:`nova.volume.manager.Manager`).
:storage_availability_zone:  Defaults to `nova`.
:volume_driver:  Used by :class:`Manager`.  Defaults to
                 :class:`nova.volume.driver.ISCSIDriver`.
:volume_group:  Name of the group that will contain exported volumes (default:
                `nova-volumes`)
:num_shell_tries:  Number of times to attempt to run commands (default: 3)

"""

import sys

from nova import context
from nova import exception
from nova import flags
from nova import log as logging
from nova import manager
from nova import rpc
from nova import utils
from nova.volume import volume_types

LOG = logging.getLogger('nova.volume.manager')
FLAGS = flags.FLAGS
flags.DEFINE_string('storage_availability_zone',
                    'nova',
                    'availability zone of this service')
flags.DEFINE_string('volume_driver', 'nova.volume.driver.ISCSIDriver',
                    'Driver to use for volume creation')
flags.DEFINE_boolean('use_local_volumes', True,
                     'if True, will not discover local volumes')
flags.DEFINE_boolean('volume_force_update_capabilities', False,
                     'if True will force update capabilities on each check')

class VolumeManager(manager.SchedulerDependentManager):
    """Manages attachable block storage devices."""
    def __init__(self, volume_driver=None, *args, **kwargs):
        """Load the driver from the one specified in args, or from flags."""
        if not volume_driver:
            volume_driver = FLAGS.volume_driver
        self.driver = utils.import_object(volume_driver)
        super(VolumeManager, self).__init__(service_name='volume',
                                                    *args, **kwargs)
        # NOTE(vish): Implementation specific db handling is done
        #             by the driver.
        self.driver.db = self.db
        self._last_volume_stats = []

    def init_host(self):
        """Do any initialization that needs to be run if this is a
           standalone service."""

        ctxt = context.get_admin_context()
        self.driver.do_setup(ctxt)
        self.driver.check_for_setup_error()

        volumes = self.db.volume_get_all_by_host(ctxt, self.host)
        LOG.debug(_("Re-exporting %s volumes"), len(volumes))
        for volume in volumes:
            if volume['status'] in ['available', 'in-use']:
                self.driver.ensure_export(ctxt, volume)
            else:
                LOG.info(_("volume %s: skipping export"), volume['name'])

    def create_volume(self, context, volume_id, snapshot_id=None):
        """Creates and exports the volume."""
        context = context.elevated()
        volume_ref = self.db.volume_get(context, volume_id)
        LOG.info(_("volume %s: creating"), volume_ref['name'])

        self.db.volume_update(context,
                              volume_id,
                              {'host': self.host})
        # NOTE(vish): so we don't have to get volume from db again
        #             before passing it to the driver.
        volume_ref['host'] = self.host

        try:
            vol_name = volume_ref['name']
            vol_size = volume_ref['size']
            LOG.debug(_("volume %(vol_name)s: creating lv of"
                    " size %(vol_size)sG") % locals())
            if snapshot_id == None:
                model_update = self.driver.create_volume(volume_ref)
            else:
                snapshot_ref = self.db.snapshot_get(context, snapshot_id)
                model_update = self.driver.create_volume_from_snapshot(
                    volume_ref,
                    snapshot_ref)
            if model_update:
                self.db.volume_update(context, volume_ref['id'], model_update)

            LOG.debug(_("volume %s: creating export"), volume_ref['name'])
            model_update = self.driver.create_export(context, volume_ref)
            if model_update:
                self.db.volume_update(context, volume_ref['id'], model_update)
        except Exception:
            with utils.save_and_reraise_exception():
                self.db.volume_update(context,
                                      volume_ref['id'], {'status': 'error'})
                self._notify_vsa(context, volume_ref, 'error')

        now = utils.utcnow()
        self.db.volume_update(context,
                              volume_ref['id'], {'status': 'available',
                                                 'launched_at': now})
        LOG.debug(_("volume %s: created successfully"), volume_ref['name'])
        self._notify_vsa(context, volume_ref, 'available')
        self._reset_stats()
        return volume_id

    def _notify_vsa(self, context, volume_ref, status):
        if volume_ref['volume_type_id'] is None:
            return

        if volume_types.is_vsa_drive(volume_ref['volume_type_id']):
            vsa_id = None
            for i in volume_ref.get('volume_metadata'):
                if i['key'] == 'to_vsa_id':
                    vsa_id = int(i['value'])
                    break

            if vsa_id:
                rpc.cast(context,
                         FLAGS.vsa_topic,
                         {"method": "vsa_volume_created",
                          "args": {"vol_id": volume_ref['id'],
                                   "vsa_id": vsa_id,
                                   "status": status}})

    def delete_volume(self, context, volume_id):
        """Deletes and unexports volume."""
        context = context.elevated()
        volume_ref = self.db.volume_get(context, volume_id)
        if volume_ref['attach_status'] == "attached":
            raise exception.Error(_("Volume is still attached"))
        if volume_ref['host'] != self.host:
            raise exception.Error(_("Volume is not local to this node"))

        self._reset_stats()
        try:
            LOG.debug(_("volume %s: removing export"), volume_ref['name'])
            self.driver.remove_export(context, volume_ref)
            LOG.debug(_("volume %s: deleting"), volume_ref['name'])
            self.driver.delete_volume(volume_ref)
        except exception.VolumeIsBusy, e:
            LOG.debug(_("volume %s: volume is busy"), volume_ref['name'])
            self.driver.ensure_export(context, volume_ref)
            self.db.volume_update(context, volume_ref['id'],
                                  {'status': 'available'})
            return True
        except Exception:
            with utils.save_and_reraise_exception():
                self.db.volume_update(context,
                                      volume_ref['id'],
                                      {'status': 'error_deleting'})

        self.db.volume_destroy(context, volume_id)
        LOG.debug(_("volume %s: deleted successfully"), volume_ref['name'])
        return True

    def create_snapshot(self, context, volume_id, snapshot_id):
        """Creates and exports the snapshot."""
        context = context.elevated()
        snapshot_ref = self.db.snapshot_get(context, snapshot_id)
        LOG.info(_("snapshot %s: creating"), snapshot_ref['name'])

        try:
            snap_name = snapshot_ref['name']
            LOG.debug(_("snapshot %(snap_name)s: creating") % locals())
            model_update = self.driver.create_snapshot(snapshot_ref)
            if model_update:
                self.db.snapshot_update(context, snapshot_ref['id'],
                                        model_update)

        except Exception:
            with utils.save_and_reraise_exception():
                self.db.snapshot_update(context,
                                        snapshot_ref['id'],
                                        {'status': 'error'})

        self.db.snapshot_update(context,
                                snapshot_ref['id'], {'status': 'available',
                                                     'progress': '100%'})
        LOG.debug(_("snapshot %s: created successfully"), snapshot_ref['name'])
        return snapshot_id

    def delete_snapshot(self, context, snapshot_id):
        """Deletes and unexports snapshot."""
        context = context.elevated()
        snapshot_ref = self.db.snapshot_get(context, snapshot_id)

        try:
            LOG.debug(_("snapshot %s: deleting"), snapshot_ref['name'])
            self.driver.delete_snapshot(snapshot_ref)
        except Exception:
            with utils.save_and_reraise_exception():
                self.db.snapshot_update(context,
                                        snapshot_ref['id'],
                                        {'status': 'error_deleting'})

        self.db.snapshot_destroy(context, snapshot_id)
        LOG.debug(_("snapshot %s: deleted successfully"), snapshot_ref['name'])
        return True

    def attach_volume(self, context, volume_id, instance_id, mountpoint):
        """Updates db to show volume is attached"""
        # TODO(vish): refactor this into a more general "reserve"
        self.db.volume_attached(context,
                                volume_id,
                                instance_id,
                                mountpoint)

    def detach_volume(self, context, volume_id):
        """Updates db to show volume is detached"""
        # TODO(vish): refactor this into a more general "unreserve"
        self.db.volume_detached(context, volume_id)

    def initialize_connection(self, context, volume_id, address):
        """Initialize volume to be connected from address.

        This method calls the driver initialize_connection and returns
        it to the caller.  The driver is responsible for doing any
        necessary security setup and returning a connection_info dictionary
        in the following format:
            {'driver_volume_type': driver_volume_type
             'data': data}

        driver_volume_type: a string to identify the type of volume.  This
                           can be used by the calling code to determine the
                           strategy for connecting to the volume. This could
                           be 'iscsi', 'rdb', 'sheepdog', etc.
        data: this is the data that the calling code will use to connect
              to the volume. Keep in mind that this will be serialized to
              json in various places, so it should not contain any non-json
              data types.
        """
        volume_ref = self.db.volume_get(context, volume_id)
        return self.driver.initialize_connection(volume_ref, address)

    def terminate_connection(self, context, volume_id, address):
        volume_ref = self.db.volume_get(context, volume_id)
        self.driver.terminate_connection(volume_ref, address)

    def check_for_export(self, context, instance_id):
        """Make sure whether volume is exported."""
        instance_ref = self.db.instance_get(context, instance_id)
        for volume in instance_ref['volumes']:
            self.driver.check_for_export(context, volume['id'])

    def periodic_tasks(self, context=None):
        """Tasks to be run at a periodic interval."""

        error_list = []
        try:
            self._report_driver_status()
        except Exception as ex:
            LOG.warning(_("Error during report_driver_status(): %s"),
                        unicode(ex))
            error_list.append(ex)

        super(VolumeManager, self).periodic_tasks(context)

        return error_list

    def _volume_stats_changed(self, stat1, stat2):
        if FLAGS.volume_force_update_capabilities:
            return True
        if len(stat1) != len(stat2):
            return True
        for (k, v) in stat1.iteritems():
            if (k, v) not in stat2.iteritems():
                return True
        return False

    def _report_driver_status(self):
        volume_stats = self.driver.get_volume_stats(refresh=True)
        if volume_stats:
            LOG.info(_("Checking volume capabilities"))

            if self._volume_stats_changed(self._last_volume_stats,
                                          volume_stats):
                LOG.info(_("New capabilities found: %s"), volume_stats)
                self._last_volume_stats = volume_stats

                # This will grab info about the host and queue it
                # to be sent to the Schedulers.
                self.update_service_capabilities(self._last_volume_stats)
            else:
                # avoid repeating fanouts
                self.update_service_capabilities(None)

    def _reset_stats(self):
        LOG.info(_("Clear capabilities"))
        self._last_volume_stats = []

    def notification(self, context, event):
        LOG.info(_("Notification {%s} received"), event)
        self._reset_stats()


text:
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, FlexibleContexts
  #-}

module Ethereum.Analyzer.EVM.CfgAugWithTopNPassSpec
  ( spec
  ) where

import Protolude hiding (show)

import Ckev.In.Text
import Data.Text as DT
import Ethereum.Analyzer.EVM
import Ethereum.Analyzer.TestData.Basic
import Test.Hspec

spec :: Spec
spec =
  describe "doCfgAugWithTopNPass" $ do
    it "works for hexstring1" $ do
      let result =
            unWordLabelMapM $ showText <$> doCfgAugWithTopNPass hexstring1
      DT.length result `shouldBe` 4876
    it "works for hexstring2" $ do
      let result =
            toS $
            unWordLabelMapM
              ((toS . showText <$> doCfgAugWithTopNPass hexstring2) :: WordLabelMapM Text)
      (result :: [Char]) `shouldContain` "OC: 9: JUMPI -> [L3,L5]"

redpajama_set_name: RedPajamaGithub


text:
layout: lab
permalink: /lab/
---


text:
package br.com.caelum.vraptor.validator;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.el.ELProcessor;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class MessagesTest {

	@Rule
	public ExpectedException exception = ExpectedException.none();

	private Messages messages;

	@Before
	public void setUp() {
		messages = new Messages();
	}

	@Test
	public void shouldThrowExceptionIfMessagesHasUnhandledErrors() {
		exception.expect(ValidationFailedException.class);
		exception.expectMessage(containsString("There are validation errors and you forgot to specify where to go."));

		messages.add(new SimpleMessage("Test", "Test message"));
		messages.assertAbsenceOfErrors();
	}

	@Test
	public void shouldNotThrowExceptionIfMessagesHasNoUnhandledErrors() {
		messages.add(new SimpleMessage("Test", "Test message"));
		messages.handleErrors();
		messages.assertAbsenceOfErrors();
	}

	@Test
	public void shouldNotThrowExceptionIfMessagesHasNoErrorsAndHasOtherSeverityMessages() {
		messages.add(new SimpleMessage("Test", "Test warn message", Severity.WARN));
		messages.add(new SimpleMessage("Test", "Test info message", Severity.INFO));
		messages.add(new SimpleMessage("Test", "Test success message", Severity.SUCCESS));
		messages.assertAbsenceOfErrors();
	}

	@Test
	public void shouldNotThrowExceptionIfMessagesHasNoErrors() {
		messages.assertAbsenceOfErrors();
	}

	@Test
	public void shouldGroupMessagesInMapFromSameCategory() {
		messages.add(new SimpleMessage("client.name", "not null"));
		messages.add(new SimpleMessage("client.name", "not empty"));
		messages.add(new SimpleMessage("client.email", "not null"));

		MessageList messageList = (MessageList) messages.getErrors();

		List<Message> messagesName = new ArrayList<>(messageList.getGrouped().get("client.name"));
		assertThat(messagesName, hasSize(2));
		assertThat(messagesName, contains(messageList.get(0), messageList.get(1)));

		List<Message> messagesEmail = new ArrayList<>(messageList.getGrouped().get("client.email"));
		assertThat(messagesEmail, hasSize(1));
		assertThat(messagesEmail, contains(messageList.get(2)));
	}

	@Test
	public void shouldGroupMessagesFromSameCategory() {
		messages.add(new SimpleMessage("client.name", "not null"));
		messages.add(new SimpleMessage("client.name", "not empty"));
		messages.add(new SimpleMessage("client.email", "is not valid e-mail"));

		Collection<String> errors = ((MessageList) messages.getErrors()).from("client.name");
		assertThat(errors, hasSize(2));
		assertThat(errors, hasItem("not null"));
		assertThat(errors, hasItem("not empty"));
		assertThat(errors, not(hasItem("is not valid e-mail")));
	}

	@Test
	public void shouldDisplayMessagesJoiningWithCommas() {
		messages.add(new SimpleMessage("client.name", "not null"));
		messages.add(new SimpleMessage("client.name", "not empty"));

		Collection<String> errors = ((MessageList) messages.getErrors()).from("client.name");
		assertThat(errors.toString(), equalTo("not null, not empty"));
	}

	@Test
	public void testReturnMessagesBySeverity() {
		Message message0 = new SimpleMessage("client.id", "not null", Severity.ERROR);
		Message message1 = new SimpleMessage("client.name", "not null", Severity.ERROR);
		Message message2 = new SimpleMessage("client.email", "is valid", Severity.INFO);
		Message message3 = new SimpleMessage("client.email", "was not checked", Severity.WARN);

		messages.add(message0);
		messages.add(message1);
		messages.add(message2);
		messages.add(message3);

		assertThat(messages.getErrors(), contains(message0, message1));
		assertThat(messages.getInfo(), contains(message2));
		assertThat(messages.getWarnings(), contains(message3));
		assertThat(messages.getSuccess(), empty());
	}

	@Test
	public void testElExpressionGettingMessagesByCaegory() {
		messages.add(new SimpleMessage("client.id", "will generated", Severity.INFO));
		messages.add(new SimpleMessage("client.name", "not null"));
		messages.add(new SimpleMessage("client.name", "not empty"));

		ELProcessor el = new ELProcessor();
		el.defineBean("messages", messages);

		String result = el.eval("messages.errors.from('client.name')").toString();
		assertThat(result, is("not null, not empty"));

		result = el.eval("messages.errors.from('client.name').join(' - ')").toString();
		assertThat(result, is("not null - not empty"));

		result = el.eval("messages.errors.from('client.id')").toString();
		assertThat(result, isEmptyString());

		result = el.eval("messages.info.from('client.id')").toString();
		assertThat(result, is("will generated"));
	}
}


text:
package slate
package util

final case class ExternalVar[A](getter: () => A, setter: A => Unit) {
  def imap[B](to: A => B)(from: B => A): ExternalVar[B] =
    ExternalVar[B](() => to(getter()), b => setter(from(b)))
  def mod(f: A => A): Unit = setter(f(getter()))
}


text:
$(document).ready(function() {
	// ----------------------------------
	// 				Editing
	// ----------------------------------
	// Save the field before starting to edit it
	$('*[contenteditable="true"]').live('focusin', function(event) {
		$.gFormEditSave = $(this).html();
		$.gFormEditing = true;
		$.gFormEditElement = this;

		var $element = this;

		// Select all
		event.preventDefault();
		window.setTimeout(function() {
			// All browsers
			if (window.getSelection && document.createRange) {
				var $selection = window.getSelection();
				var $rangeToSelect = document.createRange();
				$rangeToSelect.selectNodeContents($element);

				$selection.removeAllRanges();
				$selection.addRange($rangeToSelect);
			}
			// IE below 9
			else if (document.body.createTextRange) {
				var $rangeToSelect = document.body.createTextRange();
				rangeToSelect.moveToElementText($element);
				rangeToSelect.select();
			}
		}, 1);

		sortableDisable();
	});

	// Reenable sortable when the mouse leaves window
	$('*[contenteditable="true"]').live('mouseout', function() {
		sortableEnable();
	});

	// Disable sortable when the mouse enters the window we're editing
	$('*[contenteditable="true"]').live('mouseover', function() {
		if ($.gFormEditing === true && this == $.gFormEditElement) {
			sortableDisable();
		}
	});

	// Calls the form action if the content was edited
	$('*[contenteditable="true"]').live('focusout', function() {
		// Be sure to remove any <br>
		$(this).find('br').replaceWith('');
		if ($.gFormEditSave != $(this).html()) {
			var $form_action = $(this).parents('form').first().prop('action');
			var $id = $(this).parent().prop('id');

			// Note that it's the parent that holds the id whereas this's id
			// holds the variable name that is being edited

			// Update the element to the database
			if ($form_action !== undefined && $id !== undefined) {
				var $form_data = {
					id: $id,
					variable_name: $(this).prop('id'),
					variable_data: $(this).html(),
					ajax: true
				};

				var $formDefault = $.gFormEditSave;
				var $this = $(this);
				var $field = $(this).prop('id');

				$.ajax({
					url: $form_action,
					type: 'POST',
					data: $form_data,
					dataType: 'json',
					success: function($json) {
						if ($json === null && $json.success === undefined) {
							addMessage('Return messages is null, contact administrator', 'error');
							return;
						}

						// Call success callback
						if ($json.success === true && typeof success_edit_callback == 'function') {
							success_edit_callback($id, $field);
						}
						// Call error callback and set to default
						else if ($json.success === false) {
							$this.html($formDefault);
							if (typeof error_edit_callback == 'function') {
								error_edit_callback($id, $field);
							}
						}

						displayAjaxReturnMessages($json);

					}
				});
			}
		}
		$.gFormEditing = false;
		$.gFormEditElement = null;

		sortableEnable();
	});

	// Handle change events, escape = cancel and restore to default. Enter = end editing and apply
	$('*[contenteditable="true"]').live('keydown', function(event) {
		// Enter pressed, end editing and focusout (focusout applies changes automatically)
		if (event.keyCode == 13) {
			event.preventDefault();
			$(this).blur();
		}
		if (event.keyCode == 27) {
			$(this).html($.gFormEditSave);
			$(this).blur();
		}
	});

	// ----------------------------------
	// 				Sortable
	// ----------------------------------
	$.gSorting = false;

	$('.sortable').sortableExtended({
		helper: fixHelper,
		distance: 15,
		start: function(event, ui) {
			$.gSorting = true;
			$.gSortId = ui.item.prop('id');
			$.gSortWidth = ui.helper.width();
			ui.item.parent().width($.gSortWidth);
			ui.placeholder.css('visibility', 'visible');
		},
		stop: function(event, ui) {
			$.gSorting = false;
			$.gSortId = false;
			ui.item.parent().width('auto');
		}
	});

	$('*[contenteditable="true"]').live('click', function(event) {
		$(this).focus();
		event.preventDefault();
	});
});

// Extended sortable that fixes droppables when they are dynamically updated
(function ($, undefined) {
	$.widget('ui.sortableExtended', $.ui.sortable, {
		_init: function() {
			this.element.data("sortable", this.element.data('sortableExtended'));
			return $.ui.sortable.prototype._init.apply(this, arguments);
		},

		updateDroppables: function(event) {
			if ($.ui.ddmanager) {
				$.ui.ddmanager.prepareOffsets(this, event);
			}
		}
	});
})(jQuery);

function fixSortableWidth() {
	var $helper = $('.ui-sortable-helper');
	if ($helper !== undefined && $helper !== null) {
		var $sorter = $helper.parent();
		if ($sorter !== undefined && $sorter !== null) {
			$sorter.width('auto');
			// Sorter is smaller reset to default width
			if ($sorter.width() <= $.gSortWidth) {
				$sorter.width($.gSortWidth);
			}
			// Sorter is larger set a new width on the sorter
			else {
				$.gSortWidth = $sorter.width();
				$sorter.width($.gSortWidth);
				$helper.width($.gSortWidth);
			}
		}
	}
}

fixHelper = function(event, ui) {
	return $(ui).clone().width($(this).width()).fadeTo(100, 0.7);
}

function sortableDisable() {
	$('.sortable').sortableExtended('option', 'disabled', true);
}

function sortableEnable() {
	$('.sortable').sortableExtended('option', 'disabled', false);
}


text:
package de.mpg.mpdl.labcam.code.data.repository;

import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by yingli on 8/10/17.
 */

public interface UploadRepository {
    Call<ResponseBody> uploadItem(
            MultipartBody.Part file,
            RequestBody json
    );
}


text:
package com.cloudTop.starshare.ui.wangyi.contact;

import android.content.Context;

import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.contact.ContactEventListener;
import com.cloudTop.starshare.ui.wangyi.contact.activity.UserProfileActivity;

/**
 * UIKit联系人列表定制展示类
 * <p/>
 * Created by huangjun on 2015/9/11.
 */
public class ContactHelper {

    public static void init() {
        setContactEventListener();
    }

    private static void setContactEventListener() {
        NimUIKit.setContactEventListener(new ContactEventListener() {
            @Override
            public void onItemClick(Context context, String account) {
                UserProfileActivity.start(context, account);
            }

            @Override
            public void onItemLongClick(Context context, String account) {

            }

            @Override
            public void onAvatarClick(Context context, String account) {
                UserProfileActivity.start(context, account);
            }
        });
    }

}


text:
import PropTypes from 'prop-types';
import React from 'react';
import {Provider} from 'react-redux';
import {Route} from 'react-router-dom';
import {ConnectedRouter} from 'react-router-redux';

import App from '../components/App';
import DevTools from './DevTools';

export default function Root({store, history}) {
    return (
        <Provider store={store}>
            <div>
                <ConnectedRouter history={history}>
                    <Route path="/" component={App}/>
                </ConnectedRouter>
                <DevTools />
            </div>
        </Provider>
    );
}

Root.propTypes = {
    store: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
};


text:
// Author(s): Sébastien Lorion

using System;

namespace NLight.Transactions
{
	/// <summary>
	/// Provides data for the <see cref="TransactionContext.Created"/> event.
	/// </summary>
	public class TransactionContextCreatedEventArgs
		: EventArgs
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="TransactionContextCreatedEventArgs"/> class.
		/// </summary>
		/// <param name="context">The context.</param>
		public TransactionContextCreatedEventArgs(TransactionContext context)
			: base()
		{
			if (context == null) throw new ArgumentNullException(nameof(context));

			this.NewTransactionContext = context;
		}

		/// <summary>
		/// Gets the newly created transaction context.
		/// </summary>
		public TransactionContext NewTransactionContext { get; internal set; }
	}
}


text:
<?php
declare(strict_types=1);

namespace Gdbots\Pbjx\Exception;

use Gdbots\Pbj\SchemaCurie;
use Gdbots\Schemas\Pbjx\Enum\Code;

final class HandlerNotFound extends \LogicException implements GdbotsPbjxException
{
    private SchemaCurie $curie;

    public function __construct(SchemaCurie $curie, ?\Throwable $previous = null)
    {
        $this->curie = $curie;
        parent::__construct(
            sprintf('ServiceLocator did not find a handler for curie [%s].', $curie->toString()),
            Code::UNIMPLEMENTED->value,
            $previous
        );
    }

    public function getSchemaCurie(): SchemaCurie
    {
        return $this->curie;
    }
}


text:
from container import *

class GraphModel(Container):
    def __init__(self,
                 stages,
                 outputStageNames,
                 costFn,
                 inputDim=0,
                 outputDim=0,
                 name=None,
                 decisionFn=None,
                 specFilename=None):
        Container.__init__(self,
                 name=name,
                 stages=stages,
                 inputNames=['input'],
                 outputStageNames=outputStageNames,
                 inputDim=inputDim,
                 outputDim=outputDim,
                 outputdEdX=True)
        self.getCost = costFn
        self.predict = decisionFn
        self.specFilename = specFilename


text:
namespace InterviewSystem.Web
{
    using System.Threading.Tasks;

    using Microsoft.AspNet.Identity;

    public class SmsService : IIdentityMessageService
    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your SMS service here to send a text message.
            return Task.FromResult(0);
        }
    }
}


text:
<?php

namespace Ekyna\Component\Commerce\Tests\Customer\Updater;

use Ekyna\Component\Commerce\Customer\Updater\CustomerUpdater;
use Ekyna\Component\Commerce\Payment\Model\PaymentStates as State;
use Ekyna\Component\Commerce\Tests\Fixture;
use Ekyna\Component\Commerce\Tests\TestCase;

/**
 * Class CustomerUpdaterTest
 * @package Ekyna\Component\Commerce\Tests\Customer\Updater
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class CustomerUpdaterTest extends TestCase
{
    /**
     * @var CustomerUpdater
     */
    private $updater;

    /**
     * @inheritDoc
     */
    protected function setUp(): void
    {
        $this->updater = new CustomerUpdater($this->getPersistenceHelperMock());
    }

    /**
     * @inheritDoc
     */
    protected function tearDown(): void
    {
        parent::tearDown();

        $this->updater = null;
    }

    /**
     * @param array $payment
     * @param array $expected
     *
     * @dataProvider provideHandlePaymentInsert
     */
    public function testHandlePaymentInsert(array $payment, array $expected): void
    {
        $customer = Fixture::customer([
            'credit_balance'      => 100,
            'outstanding_balance' => -100,
        ]);

        $payment = Fixture::payment(array_replace([
            'amount' => 50,
            'order'  => [
                'customer' => $customer,
            ],
        ], $payment));

        $this->assertEquals(!empty($expected), $this->updater->handlePaymentInsert($payment));

        $expected = array_replace(['credit' => 100, 'outstanding' => -100], $expected);

        $this->assertEquals($expected['credit'], $customer->getCreditBalance());
        $this->assertEquals($expected['outstanding'], $customer->getOutstandingBalance());
    }

    public function provideHandlePaymentInsert(): \Generator
    {
        yield 'Unhandled method' => [
            [],
            [],
        ];

        yield 'Manual method' => [
            ['method' => Fixture::PAYMENT_METHOD_MANUAL],
            [],
        ];

        yield 'Credit method, payment not accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT, 'state' => State::STATE_CANCELED],
            [],
        ];

        yield 'Credit method, payment accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 50,],
        ];

        yield 'Credit method, refund accepted' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 150,],
        ];

        yield 'Outstanding method, payment not accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING, 'state' => State::STATE_CANCELED],
            [],
        ];

        yield 'Outstanding method, payment accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING],
            ['outstanding' => -150,],
        ];
    }

    /**
     * @param array $payment
     * @param array $expected
     * @param array $changed
     *
     * @dataProvider provideHandlePaymentUpdate
     */
    public function testHandlePaymentUpdate(array $payment, array $expected, array $changed = []): void
    {
        $customer = Fixture::customer([
            'credit_balance'      => 100,
            'outstanding_balance' => -100,
        ]);

        $payment = Fixture::payment(array_replace([
            'amount' => 50,
            'order'  => [
                'customer' => $customer,
            ],
        ], $payment));

        if ($changed) {
            $this
                ->getPersistenceHelperMock()
                ->expects($this->at(0))
                ->method('getChangeSet')
                ->willReturn(isset($changed['state']) ? [$changed['state'], $payment->getState()] : []);

            $this
                ->getPersistenceHelperMock()
                ->expects($this->at(1))
                ->method('getChangeSet')
                ->willReturn(isset($changed['amount']) ? [$changed['amount'], $payment->getAmount()] : []);
        }

        $this->assertEquals(!empty($expected), $this->updater->handlePaymentUpdate($payment));

        $expected = array_replace(['credit' => 100, 'outstanding' => -100], $expected);

        $this->assertEquals($expected['credit'], $customer->getCreditBalance());
        $this->assertEquals($expected['outstanding'], $customer->getOutstandingBalance());
    }

    public function provideHandlePaymentUpdate(): \Generator
    {
        yield 'Unhandled method' => [
            [],
            [],
        ];

        yield 'Manual method' => [
            ['method' => Fixture::PAYMENT_METHOD_MANUAL],
            [],
        ];

        // CREDIT

        yield 'Credit method, payment not accepted, nothing changed' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT, 'state' => State::STATE_CANCELED],
            [],
        ];

        yield 'Credit method, payment state changed from accepted to canceled' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT, 'state' => State::STATE_CANCELED],
            ['credit' => 150,],
            ['state' => State::STATE_CAPTURED],
        ];

        yield 'Credit method, payment state changed from canceled to accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 50,],
            ['state' => State::STATE_CANCELED],
        ];

        yield 'Credit method, payment amount changed 75 to 50' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 125,],
            ['amount' => 75],
        ];

        yield 'Credit method, payment amount changed 25 to 50' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 75,],
            ['amount' => 25],
        ];

        yield 'Credit method, payment state and amount changed' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT, 'state' => State::STATE_CANCELED],
            ['credit' => 125,],
            ['state' => State::STATE_CAPTURED, 'amount' => 25],
        ];

        yield 'Credit method, refund state changed from accepted to canceled' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_CREDIT, 'state' => State::STATE_CANCELED,],
            ['credit' => 50,],
            ['state' => State::STATE_CAPTURED],
        ];

        yield 'Credit method, refund state changed from canceled to accepted' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 150,],
            ['state' => State::STATE_CANCELED],
        ];

        yield 'Credit method, refund amount changed 75 to 50' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 75,],
            ['amount' => 75],
        ];

        yield 'Credit method, refund amount changed 25 to 50' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 125,],
            ['amount' => 25],
        ];

        // OUTSTANDING

        yield 'Outstanding method, payment not accepted, nothing changed' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING, 'state' => State::STATE_CANCELED],
            [],
        ];

        yield 'Outstanding method, payment state changed from accepted to canceled' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING, 'state' => State::STATE_CANCELED],
            ['outstanding' => -50],
            ['state' => State::STATE_CAPTURED],
        ];

        yield 'Outstanding method, payment state changed from canceled to accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING],
            ['outstanding' => -150],
            ['state' => State::STATE_CANCELED],
        ];

        yield 'Outstanding method, payment amount changed 75 to 50' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING],
            ['outstanding' => -75],
            ['amount' => 75],
        ];

        yield 'Outstanding method, payment amount changed 25 to 50' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING],
            ['outstanding' => -125],
            ['amount' => 25],
        ];

        yield 'Outstanding method, payment amount and state changed' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING, 'state' => State::STATE_CANCELED],
            ['outstanding' => -75],
            ['state' => State::STATE_CAPTURED, 'amount' => 25],
        ];
    }

    /**
     * @param array $payment
     * @param array $expected
     *
     * @dataProvider provideHandlePaymentDelete
     */
    public function testHandlePaymentDelete(array $payment, array $expected): void
    {
        $customer = Fixture::customer([
            'credit_balance'      => 100,
            'outstanding_balance' => -100,
        ]);

        $payment = Fixture::payment(array_replace([
            'amount' => 50,
            'order'  => [
                'customer' => $customer,
            ],
        ], $payment));

        $this->assertEquals(!empty($expected), $this->updater->handlePaymentDelete($payment));

        $expected = array_replace(['credit' => 100, 'outstanding' => -100], $expected);

        $this->assertEquals($expected['credit'], $customer->getCreditBalance());
        $this->assertEquals($expected['outstanding'], $customer->getOutstandingBalance());
    }

    public function provideHandlePaymentDelete(): \Generator
    {
        yield 'Unhandled method' => [
            [],
            [],
        ];

        yield 'Manual method' => [
            ['method' => Fixture::PAYMENT_METHOD_MANUAL],
            [],
        ];

        yield 'Credit method, payment not accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT, 'state' => State::STATE_CANCELED],
            [],
        ];

        yield 'Credit method, payment accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 150,],
        ];

        yield 'Credit method, refund accepted' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_CREDIT],
            ['credit' => 50,],
        ];

        yield 'Outstanding method, payment not accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING, 'state' => State::STATE_CANCELED],
            [],
        ];

        yield 'Outstanding method, payment accepted' => [
            ['method' => Fixture::PAYMENT_METHOD_OUTSTANDING],
            ['outstanding' => -50,],
        ];

        yield 'Outstanding method, refund accepted' => [
            ['refund' => true, 'method' => Fixture::PAYMENT_METHOD_OUTSTANDING],
            ['outstanding' => -150,],
        ];
    }

    /**
     * @param float $amount
     * @param bool  $relative
     * @param float $expected
     *
     * @dataProvider provideUpdateCreditBalance
     */
    public function testUpdateCreditBalance(float $amount, bool $relative, float $expected): void
    {
        $customer = Fixture::customer([
            'credit_balance' => 100,
        ]);

        $this->updater->updateCreditBalance($customer, $amount, $relative);

        $this->assertEquals($expected, $customer->getCreditBalance());
    }

    public function provideUpdateCreditBalance(): array
    {
        return [
            'Absolute positive' => [50, false, 50],
            'Relative positive' => [50, true, 150],
            'Absolute negative' => [-50, false, -50],
            'Relative negative' => [-50, true, 50],
        ];
    }

    /**
     * @param float $amount
     * @param bool  $relative
     * @param float $expected
     *
     * @dataProvider provideUpdateOutstandingBalance
     */
    public function testUpdateOutstandingBalance(float $amount, bool $relative, float $expected): void
    {
        $customer = Fixture::customer([
            'outstanding_balance' => -100,
        ]);

        $this->updater->updateOutstandingBalance($customer, $amount, $relative);

        $this->assertEquals($expected, $customer->getOutstandingBalance());
    }

    public function provideUpdateOutstandingBalance(): array
    {
        return [
            'Absolute positive' => [50, false, 50],
            'Relative positive' => [50, true, -50],
            'Absolute negative' => [-50, false, -50],
            'Relative negative' => [-50, true, -150],
        ];
    }

}


text:
'use strict';
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    email: DataTypes.STRING,
    password_hash: DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    }
  });
  return User;
};


text:
screen = {}

screen.fadeOut = function(ms)
	host_fadeOutScreen(ms)
	sleep(ms)
end

screen.fadeIn= function(ms)
	host_fadeInScreen(ms)
	sleep(ms)
end


text:
Targetas base

                  Alimentación

                  Potencia

                  Sensores

                  Control

                  Diseño modular

Alimentación

Potencia

Control

Sensores

Diseño modular


text:
from . import core

# pairing-heap meld of 2 heaps; O(1)
def ph_meld(h1, h2):
    if h1 is None:
        return h2
    if h2 is None:
        return h1
    lt = core.ticks_diff(h1.ph_key, h2.ph_key) < 0
    if lt:
        if h1.ph_child is None:
            h1.ph_child = h2
        else:
            h1.ph_child_last.ph_next = h2
        h1.ph_child_last = h2
        h2.ph_next = None
        h2.ph_rightmost_parent = h1
        return h1
    else:
        h1.ph_next = h2.ph_child
        h2.ph_child = h1
        if h1.ph_next is None:
            h2.ph_child_last = h1
            h1.ph_rightmost_parent = h2
        return h2

# pairing-heap pairing operation; amortised O(log N)
def ph_pairing(child):
    heap = None
    while child is not None:
        n1 = child
        child = child.ph_next
        n1.ph_next = None
        if child is not None:
            n2 = child
            child = child.ph_next
            n2.ph_next = None
            n1 = ph_meld(n1, n2)
        heap = ph_meld(heap, n1)
    return heap

# pairing-heap delete of a node; stable, amortised O(log N)
def ph_delete(heap, node):
    if node is heap:
        child = heap.ph_child
        node.ph_child = None
        return ph_pairing(child)
    # Find parent of node
    parent = node
    while parent.ph_next is not None:
        parent = parent.ph_next
    parent = parent.ph_rightmost_parent
    # Replace node with pairing of its children
    if node is parent.ph_child and node.ph_child is None:
        parent.ph_child = node.ph_next
        node.ph_next = None
        return heap
    elif node is parent.ph_child:
        child = node.ph_child
        next = node.ph_next
        node.ph_child = None
        node.ph_next = None
        node = ph_pairing(child)
        parent.ph_child = node
    else:
        n = parent.ph_child
        while node is not n.ph_next:
            n = n.ph_next
        child = node.ph_child
        next = node.ph_next
        node.ph_child = None
        node.ph_next = None
        node = ph_pairing(child)
        if node is None:
            node = n
        else:
            n.ph_next = node
    node.ph_next = next
    if next is None:
        node.ph_rightmost_parent = parent
        parent.ph_child_last = node
    return heap

# TaskQueue class based on the above pairing-heap functions.
class TaskQueue:
    def __init__(self):
        self.heap = None

    def peek(self):
        return self.heap

    def push_sorted(self, v, key):
        v.data = None
        v.ph_key = key
        v.ph_child = None
        v.ph_next = None
        self.heap = ph_meld(v, self.heap)

    def push_head(self, v):
        self.push_sorted(v, core.ticks())

    def pop_head(self):
        v = self.heap
        self.heap = ph_pairing(self.heap.ph_child)
        return v

    def remove(self, v):
        self.heap = ph_delete(self.heap, v)

# Task class representing a coroutine, can be waited on and cancelled.
class Task:
    def __init__(self, coro, globals=None):
        self.coro = coro  # Coroutine of this Task
        self.data = None  # General data for queue it is waiting on
        self.state = True  # None, False, True or a TaskQueue instance
        self.ph_key = 0  # Pairing heap
        self.ph_child = None  # Paring heap
        self.ph_child_last = None  # Paring heap
        self.ph_next = None  # Paring heap
        self.ph_rightmost_parent = None  # Paring heap

    def __iter__(self):
        if not self.state:
            # Task finished, signal that is has been await'ed on.
            self.state = False
        elif self.state is True:
            # Allocated head of linked list of Tasks waiting on completion of this task.
            self.state = TaskQueue()
        return self

    def __next__(self):
        if not self.state:
            # Task finished, raise return value to caller so it can continue.
            raise self.data
        else:
            # Put calling task on waiting queue.
            self.state.push_head(core.cur_task)
            # Set calling task's data to this task that it waits on, to double-link it.
            core.cur_task.data = self

    def done(self):
        return not self.state

    def cancel(self):
        # Check if task is already finished.
        if not self.state:
            return False
        # Can't cancel self (not supported yet).
        if self is core.cur_task:
            raise RuntimeError("can't cancel self")
        # If Task waits on another task then forward the cancel to the one it's waiting on.
        while isinstance(self.data, Task):
            self = self.data
        # Reschedule Task as a cancelled task.
        if hasattr(self.data, "remove"):
            # Not on the main running queue, remove the task from the queue it's on.
            self.data.remove(self)
            core._task_queue.push_head(self)
        elif core.ticks_diff(self.ph_key, core.ticks()) > 0:
            # On the main running queue but scheduled in the future, so bring it forward to now.
            core._task_queue.remove(self)
            core._task_queue.push_head(self)
        self.data = core.CancelledError
        return True


text:
import sbt._
import Keys._
import org.scalatra.sbt._
import org.scalatra.sbt.PluginKeys._
import com.earldouglas.xwp.JettyPlugin
import com.mojolly.scalate.ScalatePlugin._
import ScalateKeys._

object AigarBuild extends Build {
  val Organization = "io.aigar"
  val Name = "aigar"
  val Version = "0.1.0-SNAPSHOT"
  val ScalaVersion = "2.11.8"
  val ScalatraVersion = "2.5.4"
  val JettyVersion = "9.4.9.v20180320"

  lazy val project = Project ("aigar", file("."))
    .configs(IntegrationTest)
    .settings(ScalatraPlugin.scalatraSettings)
    .settings(scalateSettings)
    .settings(Defaults.itSettings : _*)
    .settings(projectSettings)
    .enablePlugins(JettyPlugin)

  lazy val projectSettings = Seq(
      organization := Organization,
      name := Name,
      version := Version,
      scalaVersion := ScalaVersion,
      resolvers += Classpaths.typesafeReleases,
      resolvers += "Scalaz Bintray Repo" at "http://dl.bintray.com/scalaz/releases",
      libraryDependencies ++= deps,
      testOptions += Tests.Setup(_ => sys.props("testing") = "true"),
      scalateTemplates,
      javaOptions ++= Seq(
        "-Dcom.sun.management.jmxremote=true",
        "-Dcom.sun.management.jmxremote.port=1099",
        "-Dcom.sun.management.jmxremote.authenticate=false",
        "-Dcom.sun.management.jmxremote.ssl=false"
      ))

  lazy val deps = Seq(
    "org.scalatra" %% "scalatra" % ScalatraVersion,
    "org.scalatra" %% "scalatra-scalate" % ScalatraVersion,
    "org.scalatra" %% "scalatra-specs2" % ScalatraVersion % "test,it",
    "org.slf4j" % "slf4j-api" % "1.7.13" % "provided",
    "org.slf4j" % "slf4j-nop" % "1.7.13" % "test,it",
    "org.eclipse.jetty" % "jetty-plus" % JettyVersion % "container;provided",
    "org.eclipse.jetty" % "jetty-webapp" % JettyVersion % "container",
    "javax.servlet" % "javax.servlet-api" % "3.1.0" % "container;provided;test" artifacts Artifact("javax.servlet-api", "jar", "jar"),
    "org.json4s" %% "json4s-jackson" % "3.5.2",
    "org.scalatra" %% "scalatra-json" % ScalatraVersion,
    "com.typesafe.slick" %% "slick" % "3.1.1",
    "com.h2database" % "h2" % "1.4.192",
    "com.mchange" % "c3p0" % "0.9.5.1",
    "org.scalactic" %% "scalactic" % "3.0.0",
    "org.scalatest" %% "scalatest" % "3.0.0" % "test,it",
    "com.github.jpbetz" % "subspace" % "0.1.0",
    "org.mockito" % "mockito-all" % "1.8.4" % "test, it",
    "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0",
    "ch.qos.logback" % "logback-classic" % "1.2.3"
  )

  lazy val scalateTemplates =
    scalateTemplateConfig in Compile <<= (sourceDirectory in Compile){ base =>
      Seq(
        TemplateConfig(
          base / "webapp" / "WEB-INF" / "templates",
          Seq.empty,  /* default imports should be added here */
         Seq(
           Binding("context", "_root_.org.scalatra.scalate.ScalatraRenderContext", importMembers = true, isImplicit = true)
         ),  /* add extra bindings here */
        Some("templates")
        )
      )
    }
}


text:
var IGJ = IGJ || {};

IGJ.Preloader = function (game) {
    this.game = game;
    this.ready = false;
};

IGJ.Preloader.prototype = {

    preload: function () {
        this.preloadBar = this.add.sprite(0,0, 'preloaderBar');
        this.preloadBar.x = 0.5*this.game.width-0.5*this.preloadBar.width;
        this.preloadBar.y = 0.5*this.game.height+46;
        this.loadText = this.game.add.text(
            0.5*this.game.width,
            0.8*this.game.height,
             'Loading assets...',
              {font:'20px Arial', fill:'#ffff00', align: 'center'}
        );
        this.loadText.anchor.setTo(0.5,0.5);
        this.load.setPreloadSprite(this.preloadBar);

        //this.game.load.atlas('cachito','assets/img/anim.png','assets/img/anim.json');
        this.game.load.pack('game', 'assets/pack.json', null, this);
    },

    create: function () {
        this.preloadBar.cropEnabled = false;
    },

    update: function () {
        /*
        this.ready = false;
        if (!this.game.load.isLoading) {
            this.loadText.setText('Decoding audio..' + Phaser.Utils.randomChoice(' o ','(  )'));
        }

        if (this.cache.isSoundDecoded('titleMusic') && this.ready === false)
        {
            this.ready = true;
            this.game.state.start('MainMenu');
        }
        */
        this.game.state.start('Game');
    }

};


text:
FROM node:argon-slim

# File Author / Maintainer
MAINTAINER Siyuan Gao <siyuangao@gmail.com>

RUN apt-get update && \
    apt-get -y install software-properties-common git-core build-essential automake unzip python-dev python-setuptools && \
    rm -rf /var/lib/apt/lists/*

RUN git clone -b v3.8.0 https://github.com/facebook/watchman.git /tmp/watchman
WORKDIR /tmp/watchman
RUN ./autogen.sh
RUN ./configure
RUN make
RUN make install

# copy all the files into /app
COPY . /app

WORKDIR /app

RUN npm install

ENV PATH node_modules/.bin:$PATH

# Run it
cmd echo 999999 | tee -a /proc/sys/fs/inotify/max_user_watches && \
echo 999999 | tee -a /proc/sys/fs/inotify/max_queued_events && \
echo 999999 | tee -a /proc/sys/fs/inotify/max_user_instances && \
watchman shutdown-server && \
npm start

# Expose ports
EXPOSE 8080
EXPOSE 8082
EXPOSE 8081


text:
package com.aleggeup.util;

import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;

/**
 * @author Stephen Legge
 */
public final class AppOptions {

    protected static final String HELP_HEADER = "Specify options for working with photos\n";
    protected static final String HELP_FOOTER = "\n"
            + "Copyright 2014 [A Legge Up Consulting]\n"
            + "Licensed under the Apache License, Version 2.0\n"
            + "* \n"
            + "Please report issues at https://github.com/ALeggeUp/phrame-man/issues\n";

    private AppOptions() {
    }

    /**
     * This is a standard "help" option
     */
    @SuppressWarnings("static-access")
    protected static final Option HELP = OptionBuilder.withLongOpt("help").hasArg(false)
            .withDescription("Print this help").create('h');

    @SuppressWarnings("static-access")
    protected static final Option SOURCE_DIR = OptionBuilder.withLongOpt("source").hasArg(true).withArgName("DIR")
            .withDescription("Source directory").isRequired().create('s');

    @SuppressWarnings("static-access")
    protected static final Option TARGET_DIR = OptionBuilder.withLongOpt("target").hasArg(true).withArgName("DIR")
            .withDescription("Target directory").isRequired().create('t');
}


text:
<?php
namespace Topxia\WebBundle\Controller;

use Topxia\Common\Paginator;
use Topxia\Common\ArrayToolkit;
use Symfony\Component\HttpFoundation\Request;

class ThreadController extends BaseController
{
    /**
     * [listAction description]
     * @param  Request $request        [description]
     * @param  [type]  $target         [description]
     * @param  [type]  $filters        [description]
     * @return [type]  [description]
     */
    public function listAction(Request $request, $target, $filters)
    {
        $conditions = $this->convertFiltersToConditions($target['id'], $filters);

        $paginator = new Paginator(
            $request,
            $this->getThreadService()->searchThreadCount($conditions),
            20
        );

        $threads = $this->getThreadService()->searchThreads(
            $conditions,
            $filters['sort'],
            $paginator->getOffsetCount(),
            $paginator->getPerPageCount()
        );

        $userIds = array_merge(
            ArrayToolkit::column($threads, 'userId'),
            ArrayToolkit::column($threads, 'lastPostUserId')
        );
        $users = $this->getUserService()->findUsersByIds($userIds);
        return $this->render("TopxiaWebBundle:Thread:list.html.twig", array(
            'target'    => $target,
            'threads'   => $threads,
            'users'     => $users,
            'paginator' => $paginator,
            'filters'   => $filters
        ));
    }

    public function showAction(Request $request, $target, $thread, $filter = array())
    {
        $conditions = array(
            'threadId' => $thread['id'],
            'parentId' => 0
        );
        $paginator = new Paginator(
            $request,
            $this->getThreadService()->searchPostsCount(array_merge($conditions, $filter)),
            10
        );

        $posts = $this->getThreadService()->searchPosts(
            array_merge($conditions, $filter),
            array('createdTime', 'asc'),
            $paginator->getOffsetCount(),
            $paginator->getPerPageCount()
        );

        $conditions['ups_GT'] = 5;
        $goodPosts            = $this->getThreadService()->searchPosts(
            $conditions,
            array('ups' => 'DESC'),
            0,
            3
        );

        $users = $this->getUserService()->findUsersByIds(ArrayToolkit::column(array_merge($goodPosts, $posts), 'userId'));

        // $users = $this->getThreadService()->setUserBadgeTitle($thread, $users);
        $this->getThreadService()->hitThread($target['id'], $thread['id']);

        return $this->render("TopxiaWebBundle:Thread:show.html.twig", array(
            'target'    => $target,
            'thread'    => $thread,
            'author'    => $this->getUserService()->getUser($thread['userId']),
            'posts'     => $posts,
            'goodPosts' => $goodPosts,
            'users'     => $users,
            'paginator' => $paginator,
            'service'   => $this->getThreadService()
        ));
    }

    public function subpostsAction(Request $request, $threadId, $postId, $less = false)
    {
        $post = $this->getThreadService()->getPost($postId);

        $paginator = new Paginator(
            $request,
            $this->getThreadService()->findPostsCountByParentId($postId),
            10
        );

        $paginator->setBaseUrl($this->generateUrl('thread_post_subposts', array('threadId' => $post['threadId'], 'postId' => $postId)));

        $posts = $this->getThreadService()->findPostsByParentId($postId, $paginator->getOffsetCount(), $paginator->getPerPageCount());
        $users = $this->getUserService()->findUsersByIds(ArrayToolkit::column($posts, 'userId'));

        return $this->render('TopxiaWebBundle:Thread:subposts.html.twig', array(
            'parentId'  => $postId,
            'posts'     => $posts,
            'users'     => $users,
            'paginator' => $paginator,
            'less'      => $less,
            'service'   => $this->getThreadService()
        ));
    }

    public function createAction(Request $request, $target, $type = 'discussion', $thread = null)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $data               = $request->request->all();
                $data['targetType'] = $target['type'];
                $data['targetId']   = $target['id'];

                $thread = $this->getThreadService()->createThread($data);

                $attachment = $request->request->get('attachment');
                $this->getUploadFileService()->createUseFiles($attachment['fileIds'], $thread['id'], $attachment['targetType'], $attachment['type']);

                return $this->redirect($this->generateUrl("{$target['type']}_thread_show", array(
                    "{$target['type']}Id" => $thread['targetId'],
                    'threadId'            => $thread['id']
                )));
            } catch (\Exception $e) {
                return $this->createMessageResponse('error', $e->getMessage(), $this->getServiceKernel()->trans('错误提示'), 1, $request->getPathInfo());
            }
        }

        return $this->render("TopxiaWebBundle:Thread:create.html.twig", array(
            'target' => $target,
            'thread' => $thread,
            'type'   => $type
        ));
    }

    public function updateAction(Request $request, $target, $thread)
    {

        if ($request->getMethod() == 'POST') {
            try {
                $user = $this->getCurrentUser();
                $data = $request->request->all();

                if (isset($data['maxUsers']) && empty($data['maxUsers'])) {
                    $data['maxUsers'] = 0;
                }

                $thread = $this->getThreadService()->updateThread($thread['id'], $data);

                $attachment = $request->request->get('attachment');
                $this->getUploadFileService()->createUseFiles($attachment['fileIds'], $thread['id'], $attachment['targetType'], $attachment['type']);

                $message = array(
                    'title'      => $thread['title'],
                    'targetType' => $target['type'],
                    'targetId'   => $target['id'],
                    'type'       => 'type-modify',
                    'userId'     => $user['id'],
                    'userName'   => $user['nickname']);

                if ($thread['userId'] != $user['id']) {
                    $this->getNotifiactionService()->notify($thread['userId'], 'group-thread', $message);
                }

                return $this->redirect($this->generateUrl("{$target['type']}_thread_show", array(
                    "{$target['type']}Id" => $target['id'],
                    'threadId'            => $thread['id']
                )));
            } catch (\Exception $e) {
                return $this->createMessageResponse('error', $e->getMessage(), $this->getServiceKernel()->trans('错误提示'), 1, $request->getPathInfo());
            }
        }

        return $this->render("TopxiaWebBundle:Thread:create.html.twig", array(
            'target' => $target,
            'thread' => $thread
        ));
    }

    public function deleteAction(Request $request, $threadId)
    {
        $thread = $this->getThreadService()->getThread($threadId);
        $this->getThreadService()->deleteThread($threadId);

        $user = $this->getCurrentUser();

        if ($thread['userId'] != $user['id']) {
            $message = array(
                'title'    => $thread['title'],
                'type'     => 'delete',
                'userId'   => $user['id'],
                'userName' => $user['nickname']);

            $this->getNotifiactionService()->notify($thread['userId'], 'group-thread', $message);
        }

        return $this->createJsonResponse(true);
    }

    public function setStickyAction(Request $request, $threadId)
    {
        $this->getThreadService()->setThreadSticky($threadId);

        return $this->createJsonResponse(true);
    }

    public function cancelStickyAction(Request $request, $threadId)
    {
        $this->getThreadService()->cancelThreadSticky($threadId);

        return $this->createJsonResponse(true);
    }

    public function setNiceAction(Request $request, $threadId)
    {
        $this->getThreadService()->setThreadNice($threadId);

        return $this->createJsonResponse(true);
    }

    public function cancelNiceAction(Request $request, $threadId)
    {
        $this->getThreadService()->cancelThreadNice($threadId);

        return $this->createJsonResponse(true);
    }

    public function postAction(Request $request, $threadId)
    {
        $user   = $this->getCurrentUser();
        $thread = $this->getThreadService()->getThread($threadId);

        if ($request->getMethod() == 'POST') {
            $fields             = $request->request->all();
            $fields['threadId'] = $threadId;
            unset($fields['attachment']);
            $post = $this->getThreadService()->createPost($fields);

            $attachment = $request->request->get('attachment');
            $this->getUploadFileService()->createUseFiles($attachment['fileIds'], $post['id'], $attachment['targetType'], $attachment['type']);

            return $this->render('TopxiaWebBundle:Thread/Part:post-item.html.twig', array(
                'post'    => $post,
                'author'  => $user,
                'service' => $this->getThreadService()
            ));
        }
        return $this->render("TopxiaWebBundle:Thread:post.html.twig", array(
            'thread'  => $thread,
            'service' => $this->getThreadService()
        ));
    }

    public function postSaveAction(Request $request, $targetType, $targetId)
    {
        $user = $this->getCurrentUser();

        if (!$user->isLogin()) {
            $this->createAccessDeniedException('用户没有登录,不能评论!');
        }

        if ($request->getMethod() == "POST") {
            $fields = $request->request->all();

            $post['content']    = $this->autoParagraph($fields['content']);
            $post['targetType'] = $targetType;
            $post['targetId']   = $targetId;

            $post = $this->getThreadService()->createPost($post);

            if ($targetType == 'openCourse') {
                $postReplyUrl = $this->container->get('router')->generate('open_course_post_reply', array('id' => $targetId, 'postId' => $post['id'], 'targetType' => 'openCourse'));
            } else {
                $postReplyUrl = $this->container->get('router')->generate('thread_post_reply', array('threadId' => $post['threadId'], 'postId' => $post['id']));
            }

            return $this->render('TopxiaWebBundle:Thread/Part:post-item.html.twig', array(
                'post'         => $post,
                'author'       => $user,
                'service'      => $this->getThreadService(),
                'postReplyUrl' => $postReplyUrl
            ));
        }
    }

    public function postReplyAction(Request $request, $threadId, $postId, $targetType = 'classroom')
    {
        $fields               = $request->request->all();
        $fields['content']    = $this->autoParagraph($fields['content']);
        $fields['threadId']   = $threadId;
        $fields['parentId']   = $postId;
        $fields['targetType'] = $targetType;

        $post = $this->getThreadService()->createPost($fields);

        return $this->render('TopxiaWebBundle:Thread:subpost-item.html.twig', array(
            'post'    => $post,
            'author'  => $this->getCurrentUser(),
            'service' => $this->getThreadService()
        ));
    }

    public function postDeleteAction(Request $request, $threadId, $postId)
    {
        $this->getThreadService()->deletePost($postId);

        return $this->createJsonResponse(true);
    }

    public function postUpAction(Request $request, $threadId, $postId)
    {
        $result = $this->getThreadService()->voteUpPost($postId);

        return $this->createJsonResponse($result);
    }

    public function jumpAction(Request $request, $threadId)
    {
        $thread = $this->getThreadService()->getThread($threadId);

        if (empty($thread)) {
            throw $this->createNotFoundException();
        }

        return $this->redirect($this->generateUrl("{$thread['targetType']}_thread_show", array(
            "{$thread['targetType']}Id" => $thread['targetId'],
            'threadId'                  => $thread['id']
        )));
    }

    public function postJumpAction(Request $request, $threadId, $postId)
    {
        $thread = $this->getThreadService()->getThread($threadId);

        if (empty($thread)) {
            throw $this->createNotFoundException();
        }

        $post = $this->getThreadService()->getPost($postId);

        if ($post && $post['parentId']) {
            $post = $this->getThreadService()->getPost($post['parentId']);
        }

        if (empty($post)) {
            return $this->redirect($this->generateUrl("{$thread['targetType']}_thread_show", array(
                "{$thread['targetType']}Id" => $thread['targetId'],
                'threadId'                  => $thread['id']
            )));
        }

        $position = $this->getThreadService()->getPostPostionInThread($post['id']);

        $page = ceil($position / 20);

        return $this->redirect($this->generateUrl("{$thread['targetType']}_thread_show", array(
            "{$thread['targetType']}Id" => $thread['targetId'],
            'threadId'                  => $thread['id'],
            'page'                      => $page
        ))."#post-{$post['id']}");
    }

    public function userOtherThreadsBlockAction(Request $request, $thread, $userId)
    {
        $threads = $this->getThreadService()->findThreadsByTargetAndUserId(array('type' => $thread['targetType'], 'id' => $thread['targetId']), $userId, 0, 11);

        return $this->render('TopxiaWebBundle:Thread:user-threads-block.html.twig', array(
            'currentThread' => $thread,
            'threads'       => $threads
        ));
    }

    public function zeroPostThreadsBlockAction(Request $request, $thread)
    {
        $target  = array('type' => $thread['targetType'], 'id' => $thread['targetId']);
        $threads = $this->getThreadService()->findZeroPostThreadsByTarget($target, 0, 11);

        return $this->render('TopxiaWebBundle:Thread:zero-post-threads-block.html.twig', array(
            'currentThread' => $thread,
            'threads'       => $threads
        ));
    }

    protected function getThreadService()
    {
        return $this->getServiceKernel()->createService('Thread.ThreadService');
    }

    protected function convertFiltersToConditions($id, $filters)
    {
        $conditions = array('targetId' => $id);

        switch ($filters['type']) {
            case 'question':
                $conditions['type'] = 'question';
                break;
            case 'nice':
                $conditions['nice'] = 1;
                break;
            default:
                break;
        }

        return $conditions;
    }

    /**
     * This function is from Cakephp TextHelper Class
     */
    protected function autoParagraph($text)
    {
        if (trim($text) !== '') {
            $text  = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
            $text  = preg_replace("/\n\n+/", "\n\n", str_replace(array("\r\n", "\r"), "\n", $text));
            $texts = preg_split('/\n\s*\n/', $text, -1, PREG_SPLIT_NO_EMPTY);
            $text  = '';

            foreach ($texts as $txt) {
                $text .= '
'.nl2br(trim($txt, "\n"))."
\n";
            }

            $text = preg_replace('|
\s*
|', '', $text);
        }

        return $text;
    }

    protected function getTokenBucketService()
    {
        return $this->getServiceKernel()->createService('PostFilter.TokenBucketService');
    }

    protected function getNotifiactionService()
    {
        return $this->getServiceKernel()->createService('User.NotificationService');
    }

    protected function getUploadFileService()
    {
        return $this->createService('File.UploadFileService');
    }
}


text:
import crypto from 'crypto';

export function hash(password) {
  return crypto.createHash('sha256').update(password).digest('base64');
}

export function scorePassword(password) {
  let score = 0;
  if (!password) {
    return score;
  }

  // award every unique letter until 5 repetitions
  const letters = {};
  for (let i = 0; i < password.length; i += 1) {
    letters[password[i]] = (letters[password[i]] || 0) + 1;
    score += 5.0 / letters[password[i]];
  }

  // bonus points for mixing it up
  const variations = {
    digits: /\d/.test(password),
    lower: /[a-z]/.test(password),
    upper: /[A-Z]/.test(password),
    nonWords: /\W/.test(password),
  };

  let variationCount = 0;
  Object.keys(variations).forEach((key) => {
    variationCount += (variations[key] === true) ? 1 : 0;
  });

  score += (variationCount - 1) * 10;

  return parseInt(score, 10);
}


text:
jquery.breakpoint
=================

Custom jQuery element breakpoint event.

Dependency
----------
[window.breakpoint.js](https://github.com/changalberto/window.breakpoint.js)

Usage
-----
```javascript
$('.element').on('breakpoint', function(e){
  switch(e.breakpoint){
    case 'sm':
      // Breakpoint Logics
    break;
    case 'md':
      // Breakpoint Logics
    break;
    case 'lg':
      // Breakpoint Logics
    break;
  }
});
```


text:
This sample provides a map tool that when you left click in the view will show the map coordinates of the click location in the top left corner of the view.

View it live

```
Language:              C# 6.0
Subject:               Map Exploration
Contributor:           ArcGIS Pro SDK Team <arcgisprosdk@esri.com>
Organization:          Esri, http://www.esri.com
Date:                  11/8/2017
ArcGIS Pro:            2.1
Visual Studio:         2015, 2017
.NET Target Framework: 4.6.1
```

## Resources

* [API Reference online](http://pro.arcgis.com/en/pro-app/sdk/api-reference)
* ArcGIS Pro SDK for .NET (pro.arcgis.com)
* [arcgis-pro-sdk-community-samples](http://github.com/Esri/arcgis-pro-sdk-community-samples)
* [ArcGISPro Registry Keys](http://github.com/Esri/arcgis-pro-sdk/wiki/ArcGIS-Pro-Registry-Keys)
* [FAQ](http://github.com/Esri/arcgis-pro-sdk/wiki/FAQ)
* [ArcGIS Pro SDK icons](https://github.com/Esri/arcgis-pro-sdk/releases/tag/1.4.0.7198)
* [ProConcepts: ArcGIS Pro Add in Samples](https://github.com/Esri/arcgis-pro-sdk-community-samples/wiki/ProConcepts-ArcGIS-Pro-Add-in-Samples)

![ArcGIS Pro SDK for .NET Icons](https://esri.github.io/arcgis-pro-sdk/images/Home/Image-of-icons.png "ArcGIS Pro SDK Icons")

* [ProSnippets: 2.0 Migration](http://github.com/Esri/arcgis-pro-sdk/wiki/ProSnippets-Migrating-to-2.0)
* [ProSnippets: 2.0 Migration Samples](http://github.com/Esri/arcgis-pro-sdk/wiki/ProSnippets-2.0-Migration-Samples)
* [ProConcepts: 2.0 Migration](http://github.com/Esri/arcgis-pro-sdk/wiki/ProConcepts-2.0-Migration-Guide)

### Samples Data

* Sample data for ArcGIS Pro SDK Community Samples can be downloaded from the [repo releases](https://github.com/Esri/arcgis-pro-sdk-community-samples/releases) page.

## How to use the sample

1. In Visual Studio click the Build menu. Then select Build Solution.
2. Click Start button to open ArcGIS Pro.
3. ArcGIS Pro will open.
4. With a map view active go to the Add-In tab and click the Show Coordinates tool.
5. Click within the map view and the coordinates of the location you clicked will be shown in a control in the top left corner of the view.
![UI](Screenshots/screenshot.png)

[Home](https://github.com/Esri/arcgis-pro-sdk/wiki) | API Reference | [Requirements](https://github.com/Esri/arcgis-pro-sdk/wiki#requirements) | [Download](https://github.com/Esri/arcgis-pro-sdk/wiki#installing-arcgis-pro-sdk-for-net) | Samples


text:
var Rx         = require('rx');
var Observable = Rx.Observable;
var identity   = require('lodash/utility/identity');
var globRx     = Observable.fromNodeCallback(require('glob'), null, identity);
/**
 * **File:** [rx/glob.js](rx/glob.js)
 *
 * @member module:Protean.Rx.glob
 * @function
 * @param {String} pattern The glob pattern
 * @param {Object} [opts] {@link https://github.com/isaacs/node-glob#options}
 * @returns {Observable<String>} An Observable emiting the paths found
 */
module.exports = function glob (patterns, opts) {
    return globRx(patterns, opts).
        flatMap(Observable.from);
};


text:
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.Extensions.DependencyInjection;

namespace OrchardCore.Mvc
{
    /// <summary>
    /// Shares across tenants the same <see cref="IViewCompiler"/>.
    /// </summary>
    public class SharedViewCompilerProvider : IViewCompilerProvider
    {
        private object _synLock = new object();
        private static IViewCompiler _compiler;
        private readonly IServiceProvider _services;

        public SharedViewCompilerProvider(IServiceProvider services)
        {
            _services = services;
        }

        public IViewCompiler GetCompiler()
        {
            if (_compiler != null)
            {
                return _compiler;
            }

            lock (_synLock)
            {
                _compiler = _services
                    .GetServices<IViewCompilerProvider>()
                    .FirstOrDefault()
                    .GetCompiler();
            }

            return _compiler;
        }
    }
}


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
---

# Guía de lista blanca

## Perspectiva general

Listas blancas de recursos es un modelo de seguridad que controla el acceso a recursos de red externos, tales como `http://google.com` . Directiva de seguridad predeterminada de Apache Cordova permite el acceso a cualquier recurso en cualquier sitio en Internet. Antes de su aplicación a la producción, debe revisar su lista blanca y declarar el acceso a la red específica dominios y subdominios.

## Especificación

Dominio whitelisting sienta las bases para la especificación [W3C Widget acceso][1]. En la especificación de acceso Widget, el `<access>` elemento se utiliza para declarar el acceso a recursos de red específicos. Apache Cordova se extiende este concepto para permitir las listas blancas de recursos (URL) de la red individuales. En el futuro, Apache Cordova se resumen las implementaciones de las listas blancas de plataforma. Sin embargo, por ahora cada plataforma implementa sus propias listas blancas recurso o dominio. Las diferencias entre las implementaciones de la plataforma se describen más adelante en este documento.

 [1]: http://www.w3.org/TR/widgets-access/

El formato general para las entradas de la lista blanca sigue la especificación "[coinciden con patrón][2]" para Google Chrome Apps empaquetados. Los recursos son especificados por URL, pero un asterisco (*) personaje puede utilizarse como un "comodín" en varios lugares para indicar que "cualquier valor puede ir aquí". Abajo se muestran ejemplos concretos.

 [2]: http://developer.chrome.com/apps/match_patterns.html

## Sintaxis

Acceso a todos los recursos en [google.com][3]:

 [3]: http://google.com

    http://google.com/*

Acceso a todos los recursos en el seguro [google.com][4] ( `https://` ):

 [4]: https://google.com

    https://Google.com/ *

Acceso al subdominio específico [maps.google.com][5]:

 [5]: http://maps.google.com

    http://maps.google.com/*

Acceso a todos los subdominios en [google.com][3] (por ejemplo, [mail.google.com][6] y [docs.google.com][7]):

 [6]: http://mail.google.com
 [7]: http://docs.google.com

    http://*.google.com/*

Acceso a todos los recursos en [www.google.com][8] en la ruta "/ móvil":

 [8]: http://www.google.com

    http://www.google.com/mobile/*

Acceso a [google.com][3] en cualquier protocolo (por ejemplo, HTTP, HTTPS, FTP, etc.):

    *://google.com/*

Acceso a los recursos en Internet (por ejemplo, [google.com][3] y [developer.mozilla.org][9]):

 [9]: http://developer.mozilla.org

    *

## Android

### Detalles

Las reglas de las listas blancas se encuentran en `res/xml/config.xml` y declarado con el elemento`<access origin="..." />`.

Android apoya plenamente la sintaxis de las listas blancas.

### Sintaxis

Acceso a [google.com][3]:

    <access origin="http://google.com/*" />

## BlackBerry 10

### Detalles

Las reglas de las listas blancas se encuentran en `www/config.xml` y declarado con el elemento`<access origin="..." />`.

BlackBerry 10 maneja comodines diferentemente que otras plataformas de dos maneras:

1) Contenido utilizando XMLHttpRequest debe declararse explícitamente. origen = "*" no será respetado por este caso de uso. Alternativamente, puede deshabilitarse toda seguridad web usando una preferencia.

2) subdominios = "true" puede usarse en lugar de "* .dominio"

### Sintaxis

Acceso a [google.com][3]:

    <access origin="http://google.com" subdomains="false" />

Acceso a [maps.google.com][5]:

    <access origin="http://maps.google.com" subdomains="false" />

Acceso a todos los subdominios de [google.com][3]:

    <access origin="http://google.com" subdomains="true" />

Acceso a todos los dominios, incluyendo `file://` Protocolo:

    <access origin="*" subdomains="true" />

Deshabilitar la seguridad web:

    <preference name="websecurity" value="disable" />

## iOS

### Detalles

Las reglas de las listas blancas se encuentran en `AppName/config.xml` y declarado con el elemento`<access origin="..." />`.

iOS apoya plenamente la sintaxis de las listas blancas.

### Cambiado en 3.1.0:

Antes de la versión 3.1.0, Cordova-iOS incluyó algunas extensiones no estándares para el dominio whilelisting esquema apoyado por otras plataformas de Córdoba. A partir de 3.1.0, la lista blanca de iOS ahora se ajusta a la sintaxis de lista blanca de recursos descrita en la parte superior de este documento. Si actualiza desde pre-3.1.0 y usaban estas extensiones, tienes que cambiar tu `config.xml` archivo para continuar whitelisting el mismo conjunto de recursos como antes.

Específicamente, estos patrones necesitan ser actualizados:

*   " `apache.org` " (sin protocolo): anteriormente esto coincidiría con `http` , `https` , `ftp` , y `ftps` los protocolos. Cambiar a " `*://apache.org/*` " para incluir todos los protocolos, o incluir una línea para cada protocolo que necesitas ayuda.

*   " `http://apache.*` " (wildcard en el final del dominio): anteriormente esto coincidiría con todos top-level-dominios, incluyendo toda posibles TLDs de dos letras (pero no útiles dominios como. co.uk). Incluir una línea para cada TLD que usted realmente controla y necesita a la lista blanca.

*   " `h*t*://ap*he.o*g` " (comodines para letras faltantes al azar): estos ya no son soportados; cambio para incluir una línea para cada dominio y protocolo que en realidad necesita a la lista blanca.

### Sintaxis

Acceso a [google.com][3]:

    <access origin="http://google.com/*" />

## Windows Phone (7 y 8)

Las reglas de las listas blancas se encuentran en `config.xml` y declarado con el elemento`<access origin="..." />`.

### Sintaxis

Acceso a [google.com][3]:

    <access origin="http://google.com" />

## Tizen

### Detalles

Del directorio raíz de la aplicación `config.xml` archivo especifica reglas whitelisting dominio, usando el `<access origin="..." />` elemento. Para una referencia completa, vea la [documentación de Tizen acceder a recursos externos red][10].

 [10]: https://developer.tizen.org/help/topic/org.tizen.help.gs/Creating%20a%20Project.html?path=0_1_1_4#8814682_CreatingaProject-AccessingExternalNetworkResources

### Sintaxis

Acceso a [google.com][3]:

    <access origin="http://google.com" subdomains="false" />

Acceso a los seguros [google.com][4] ( `https://` ):

    <access origin="https://google.com" subdomains="false" />

Acceso a todos los subdominios de [google.com][3]:

    <access origin="http://google.com" subdomains="true" />

Acceso a todos los dominios, incluyendo `file://` Protocolo:

    <access origin="*" subdomains="true" />


text:
Validates if the given input is a prime number.

Valid values:

```js
validator.primeNumber().validate(3);
validator.primeNumber().validate(5);
validator.primeNumber().validate(7);
validator.primeNumber().validate('3');
validator.primeNumber().validate('5');
validator.primeNumber().validate('+7');
```

Invalid values:

```js
validator.primeNumber().validate('');
validator.primeNumber().validate(null);
validator.primeNumber().validate(0);
validator.primeNumber().validate(10);
validator.primeNumber().validate(25);
validator.primeNumber().validate(36);
validator.primeNumber().validate(-1);
validator.primeNumber().validate('-1');
validator.primeNumber().validate('25');
validator.primeNumber().validate('0');
validator.primeNumber().validate('a');
validator.primeNumber().validate(' ');
validator.primeNumber().validate('Foo');
```


text:
/* This file has been autogenerated by Ivory
 * Compiler version  0.1.0.5
 */
#ifndef __SEQUENCE_NUMBERED_PX4FLOW_SAMPLE_TYPES_H__
#define __SEQUENCE_NUMBERED_PX4FLOW_SAMPLE_TYPES_H__
#ifdef __cplusplus
extern "C" {
#endif
#include "ivory.h"
#include "ivory_serialize.h"
#include "sequence_num_types.h"
#include "px4flow_sample_types.h"
typedef struct sequence_numbered_px4flow_sample {
            uint32_t seqnum;
            struct px4flow_sample val;
        } sequence_numbered_px4flow_sample;
void sequence_numbered_px4flow_sample_get_le(const uint8_t *n_var0, uint32_t n_var1, struct sequence_numbered_px4flow_sample *n_var2);
void sequence_numbered_px4flow_sample_get_be(const uint8_t *n_var0, uint32_t n_var1, struct sequence_numbered_px4flow_sample *n_var2);
void sequence_numbered_px4flow_sample_set_le(uint8_t *n_var0, uint32_t n_var1, const struct sequence_numbered_px4flow_sample *n_var2);
void sequence_numbered_px4flow_sample_set_be(uint8_t *n_var0, uint32_t n_var1, const struct sequence_numbered_px4flow_sample *n_var2);

#ifdef __cplusplus
}
#endif
#endif /* __SEQUENCE_NUMBERED_PX4FLOW_SAMPLE_TYPES_H__ */


text:
package fr.pizzeria.exception;

/**
 * Exception pour les problèmes d'ajouts des clients.
 */
public class SaveClientException extends DaoException {

	private static final long serialVersionUID = 1L;

	public SaveClientException() {
		super();
	}

	public SaveClientException(String string, Throwable e) {
		super(string, e);
	}
}


text:
namespace org.apache.lucene.analysis.fa
{

	using BaseTokenStreamFactoryTestCase = org.apache.lucene.analysis.util.BaseTokenStreamFactoryTestCase;

	/// <summary>
	/// Simple tests to ensure the Persian normalization factory is working.
	/// </summary>
	public class TestPersianNormalizationFilterFactory : BaseTokenStreamFactoryTestCase
	{
	  /// <summary>
	  /// Ensure the filter actually normalizes persian text.
	  /// </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testNormalization() throws Exception
	  public virtual void testNormalization()
	  {
		Reader reader = new StringReader("های");
		TokenStream stream = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
		stream = tokenFilterFactory("PersianNormalization").create(stream);
		assertTokenStreamContents(stream, new string[] {"هاي"});
	  }

	  /// <summary>
	  /// Test that bogus arguments result in exception </summary>
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void testBogusArguments() throws Exception
	  public virtual void testBogusArguments()
	  {
		try
		{
		  tokenFilterFactory("PersianNormalization", "bogusArg", "bogusValue");
		  fail();
		}
		catch (System.ArgumentException expected)
		{
		  assertTrue(expected.Message.contains("Unknown parameters"));
		}
	  }
	}

}


text:
namespace views {

// Pure-virtual base class of an observer that can be attached to
// InkDropAnimations.
class VIEWS_EXPORT InkDropAnimationObserver {
 public:
  // Enumeration of the different reasons why an InkDropAnimation has finished.
  enum InkDropAnimationEndedReason {
    // The animation was completed successfully.
    SUCCESS,
    // The animation was stopped prematurely before reaching its final state.
    PRE_EMPTED
  };

  // Notifies the observer that an animation for |ink_drop_state| has started.
  virtual void InkDropAnimationStarted(InkDropState ink_drop_state) = 0;

  // Notifies the observer that an animation for |ink_drop_state| has finished
  // and the reason for completion is given by |reason|. If |reason| is SUCCESS
  // then the animation has progressed to its final frame however if |reason|
  // is |PRE_EMPTED| then the animation was stopped before its final frame. In
  // the event that an animation is in progress for ink drop state 's1' and an
  // animation to a new state 's2' is triggered, then
  // InkDropAnimationEnded(s1, PRE_EMPTED) will be called before
  // InkDropAnimationStarted(s2).
  virtual void InkDropAnimationEnded(InkDropState ink_drop_state,
                                     InkDropAnimationEndedReason reason) = 0;

 protected:
  InkDropAnimationObserver() {}
  virtual ~InkDropAnimationObserver() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(InkDropAnimationObserver);
};

// Returns a human readable string for |reason|.  Useful for logging.
std::string ToString(
    InkDropAnimationObserver::InkDropAnimationEndedReason reason);

}  // namespace views

#endif  // UI_VIEWS_ANIMATION_INK_DROP_ANIMATION_OBSERVER_H_


text:
package it.polito.teaching.cv;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

/**
 * The controller associated to the only view of our application. The
 * application logic is implemented here. It handles the button for opening an
 * image and perform all the operation related to the Fourier transformation and
 * antitransformation.
 *
 * @author Luigi De Russis
 * @version 1.1 (2015-11-03)
 * @since 1.0 (2013-12-11)
 *
 */
public class FourierController
{
	// images to show in the view
	@FXML
	private ImageView originalImage;
	@FXML
	private ImageView transformedImage;
	@FXML
	private ImageView antitransformedImage;
	// a FXML button for performing the transformation
	@FXML
	private Button transformButton;
	// a FXML button for performing the antitransformation
	@FXML
	private Button antitransformButton;

	// the main stage
	private Stage stage;
	// the JavaFX file chooser
	private FileChooser fileChooser;
	// support variables
	private Mat image;
	private List<Mat> planes;
	// the final complex image
	private Mat complexImage;

	/**
	 * Init the needed variables
	 */
	protected void init()
	{
		this.fileChooser = new FileChooser();
		this.image = new Mat();
		this.planes = new ArrayList<>();
		this.complexImage = new Mat();
	}

	/**
	 * Load an image from disk
	 */
	@FXML
	protected void loadImage()
	{
		// show the open dialog window
		File file = this.fileChooser.showOpenDialog(this.stage);
		if (file != null)
		{
			// read the image in gray scale
			this.image = Imgcodecs.imread(file.getAbsolutePath(), Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
			// show the image
			this.originalImage.setImage(this.mat2Image(this.image));
			// set a fixed width
			this.originalImage.setFitWidth(250);
			// preserve image ratio
			this.originalImage.setPreserveRatio(true);
			// update the UI
			this.transformButton.setDisable(false);

			// empty the image planes and the image views if it is not the first
			// loaded image
			if (!this.planes.isEmpty())
			{
				this.planes.clear();
				this.transformedImage.setImage(null);
				this.antitransformedImage.setImage(null);
			}

		}
	}

	/**
	 * The action triggered by pushing the button for apply the dft to the
	 * loaded image
	 */
	@FXML
	protected void transformImage()
	{
		// optimize the dimension of the loaded image
		Mat padded = this.optimizeImageDim(this.image);
		padded.convertTo(padded, CvType.CV_32F);
		// prepare the image planes to obtain the complex image
		this.planes.add(padded);
		this.planes.add(Mat.zeros(padded.size(), CvType.CV_32F));
		// prepare a complex image for performing the dft
		Core.merge(this.planes, this.complexImage);

		// dft
		Core.dft(this.complexImage, this.complexImage);

		// optimize the image resulting from the dft operation
		Mat magnitude = this.createOptimizedMagnitude(this.complexImage);

		// show the result of the transformation as an image
		this.transformedImage.setImage(this.mat2Image(magnitude));
		// set a fixed width
		this.transformedImage.setFitWidth(250);
		// preserve image ratio
		this.transformedImage.setPreserveRatio(true);

		// enable the button for performing the antitransformation
		this.antitransformButton.setDisable(false);
		// disable the button for applying the dft
		this.transformButton.setDisable(true);
	}

	/**
	 * The action triggered by pushing the button for apply the inverse dft to
	 * the loaded image
	 */
	@FXML
	protected void antitransformImage()
	{
		Core.idft(this.complexImage, this.complexImage);

		Mat restoredImage = new Mat();
		Core.split(this.complexImage, this.planes);
		Core.normalize(this.planes.get(0), restoredImage, 0, 255, Core.NORM_MINMAX);

		this.antitransformedImage.setImage(this.mat2Image(restoredImage));
		// set a fixed width
		this.antitransformedImage.setFitWidth(250);
		// preserve image ratio
		this.antitransformedImage.setPreserveRatio(true);

		// disable the button for performing the antitransformation
		this.antitransformButton.setDisable(true);
	}

	/**
	 * Optimize the image dimensions
	 *
	 * @param image
	 *            the {@link Mat} to optimize
	 * @return the image whose dimensions have been optimized
	 */
	private Mat optimizeImageDim(Mat image)
	{
		// init
		Mat padded = new Mat();
		// get the optimal rows size for dft
		int addPixelRows = Core.getOptimalDFTSize(image.rows());
		// get the optimal cols size for dft
		int addPixelCols = Core.getOptimalDFTSize(image.cols());
		// apply the optimal cols and rows size to the image
		Core.copyMakeBorder(image, padded, 0, addPixelRows - image.rows(), 0, addPixelCols - image.cols(),
				Core.BORDER_CONSTANT, Scalar.all(0));

		return padded;
	}

	/**
	 * Optimize the magnitude of the complex image obtained from the DFT, to
	 * improve its visualization
	 *
	 * @param complexImage
	 *            the complex image obtained from the DFT
	 * @return the optimized image
	 */
	private Mat createOptimizedMagnitude(Mat complexImage)
	{
		// init
		List<Mat> newPlanes = new ArrayList<>();
		Mat mag = new Mat();
		// split the comples image in two planes
		Core.split(complexImage, newPlanes);
		// compute the magnitude
		Core.magnitude(newPlanes.get(0), newPlanes.get(1), mag);

		// move to a logarithmic scale
		Core.add(Mat.ones(mag.size(), CvType.CV_32F), mag, mag);
		Core.log(mag, mag);
		// optionally reorder the 4 quadrants of the magnitude image
		this.shiftDFT(mag);
		// normalize the magnitude image for the visualization since both JavaFX
		// and OpenCV need images with value between 0 and 255
		// convert back to CV_8UC1
		mag.convertTo(mag, CvType.CV_8UC1);
		Core.normalize(mag, mag, 0, 255, Core.NORM_MINMAX, CvType.CV_8UC1);

		// you can also write on disk the resulting image...
		// Imgcodecs.imwrite("../magnitude.png", mag);

		return mag;
	}

	/**
	 * Reorder the 4 quadrants of the image representing the magnitude, after
	 * the DFT
	 *
	 * @param image
	 *            the {@link Mat} object whose quadrants are to reorder
	 */
	private void shiftDFT(Mat image)
	{
		image = image.submat(new Rect(0, 0, image.cols() & -2, image.rows() & -2));
		int cx = image.cols() / 2;
		int cy = image.rows() / 2;

		Mat q0 = new Mat(image, new Rect(0, 0, cx, cy));
		Mat q1 = new Mat(image, new Rect(cx, 0, cx, cy));
		Mat q2 = new Mat(image, new Rect(0, cy, cx, cy));
		Mat q3 = new Mat(image, new Rect(cx, cy, cx, cy));

		Mat tmp = new Mat();
		q0.copyTo(tmp);
		q3.copyTo(q0);
		tmp.copyTo(q3);

		q1.copyTo(tmp);
		q2.copyTo(q1);
		tmp.copyTo(q2);
	}

	/**
	 * Set the current stage (needed for the FileChooser modal window)
	 *
	 * @param stage
	 *            the stage
	 */
	public void setStage(Stage stage)
	{
		this.stage = stage;
	}

	/**
	 * Convert a Mat object (OpenCV) in the corresponding Image for JavaFX
	 *
	 * @param frame
	 *            the {@link Mat} representing the current frame
	 * @return the {@link Image} to show
	 */
	private Image mat2Image(Mat frame)
	{
		// create a temporary buffer
		MatOfByte buffer = new MatOfByte();
		// encode the frame in the buffer, according to the PNG format
		Imgcodecs.imencode(".png", frame, buffer);
		// build and return an Image created from the image encoded in the
		// buffer
		return new Image(new ByteArrayInputStream(buffer.toArray()));
	}
}