text:
<!doctype html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Aurelia • TodoMVC</title>
	<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
	<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">

		<let
			filtered-todos.bind="todos | filterTodo :filter :todos.length :filterVersion"
			active-todos.bind="todos | filterTodo :'active' :todos.length :filterVersion"></let>

todos

			<form submit.trigger="addNewTodo()">
				<input class="new-todo" placeholder="What needs to be done?" focus.one-time="true" value.bind="newTodoTitle">
			</form>

			<input id="toggle-all" class="toggle-all" type="checkbox" change.trigger="toggleAll()">
			Mark all as complete

						<input class="toggle" type="checkbox" checked.to-view="todo.isCompleted" change.trigger="toggleTodo(todo)">

						<button click.delegate="deleteTodo(todo)" class="destroy"></button>

					<input class="edit" value.bind="todo.tempTitle" focus.to-view="todo.isEditing" blur.trigger="cancelEdit(todo)" keyup.trigger="handleKeyup(todo, $event)">

All

Active

Completed

			<button class="clear-completed" click.delegate="clearCompletedTodos()" show.bind="todos.length > activeTodos.length">
				Clear completed
			</button>

Double-click to edit a todo

Created by Marcel Hoyer

Enhanced by bigopon

Part of TodoMVC

redpajama_set_name: RedPajamaGithub


text:
package org.ietf.jgss;

/**
 * This interface encapsulates the GSS-API credentials for an entity.  A
 * credential contains all the necessary cryptographic information to
 * enable the creation of a context on behalf of the entity that it
 * represents.  It may contain multiple, distinct, mechanism specific
 * credential elements, each containing information for a specific
 * security mechanism, but all referring to the same entity. A credential
 * may be used to perform context initiation, acceptance, or both.

 *
 * Credentials are instantiated using one of the
 * createCredential methods in the {@link GSSManager
 * GSSManager} class. GSS-API credential creation is not
 * intended to provide a "login to the network" function, as such a
 * function would involve the creation of new credentials rather than
 * merely acquiring a handle to existing credentials. The
 * section on credential
 * acquisition in the package level description describes
 * how existing credentials are acquired in the Java platform. GSS-API
 * implementations must impose a local access-control policy on callers to
 * prevent unauthorized callers from acquiring credentials to which they
 * are not entitled.

 *
 * Applications will create a credential object passing the desired
 * parameters.  The application can then use the query methods to obtain
 * specific information about the instantiated credential object.
 * When the credential is no longer needed, the application should call
 * the {@link #dispose() dispose} method to release any resources held by
 * the credential object and to destroy any cryptographically sensitive
 * information.

 *
 * This example code demonstrates the creation of a GSSCredential
 * implementation for a specific entity, querying of its fields, and its
 * release when it is no longer needed:

 *

 *    GSSManager manager = GSSManager.getInstance();
 *
 *    // start by creating a name object for the entity
 *    GSSName name = manager.createName("myusername", GSSName.NT_USER_NAME);
 *
 *    // now acquire credentials for the entity
 *    GSSCredential cred = manager.createCredential(name,
 *                    GSSCredential.ACCEPT_ONLY);
 *
 *    // display credential information - name, remaining lifetime,
 *    // and the mechanisms it has been acquired over
 *    System.out.println(cred.getName().toString());
 *    System.out.println(cred.getRemainingLifetime());
 *
 *    Oid [] mechs = cred.getMechs();
 *    if (mechs != null) {
 *            for (int i = 0; i < mechs.length; i++)
 *                    System.out.println(mechs[i].toString());
 *    }
 *
 *    // release system resources held by the credential
 *    cred.dispose();
 *

 *
 * @see GSSManager#createCredential(int)
 * @see GSSManager#createCredential(GSSName, int, Oid, int)
 * @see GSSManager#createCredential(GSSName, int, Oid[], int)
 * @see #dispose()
 *
 * @author Mayank Upadhyay
 * @since 1.4
 */
public interface GSSCredential extends Cloneable{

    /**
     * Credential usage flag requesting that it be usable
     * for both context initiation and acceptance.
     *
     */
    public static final int INITIATE_AND_ACCEPT = 0;

    /**
     * Credential usage flag requesting that it be usable
     * for context initiation only.
     *
     */
    public static final int INITIATE_ONLY = 1;

    /**
     * Credential usage flag requesting that it be usable
     * for context acceptance only.
     *
     */
    public static final int ACCEPT_ONLY = 2;

    /**
     * A lifetime constant representing the default credential lifetime. This
     * value it set to 0.
     */
    public static final int DEFAULT_LIFETIME = 0;

    /**
     * A lifetime constant representing indefinite credential lifetime.
     * This value must is set to the maximum integer value in Java -
     * {@link Integer#MAX_VALUE Integer.MAX_VALUE}.
     */
    public static final int INDEFINITE_LIFETIME = Integer.MAX_VALUE;

    /**
     * Releases any sensitive information that the GSSCredential object may
     * be containing.  Applications should call this method as soon as the
     * credential is no longer needed to minimize the time any sensitive
     * information is maintained.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public void dispose() throws GSSException;

    /**
     *  Retrieves the name of the entity that the credential asserts.
     *
     * @return a GSSName representing the entity
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public GSSName getName() throws GSSException;

    /**
     * Retrieves a Mechanism Name of the entity that the credential
     * asserts. This is equivalent to calling {@link
     * GSSName#canonicalize(Oid) canonicalize} on the value returned by
     * the other form of {@link #getName() getName}.
     *
     * @param mech the Oid of the mechanism for which the Mechanism Name
     * should be returned.
     * @return a GSSName representing the entity canonicalized for the
     * desired mechanism
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#BAD_MECH GSSException.BAD_MECH},
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public GSSName getName(Oid mech) throws GSSException;

    /**
     * Returns the remaining lifetime in seconds for a credential.  The
     * remaining lifetime is the minimum lifetime amongst all of the underlying
     * mechanism specific credential elements.
     *
     * @return the minimum remaining lifetime in seconds for this
     * credential. A return value of {@link #INDEFINITE_LIFETIME
     * INDEFINITE_LIFETIME} indicates that the credential does
     * not expire. A return value of 0 indicates that the credential is
     * already expired.
     *
     * @see #getRemainingInitLifetime(Oid)
     * @see #getRemainingAcceptLifetime(Oid)
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public int getRemainingLifetime() throws GSSException;

    /**
     * Returns the lifetime in seconds for the credential to remain capable
     * of initiating security contexts using the specified mechanism. This
     * method queries the initiator credential element that belongs to the
     * specified mechanism.
     *
     * @return the number of seconds remaining in the life of this credential
     * element. A return value of {@link #INDEFINITE_LIFETIME
     * INDEFINITE_LIFETIME} indicates that the credential element does not
     * expire.  A return value of 0 indicates that the credential element is
     * already expired.
     *
     * @param mech the Oid of the mechanism whose initiator credential element
     * should be queried.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#BAD_MECH GSSException.BAD_MECH},
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public int getRemainingInitLifetime(Oid mech) throws GSSException;

    /**
     * Returns the lifetime in seconds for the credential to remain capable
     * of accepting security contexts using the specified mechanism. This
     * method queries the acceptor credential element that belongs to the
     * specified mechanism.
     *
     * @return the number of seconds remaining in the life of this credential
     * element. A return value of {@link #INDEFINITE_LIFETIME
     * INDEFINITE_LIFETIME} indicates that the credential element does not
     * expire.  A return value of 0 indicates that the credential element is
     * already expired.
     *
     * @param mech the Oid of the mechanism whose acceptor credential element
     * should be queried.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#BAD_MECH GSSException.BAD_MECH},
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public int getRemainingAcceptLifetime(Oid mech) throws GSSException;

    /**
     * Returns the credential usage mode. In other words, it
     * tells us if this credential can be used for initiating or accepting
     * security contexts. It does not tell us which mechanism(s) has to be
     * used in order to do so. It is expected that an application will allow
     * the GSS-API to pick a default mechanism after calling this method.
     *
     * @return The return value will be one of {@link #INITIATE_ONLY
     * INITIATE_ONLY}, {@link #ACCEPT_ONLY ACCEPT_ONLY}, and {@link
     * #INITIATE_AND_ACCEPT INITIATE_AND_ACCEPT}.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public int getUsage() throws GSSException;

    /**
     * Returns the credential usage mode for a specific mechanism. In other
     * words, it tells us if this credential can be used
     * for initiating or accepting security contexts with a given underlying
     * mechanism.
     *
     * @return The return value will be one of {@link #INITIATE_ONLY
     * INITIATE_ONLY}, {@link #ACCEPT_ONLY ACCEPT_ONLY}, and {@link
     * #INITIATE_AND_ACCEPT INITIATE_AND_ACCEPT}.
     * @param mech the Oid of the mechanism whose credentials usage mode is
     * to be determined.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#BAD_MECH GSSException.BAD_MECH},
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public int getUsage(Oid mech) throws GSSException;

    /**
     * Returns a list of mechanisms supported by this credential. It does
     * not tell us which ones can be used to initiate
     * contexts and which ones can be used to accept contexts. The
     * application must call the {@link #getUsage(Oid) getUsage} method with
     * each of the returned Oid's to determine the possible modes of
     * usage.
     *
     * @return an array of Oid's corresponding to the supported mechanisms.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public Oid[] getMechs() throws GSSException;

    /**
     * Adds a mechanism specific credential-element to an existing
     * credential.  This method allows the construction of credentials, one
     * mechanism at a time.

     *
     * This routine is envisioned to be used mainly by context acceptors
     * during the creation of acceptor credentials which are to be used
     * with a variety of clients using different security mechanisms.

     *
     * This routine adds the new credential element "in-place".  To add the
     * element in a new credential, first call clone to obtain a
     * copy of this credential, then call its add method.

     *
     * As always, GSS-API implementations must impose a local access-control
     * policy on callers to prevent unauthorized callers from acquiring
     * credentials to which they are not entitled.
     *
     * Non-default values for initLifetime and acceptLifetime cannot always
     * be honored by the underlying mechanisms, thus callers should be
     * prepared to call {@link #getRemainingInitLifetime(Oid)
     * getRemainingInitLifetime} and {@link #getRemainingAcceptLifetime(Oid)
     * getRemainingAcceptLifetime} on the credential.
     *
     * @param name the name of the principal for whom this credential is to
     * be acquired.  Use null to specify the default
     * principal.
     * @param initLifetime the number of seconds that the credential element
     * should remain valid for initiating of security contexts. Use {@link
     * GSSCredential#INDEFINITE_LIFETIME GSSCredential.INDEFINITE_LIFETIME}
     * to request that the credentials have the maximum permitted lifetime
     * for this.  Use {@link GSSCredential#DEFAULT_LIFETIME
     * GSSCredential.DEFAULT_LIFETIME} to request default credential lifetime
     * for this.
     * @param acceptLifetime the number of seconds that the credential
     * element should remain valid for accepting security contexts. Use {@link
     * GSSCredential#INDEFINITE_LIFETIME GSSCredential.INDEFINITE_LIFETIME}
     * to request that the credentials have the maximum permitted lifetime
     * for this.  Use {@link GSSCredential#DEFAULT_LIFETIME
     * GSSCredential.DEFAULT_LIFETIME} to request default credential lifetime
     * for this.
     * @param mech the mechanism over which the credential is to be acquired.
     * @param usage the usage mode that this credential
     * element should add to the credential. The value
     * of this parameter must be one of:
     * {@link #INITIATE_AND_ACCEPT INITIATE_AND_ACCEPT},
     * {@link #ACCEPT_ONLY ACCEPT_ONLY}, and
     * {@link #INITIATE_ONLY INITIATE_ONLY}.
     *
     * @throws GSSException containing the following
     * major error codes:
     *         {@link GSSException#DUPLICATE_ELEMENT
     *                          GSSException.DUPLICATE_ELEMENT},
     *         {@link GSSException#BAD_MECH GSSException.BAD_MECH},
     *         {@link GSSException#BAD_NAMETYPE GSSException.BAD_NAMETYPE},
     *         {@link GSSException#NO_CRED GSSException.NO_CRED},
     *         {@link GSSException#CREDENTIALS_EXPIRED
     *                                  GSSException.CREDENTIALS_EXPIRED},
     *         {@link GSSException#FAILURE GSSException.FAILURE}
     */
    public void add(GSSName name, int initLifetime, int acceptLifetime,
                    Oid mech, int usage) throws GSSException;

    /**
     * Tests if this GSSCredential asserts the same entity as the supplied
     * object.  The two credentials must be acquired over the same
     * mechanisms and must refer to the same principal.
     *
     * @return true if the two GSSCredentials assert the same
     * entity; false otherwise.
     * @param another another GSSCredential for comparison to this one
     */
    public boolean equals(Object another);

    /**
     * Returns a hashcode value for this GSSCredential.
     *
     * @return a hashCode value
     */
    public int hashCode();

}


text:
using System;
using System.Linq;

using Composite.Data;
using Composite.Data.Types;

using CompositeC1Contrib.Security.Data.Types;
using CompositeC1Contrib.Workflows;

namespace CompositeC1Contrib.Security.C1Console.Workflows
{
    public class EditWebsiteSecuritySettingsWorkflow : Basic1StepDocumentWorkflow
    {
        private IPage Page => GetDataItemFromEntityToken<IPage>();

        public EditWebsiteSecuritySettingsWorkflow() : base("\\InstalledPackages\\CompositeC1Contrib.Security\\EditWebsiteSecuritySettingsWorkflow.xml") { }

        public override void OnInitialize(object sender, EventArgs e)
        {
            if (BindingExist(nameof(IWebsiteSecuritySettings.WebsiteId)))
            {
                return;
            }

            using (var data = new DataConnection())
            {
                var settings = data.Get<IWebsiteSecuritySettings>().SingleOrDefault(s => s.WebsiteId == Page.Id);
                if (settings == null)
                {
                    settings = data.CreateNew<IWebsiteSecuritySettings>();

                    settings.WebsiteId = Page.Id;

                    data.Add(settings);
                }

                Bindings.Add(nameof(IWebsiteSecuritySettings.WebsiteId), settings.WebsiteId);
                Bindings.Add(nameof(IWebsiteSecuritySettings.LoginPageId), settings.LoginPageId);
                Bindings.Add(nameof(IWebsiteSecuritySettings.ForgotPasswordPageId), settings.ForgotPasswordPageId);
                Bindings.Add(nameof(IWebsiteSecuritySettings.AfterLoginPageId), settings.AfterLoginPageId);
            }
        }

        public override void OnFinish(object sender, EventArgs e)
        {
            var loginPageId = GetBinding<Guid?>(nameof(IWebsiteSecuritySettings.LoginPageId));
            var forgotPasswordPageId = GetBinding<Guid?>(nameof(IWebsiteSecuritySettings.ForgotPasswordPageId));
            var afterLoginPageId = GetBinding<Guid?>(nameof(IWebsiteSecuritySettings.AfterLoginPageId));

            using (var data = new DataConnection())
            {
                var settings = data.Get<IWebsiteSecuritySettings>().Single(s => s.WebsiteId == Page.Id);

                settings.LoginPageId = loginPageId;
                settings.ForgotPasswordPageId = forgotPasswordPageId;
                settings.AfterLoginPageId = afterLoginPageId;

                data.Update(settings);
            }

            var treeRefresher = CreateParentTreeRefresher();
            treeRefresher.PostRefreshMesseges(EntityToken);

            SetSaveStatus(true);
        }
    }
}


text:
1. Create a new application

        mix new my_app

2. Add maru to your `mix.exs` dependencies:

        def deps do
          [ {:maru, "~> 0.4"} ]
        end

3. List `:maru` as your application dependencies:

        def application do
          [ applications: [:maru] ]
        end

### Router example

```elixir
defmodule MyAPP.Router.Homepage do
  use Maru.Router

  get do
    %{ hello: :world }
  end
end

defmodule MyAPP.API do
  use Maru.Router

  mount MyAPP.Router.Homepage

  rescue_from :all do
    status 500
    "Server Error"
  end
end
```

### Config example

```elixir
config :maru, MyAPP.API,
  http: [port: 8880]
```

### Run Server

```shell
> mix deps.get

> iex -S mix
Erlang/OTP 17 [erts-6.4] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Interactive Elixir (1.0.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Application.start :maru
:ok

> curl 127.0.0.1:8880
{"hello":"world"}
```

### Generate Router Docs

`MIX_ENV=dev` is required for generating docs.

```shell
> MIX_ENV=dev mix maru.routers
```


text:
package api.search.user;

import com.google.gson.annotations.SerializedName;

/**
 * The Class User.
 * Describes a User as returned to us in a User search
 *
 * @author Gwindow
 */
public class User {
	/** The user class. */
	@SerializedName("class")
	private String userClass;

	/** If the user is a donor. */
	private boolean donor;

	/** If the user's account is enabled */
	private boolean enabled;

	/** The user id. */
	private Number userId;

	/** The user name. */
	private String username;

	/** If the user is warned. */
	private boolean warned;

	/**
	 * Get the user class.
	 *
	 * @return the user class
	 */
	public String getUserClass() {
		return userClass;
	}

	/**
	 * Check if the user is a donor
	 *
	 * @return True if a donor
	 */
	public boolean isDonor() {
		return donor;
	}

	/**
	 * Check if the user is enabled
	 *
	 * @return True if enabled
	 */
	public boolean isEnabled() {
		return enabled;
	}

	/**
	 * Get the user id
	 *
	 * @return the user id
	 */
	public Number getUserId() {
		return userId;
	}

	/**
	 * Get the username
	 *
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * Check if the user is warned
	 *
	 * @return True if warned
	 */
	public Boolean isWarned() {
		return warned;
	}

	@Override
	public String toString() {
		return "User [getUserClass=" + getUserClass() + ", isDonor=" + isDonor() + ", isEnabled=" + isEnabled()
				+ ", getUserId=" + getUserId() + ", getUsername=" + getUsername() + ", isWarned=" + isWarned() + "]";
	}
}


text:
module Rubikon

  # This module will extend the argument array passed to the application,
  # usually ARGV. It provides functionality to parse Rubikon specific tokens
  # from the strings contained in the argument list passed to the application.
  #
  # @author Sebastian Staudt
  # @since 0.6.0
  module ArgumentVector

    # Gets the command to use from the list of arguments passed to the
    # application. The first argument matching a command name or alias will
    # cause the corresponding command to be selected.
    #
    # The command and all arguments equal to '--' will be removed from the
    # array.
    #
    # @param [Hash<Symbol, Command>] commands A list of available commands
    # @return [Command] The command found in the argument list
    # @return [Fixnum] The position of the command in the argument list
    def command!(commands)
      command = nil
      command_index = 0
      each_with_index do |arg, i|
        break if arg == '--'

        command = commands[arg.to_sym]
        unless command.nil?
          command_index = i
          delete_at i
          break
        end
      end
      delete '--'

      command ||= commands[:__default]

      return command, command_index
    end

    # Turns arguments using a special syntax into arguments that are parseable.
    #
    # Single character parameters may be joined together like '-dv'. This
    # method will split them into separate parameters like '-d -v'.
    #
    # Additionally a parameter argument may be attached to the parameter itself
    # using '=' like '--path=/tmp'. This method will also split them into
    # '--path /tmp'.
    def expand!
      each_with_index do |arg, i|
        next if !arg.start_with?('-')
        self[i] = arg.split('=', 2)
        next if arg.start_with?('--')
        self[i] = arg[1..-1].split('').uniq.map { |a| '-' + a }
      end
      flatten!
    end

    # Selects active parameters from a list of available parameters
    #
    # For every option found in the argument list {#scoped_args!} is called to
    # find the arguments for that option.
    #
    # All parameters found will be removed from the array.
    #
    # @param [Hash<Symbol, Parameter>] params A list of available parameters
    # @param [Fixnum] pos The position of the first argument that should be
    #        checked. All arguments ahead of that position will be skipped.
    # @return [Array<Parameter>] Parameters called from the given argument list
    # @see #scoped_args
    def params!(params, pos = 0)
      active_params = []
      to_delete     = []
      each_with_index do |arg, i|
        next if i < pos || arg.nil? || !arg.start_with?('-')

        param = params[(arg.start_with?('--') ? arg[2..-1] : arg[1..1]).to_sym]
        unless param.nil?
          to_delete << i
          scoped_args! param, i + 1 if param.is_a? Option
          active_params << param
        end
      end

      to_delete.reverse.each { |i| delete_at i }

      active_params
    end

    # Gets all arguments passed to a specific scope, i.e. a command or an
    # option.
    #
    # All arguments in the scope will be removed from the array.
    #
    # @param [HasArguments] has_args
    # @param [Fixnum] pos The position of the first argument that should be
    #        checked. All arguments ahead of that position will be skipped.
    def scoped_args!(has_args, pos = 0)
      to_delete = []

      each_with_index do |arg, i|
        next if i < pos
        break if arg.start_with?('-') || !has_args.send(:more_args?)

        to_delete << i
        has_args.send(:<<, arg)
      end

      to_delete.reverse.each { |i| delete_at i }
    end

  end

end


text:
define(['nexus'],function(nexus){

    return function(threadId, model){
        var _make = model.make,
            _threadId = threadId,
            _checkMake = function(msg){
                msg.model.checkMake = msg.model.make === _make;
                return msg.sendMessage('checked');
            };
        nexus.bind({
            handles: 'check make',
            handle: _checkMake,
            threadId: _threadId
        });
    };

});


text:
package user

import (
	"encoding/json"
	"net/http"

	log "github.com/Sirupsen/logrus"
	"github.com/gorilla/mux"
	"github.com/itsyouonline/identityserver/db/user"
)

// RegisterNewDigitalAssetAddress is the handler for POST /users/{username}/digitalwallet
// Register a new address
func (api UsersAPI) RegisterNewDigitalAssetAddress(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	userMgr := user.NewManager(r)

	currency := user.DigitalAssetAddress{}

	if err := json.NewDecoder(r.Body).Decode(&currency); err != nil {
		log.Debug("Error while decoding the body: ", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if !currency.Validate() {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	u, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	//Check if this label is already used
	_, err = u.GetDigitalAssetAddressByLabel(currency.Label)
	if err == nil {
		http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
		return
	}

	if err := userMgr.SaveVirtualCurrency(username, currency); err != nil {
		log.Error("ERROR while saving virtual currency:\n", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	// respond with created digital wallet.
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)

	json.NewEncoder(w).Encode(&currency)
}

// GetDigitalWallet is handler for GET /users/{username}/digitalwallet
func (api UsersAPI) GetDigitalWallet(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	userMgr := user.NewManager(r)

	useobj, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	if len(useobj.DigitalWallet) == 0 {
		useobj.DigitalWallet = make([]user.DigitalAssetAddress, 0)
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(useobj.DigitalWallet)
}

// GetDigitalAssetAddress It is handler for GET /users/{username}/digitalwallet/{label}
func (api UsersAPI) GetDigitalAssetAddress(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	label := mux.Vars(r)["label"]
	userMgr := user.NewManager(r)

	userobj, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	currency, err := userobj.GetDigitalAssetAddressByLabel(label)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(currency)
}

// UpdateDigitalAssetAddress is the handler for PUT /users/{username}/digitalwallet/{label}
// Update the label and/or value of an existing address.
func (api UsersAPI) UpdateDigitalAssetAddress(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	oldlabel := mux.Vars(r)["label"]

	newcurrency := user.DigitalAssetAddress{}
	if err := json.NewDecoder(r.Body).Decode(&newcurrency); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	if !newcurrency.Validate() {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	userMgr := user.NewManager(r)

	u, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	_, err = u.GetDigitalAssetAddressByLabel(oldlabel)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	if oldlabel != newcurrency.Label {
		_, err = u.GetDigitalAssetAddressByLabel(newcurrency.Label)
		if err == nil {
			http.Error(w, http.StatusText(http.StatusConflict), http.StatusConflict)
			return
		}
	}

	if err = userMgr.SaveVirtualCurrency(username, newcurrency); err != nil {
		log.Error("ERROR while saving address - ", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	if oldlabel != newcurrency.Label {
		if err := userMgr.RemoveVirtualCurrency(username, oldlabel); err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
	}
	w.Header().Set("Content-Type", "application/json")

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(newcurrency)
}

// DeleteDigitalAssetAddress is the handler for DELETE /users/{username}/digitalwallet/{label}
func (api UsersAPI) DeleteDigitalAssetAddress(w http.ResponseWriter, r *http.Request) {
	username := mux.Vars(r)["username"]
	label := mux.Vars(r)["label"]
	userMgr := user.NewManager(r)

	u, err := userMgr.GetByName(username)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	_, err = u.GetDigitalAssetAddressByLabel(label)
	if err != nil {
		http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
		return
	}

	if err = userMgr.RemoveVirtualCurrency(username, label); err != nil {
		log.Error("ERROR while saving address:\n", err)
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}


text:
/*jslint indent: 2 */
/*global $, window */

(function () {

  'use strict';

  var $sam, $top, parms;

  function randomOffset() {
    var range = 15;
    return Math.floor(Math.random() * range) - Math.ceil(range / 2);
  }

  function setDimensions() {
    var scaleWidth, scaleHeight, scaleRatio, newWidth, newHeight;
    scaleWidth  = $top.width()  / $sam.width();
    scaleHeight = $top.height() / $sam.height();
    scaleRatio  = Math.min(scaleWidth, scaleHeight);
    newWidth  = $sam.width()  * scaleRatio;
    newHeight = $sam.height() * scaleRatio;
    $sam.css({
      width:  newWidth,
      height: newHeight
    });
  }

  function setPosition() {
    var baseLeft, baseTop, newTop, newLeft;
    baseLeft = ($top.width()  / 2) - ($sam.width()  / 2);
    baseTop  = ($top.height() / 2) - ($sam.height() / 2);
    newTop  = baseTop  + randomOffset() + 'px';
    newLeft = baseLeft + randomOffset() + 'px';
    $sam.css({
      marginTop:  newTop,
      marginLeft: newLeft
    });
  }

  function wiggle() {
    setDimensions();
    setPosition();
  }

  function cacheQueries() {
    $sam = $('img');
    $top = $(window.top);
  }

  function setImage() {
    var $newSam;
    if (parms.img) {
      $newSam = $('<img src="' + parms.img + '">');
      $sam.replaceWith($newSam);
      $sam = $newSam;
    }
  }

  function parseParameters() {
    var rawParms;
    parms    = [];
    rawParms = window.location.href.split('?')[1];
    if (rawParms === undefined) {
      return;
    }
    $.each(rawParms.split('&'), function () {
      var pair, key, value;
      pair       = this.split('=');
      key        = pair[0];
      value      = pair[1];
      parms[key] = value;
    });
  }

  $(function () {
    parseParameters();
    cacheQueries();
    setImage();
    window.setInterval(wiggle, 50);
  });
}(this));


text:
namespace P04_HashTableTests
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using P04_HashTableImplementation;

    [TestClass]
    public class HashTableTests
    {
        [TestMethod]
        public void TestHashTableParameterlessConstructor()
        {
            int defaultCapacity = 16;
            HashTable<int, int> hashTable = new HashTable<int, int>();
            int actualCapacity = hashTable.Capacity();

            Assert.AreEqual(defaultCapacity, actualCapacity);
        }

        [TestMethod]
        public void TestHashTableConstructorWithInitialCapacityParameter()
        {
            int userDefinedCapacity = 20;
            HashTable<int, int> hashTable = new HashTable<int, int>(userDefinedCapacity);
            int actualCapacity = hashTable.Capacity();

            Assert.AreEqual(userDefinedCapacity, actualCapacity);
        }

        [TestMethod]
        public void TestIfAddingToTableWorks()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            Assert.AreEqual(countOfEntries, hashTable.Count());
        }

        [TestMethod]
        public void TestIfAfterAddingElementThatFillsMoreThan75PercentResizesTheTable()
        {
            int countOfEntries = 25;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int expectedCapacity = 32;
            int actualCapacity = hashTable.Capacity();

            Assert.AreEqual(expectedCapacity, actualCapacity);
        }

        [TestMethod]
        public void TestIfFindReturnsTheProperValue()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int indexToAssert = 4;
            int expected = indexToAssert + 100;
            int actual = hashTable.Find("Hello " + indexToAssert);

            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        [ExpectedException(typeof(KeyNotFoundException))]
        public void TestIfRemoveRemovesTheProperKeyValue()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int indexToRemove = 4;

            hashTable.Remove("Hello " + indexToRemove);
            hashTable.Find("Hello " + indexToRemove);
        }

        [TestMethod]
        public void TestIfRemoveRemovesWorksWithNonExistingKey()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            hashTable.Remove("ByeBye");
            var actualCount = hashTable.Count();

            Assert.AreEqual(countOfEntries, actualCount);
        }

        [TestMethod]
        public void TestIfCountReturnsTheProperValueWithEmptyTable()
        {
            int expectedCount = 0;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            int actualCount = hashTable.Count();

            Assert.AreEqual(expectedCount, actualCount);
        }

        [TestMethod]
        public void TestIfCountReturnsTheProperValueWithNonEmptyTable()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int actualCount = hashTable.Count();

            Assert.AreEqual(countOfEntries, actualCount);
        }

        [TestMethod]
        public void TestIfClearWorksOnEmptyHashTable()
        {
            int expectedCount = 0;
            HashTable<string, int> hashTable = new HashTable<string, int>();
            hashTable.Clear();
            int actualCount = hashTable.Count();

            Assert.AreEqual(expectedCount, actualCount);
        }

        [TestMethod]
        public void TestIfClearWorksOnNonEmptyHashTable()
        {
            int expectedCount = 0;
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            hashTable.Clear();
            int actualCount = hashTable.Count();

            Assert.AreEqual(expectedCount, actualCount);
        }

        [TestMethod]
        public void TestIfIndexerReturnsTheExpectedValueWithValidKey()
        {
            int indexToLookFor = 5;
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int expectedValue = hashTable["Hello " + indexToLookFor];

            Assert.AreEqual(expectedValue, indexToLookFor + 100);
        }

        [TestMethod]
        public void TestIfIndexerAddsWhenUsedWithNewKey()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            string newKey = "Hello 1001";
            int newValue = 201;

            hashTable[newKey] = newValue;

            var actual = hashTable[newKey];

            Assert.AreEqual(newValue, actual);
        }

        [TestMethod]
        [ExpectedException(typeof(KeyNotFoundException))]
        public void TestIfIndexerReturnsTheExpectedValueWithInvalidKey()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int expectingError = hashTable["Bye Bye"];
        }

        [TestMethod]
        public void TestIfIndexerChangesTheValueOfExistingKey()
        {
            int indexToChange = 5;
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            int expectedValue = 356;
            hashTable["Hello " + indexToChange] = expectedValue;

            int actualValue = hashTable["Hello " + indexToChange];

            Assert.AreEqual(expectedValue, actualValue);
        }

        [TestMethod]
        public void TestIfKeysReturnsAllKeys()
        {
            int countOfEntries = 3;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            var actual = hashTable.Keys().Count;

            Assert.AreEqual(countOfEntries, actual);
        }

        [TestMethod]
        public void TestIfForeachWorks()
        {
            int countOfEntries = 10;
            HashTable<string, int> hashTable = new HashTable<string, int>();

            for (int i = 1; i <= countOfEntries; i++)
            {
                hashTable.Add("Hello " + i, i + 100);
            }

            var expected = hashTable.Keys().Count;
            var actual = 0;

            foreach (var item in hashTable)
            {
                actual++;
            }

            Assert.AreEqual(expected, actual);
        }
    }
}


text:
// This file is licensed under the MIT open source license
// https://opensource.org/licenses/MIT

namespace Daemos.Mute.Expressions
{
    using Antlr4.Runtime;

    public sealed class NotNullExpression : UnaryExpression
    {
        public NotNullExpression(Expression operand, ParserRuleContext context)
            : base(new DataType(operand.Type.ClrType, false), operand, UnaryOperator.NotNull, context)
        {
        }

        public override string ToString()
        {
            return $"!!{this.Operand}";
        }
    }
}


text:
dir = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift File.join(dir, 'lib')

# Don't want puppet getting the command line arguments for rake or autotest
 ARGV.clear
#
 require 'puppet'
 gem 'rspec', '>=2.0.0'
 require 'rspec/expectations'
#
 require 'puppetlabs_spec_helper/module_spec_helper'
#


text:
//
//  DBRestClient.h
//  DropboxSDK
//
//  Created by Brian Smith on 4/9/10.
//  Copyright 2010 Dropbox, Inc. All rights reserved.
//

#import "DBSession.h"

@protocol DBRestClientDelegate;
@class DBAccountInfo;
@class DBMetadata;

@interface DBRestClient : NSObject {
    DBSession* session;
    NSString* userId;
    NSString* root;
    NSMutableSet* requests;
    /* Map from path to the load request. Needs to be expanded to a general framework for cancelling
       requests. */
    NSMutableDictionary* loadRequests;
    NSMutableDictionary* imageLoadRequests;
    NSMutableDictionary* uploadRequests;
    id<DBRestClientDelegate> delegate;
}

- (id)initWithSession:(DBSession*)session;
- (id)initWithSession:(DBSession *)session userId:(NSString *)userId;

/* Cancels all outstanding requests. No callback for those requests will be sent */
- (void)cancelAllRequests;

/* Loads metadata for the object at the given root/path and returns the result to the delegate as a
   dictionary */
- (void)loadMetadata:(NSString*)path withHash:(NSString*)hash;

- (void)loadMetadata:(NSString*)path;

/* This will load the metadata of a file at a given rev */
- (void)loadMetadata:(NSString *)path atRev:(NSString *)rev;

/* Loads a list of files (represented as DBDeltaEntry objects) that have changed since the cursor was generated */
- (void)loadDelta:(NSString *)cursor;

/* Loads the file contents at the given root/path and stores the result into destinationPath */
- (void)loadFile:(NSString *)path intoPath:(NSString *)destinationPath;

/* This will load a file as it existed at a given rev */
- (void)loadFile:(NSString *)path atRev:(NSString *)rev intoPath:(NSString *)destPath;

- (void)cancelFileLoad:(NSString*)path;

- (void)loadThumbnail:(NSString *)path ofSize:(NSString *)size intoPath:(NSString *)destinationPath;
- (void)cancelThumbnailLoad:(NSString*)path size:(NSString*)size;

/* Uploads a file that will be named filename to the given path on the server. sourcePath is the
   full path of the file you want to upload. If you are modifying a file, parentRev represents the
   rev of the file before you modified it as returned from the server. If you are uploading a new
   file set parentRev to nil. */
- (void)uploadFile:(NSString *)filename toPath:(NSString *)path withParentRev:(NSString *)parentRev
    fromPath:(NSString *)sourcePath;

- (void)cancelFileUpload:(NSString *)path;

/* Avoid using this because it is very easy to overwrite conflicting changes. Provided for backwards
   compatibility reasons only */
- (void)uploadFile:(NSString*)filename toPath:(NSString*)path fromPath:(NSString *)sourcePath __attribute__((deprecated));

/* These calls allow you to upload files in chunks, which is better for file larger than a few megabytes.
   You can append bytes to the file using -[DBRestClient uploadFileChunk:offset:uploadId:] and then call
   -[DBRestClient uploadFile:toPath:withParentRev:fromUploadId:] to turn the bytes appended at that uploadId
   into an actual file in the user's Dropbox.
   Use a nil uploadId to start uploading a new file. */
- (void)uploadFileChunk:(NSString *)uploadId offset:(unsigned long long)offset fromPath:(NSString *)localPath;
- (void)uploadFile:(NSString *)filename toPath:(NSString *)parentFolder withParentRev:(NSString *)parentRev
	fromUploadId:(NSString *)uploadId;

/* Loads a list of up to 10 DBMetadata objects representing past revisions of the file at path */
- (void)loadRevisionsForFile:(NSString *)path;

/* Same as above but with a configurable limit to number of DBMetadata objects returned, up to 1000 */
- (void)loadRevisionsForFile:(NSString *)path limit:(NSInteger)limit;

/* Restores a file at path as it existed at the given rev and returns the metadata of the restored
   file after restoration */
- (void)restoreFile:(NSString *)path toRev:(NSString *)rev;

/* Creates a folder at the given root/path */
- (void)createFolder:(NSString*)path;

- (void)deletePath:(NSString*)path;

- (void)copyFrom:(NSString*)fromPath toPath:(NSString *)toPath;

- (void)createCopyRef:(NSString *)path; // Used to copy between Dropboxes
- (void)copyFromRef:(NSString*)copyRef toPath:(NSString *)toPath; // Takes copy ref created by above call

- (void)moveFrom:(NSString*)fromPath toPath:(NSString *)toPath;

- (void)loadAccountInfo;

- (void)searchPath:(NSString*)path forKeyword:(NSString*)keyword;

- (void)loadSharableLinkForFile:(NSString *)path;
- (void)loadSharableLinkForFile:(NSString *)path shortUrl:(BOOL)createShortUrl;

- (void)loadStreamableURLForFile:(NSString *)path;

- (NSUInteger)requestCount;

@property (nonatomic, assign) id<DBRestClientDelegate> delegate;

@end

/* The delegate provides allows the user to get the result of the calls made on the DBRestClient.
   Right now, the error parameter of failed calls may be nil and [error localizedDescription] does
   not contain an error message appropriate to show to the user. */
@protocol DBRestClientDelegate <NSObject>

@optional

- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata;
- (void)restClient:(DBRestClient*)client metadataUnchangedAtPath:(NSString*)path;
- (void)restClient:(DBRestClient*)client loadMetadataFailedWithError:(NSError*)error;
// [error userInfo] contains the root and path of the call that failed

- (void)restClient:(DBRestClient*)client loadedDeltaEntries:(NSArray *)entries reset:(BOOL)shouldReset cursor:(NSString *)cursor hasMore:(BOOL)hasMore;
- (void)restClient:(DBRestClient*)client loadDeltaFailedWithError:(NSError *)error;

- (void)restClient:(DBRestClient*)client loadedAccountInfo:(DBAccountInfo*)info;
- (void)restClient:(DBRestClient*)client loadAccountInfoFailedWithError:(NSError*)error;

- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath;
// Implement the following callback instead of the previous if you care about the value of the
// Content-Type HTTP header and the file metadata. Only one will be called per successful response.
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath contentType:(NSString*)contentType metadata:(DBMetadata*)metadata;
- (void)restClient:(DBRestClient*)client loadProgress:(CGFloat)progress forFile:(NSString*)destPath;
- (void)restClient:(DBRestClient*)client loadFileFailedWithError:(NSError*)error;
// [error userInfo] contains the destinationPath

- (void)restClient:(DBRestClient*)client loadedThumbnail:(NSString*)destPath metadata:(DBMetadata*)metadata;
- (void)restClient:(DBRestClient*)client loadThumbnailFailedWithError:(NSError*)error;

- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath from:(NSString*)srcPath
        metadata:(DBMetadata*)metadata;
- (void)restClient:(DBRestClient*)client uploadProgress:(CGFloat)progress
        forFile:(NSString*)destPath from:(NSString*)srcPath;
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error;
// [error userInfo] contains the sourcePath

- (void)restClient:(DBRestClient *)client uploadedFileChunk:(NSString *)uploadId newOffset:(unsigned long long)offset
	fromFile:(NSString *)localPath expires:(NSDate *)expiresDate;
- (void)restClient:(DBRestClient *)client uploadFileChunkFailedWithError:(NSError *)error;

- (void)restClient:(DBRestClient *)client uploadedFile:(NSString *)destPath fromUploadId:(NSString *)uploadId
    metadata:(DBMetadata *)metadata;
- (void)restClient:(DBRestClient *)client uploadFromUploadIdFailedWithError:(NSError *)error;

// Deprecated upload callback
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath from:(NSString*)srcPath;

// Deprecated download callbacks
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath contentType:(NSString*)contentType;
- (void)restClient:(DBRestClient*)client loadedThumbnail:(NSString*)destPath;

- (void)restClient:(DBRestClient*)client loadedRevisions:(NSArray *)revisions forFile:(NSString *)path;
- (void)restClient:(DBRestClient*)client loadRevisionsFailedWithError:(NSError *)error;

- (void)restClient:(DBRestClient*)client restoredFile:(DBMetadata *)fileMetadata;
- (void)restClient:(DBRestClient*)client restoreFileFailedWithError:(NSError *)error;

- (void)restClient:(DBRestClient*)client createdFolder:(DBMetadata*)folder;
// Folder is the metadata for the newly created folder
- (void)restClient:(DBRestClient*)client createFolderFailedWithError:(NSError*)error;
// [error userInfo] contains the root and path

- (void)restClient:(DBRestClient*)client deletedPath:(NSString *)path;
- (void)restClient:(DBRestClient*)client deletePathFailedWithError:(NSError*)error;
// [error userInfo] contains the root and path

- (void)restClient:(DBRestClient*)client copiedPath:(NSString *)fromPath to:(DBMetadata *)to;
- (void)restClient:(DBRestClient*)client copyPathFailedWithError:(NSError*)error;
// [error userInfo] contains the root and path

- (void)restClient:(DBRestClient*)client createdCopyRef:(NSString *)copyRef;
- (void)restClient:(DBRestClient*)client createCopyRefFailedWithError:(NSError *)error;

- (void)restClient:(DBRestClient*)client copiedRef:(NSString *)copyRef to:(DBMetadata *)to;
- (void)restClient:(DBRestClient*)client copyFromRefFailedWithError:(NSError*)error;

- (void)restClient:(DBRestClient*)client movedPath:(NSString *)from_path to:(DBMetadata *)result;
- (void)restClient:(DBRestClient*)client movePathFailedWithError:(NSError*)error;
// [error userInfo] contains the root and path

- (void)restClient:(DBRestClient*)restClient loadedSearchResults:(NSArray*)results
forPath:(NSString*)path keyword:(NSString*)keyword;
// results is a list of DBMetadata * objects
- (void)restClient:(DBRestClient*)restClient searchFailedWithError:(NSError*)error;

- (void)restClient:(DBRestClient*)restClient loadedSharableLink:(NSString*)link
forFile:(NSString*)path;
- (void)restClient:(DBRestClient*)restClient loadSharableLinkFailedWithError:(NSError*)error;

- (void)restClient:(DBRestClient*)restClient loadedStreamableURL:(NSURL*)url forFile:(NSString*)path;
- (void)restClient:(DBRestClient*)restClient loadStreamableURLFailedWithError:(NSError*)error;

@end


text:
from __future__ import print_function
# import
## batteries
import os
import sys
import argparse
import functools
from itertools import product,cycle
## 3rd party
import numpy as np
import pandas as pd
## package
from pyTecanFluent import Utils
from pyTecanFluent import Fluent
from pyTecanFluent import Labware
from pyTecanFluent import Tn5_onBead_pip

# functions
def get_desc():
    desc = 'Create TECAN Fluent worklist instructions for Tn5 library prep'
    return desc

def parse_args(test_args=None, subparsers=None):
    desc = get_desc()
    epi = """DESCRIPTION:
    Convert an input table of samples into a GWL file, which is used by the TECAN
    robot to conduct the NGS Tn5 (self-produced enzyme) library prep.
    The extra columns in the mapping file designate the SOURCE of samples and primers.
    The DESTINATION (plate & well) is set by this script.

    Required columns in the input samples table:
    * "TECAN_sample_labware_name" = The sample labware name on the robot worktable. Whatever name you want to use!
    * "TECAN_sample_labware_type" = The type of labware containing samples (eg., '96 Well Eppendorf TwinTec PCR')
    * "TECAN_sample_target_position" = The well or tube location (a number)
    * "TECAN_primer_labware_name" = The primer plate labware name on the robot worktable (eg., "515F-806R")
    * "TECAN_primer_labware_type" = The primer plate labware type on the robot worktable (eg., "96 Well Eppendorf TwinTec PCR"
    * "TECAN_primer_target_position" = The position (well) of your samples in your labware

    PRIMERS:
    * For single-indexed primers (eg., EMP primers), the non-barcoded primer should be pre-added to either
      the mastermix (adjust the volume used for this script!) or each of the barcoded primers.
    * If --primer-volume set to 0, then primers are skipped.

    CONTROLS:
    * For the positive & negative controls, include them in the mapping file.
    * If the controls (or samples) are provided in a tube, use "1.5ml Eppendorf"
      for the "TECAN_sample_labware_type" column. The labware name can be whatever you want.

    LABWARE:
    * In order to use a plate adapter, use "PCR Adapter 96 Well and 96 Well Eppendorf TwinTec PCR"

    MISC NOTES:
    * All volumes are in ul
    * Plate well locations are 1 to n-wells; numbering by column
    * PicoGreen should be added to the MasterMix *prior* to loading on robot
    """
    if subparsers:
        parser = subparsers.add_parser('Tn5_onBead', description=desc, epilog=epi,
                                       formatter_class=argparse.RawTextHelpFormatter)
    else:
        parser = argparse.ArgumentParser(description=desc, epilog=epi,
                                         formatter_class=argparse.RawTextHelpFormatter)

    # args
    ## I/O
    groupIO = parser.add_argument_group('I/O')
    groupIO.add_argument('mapfile', metavar='MapFile', type=str,
                         help='A samples file with the required columns (see the help docs)')
    groupIO.add_argument('--rows', type=str, default='all',
                         help='Which rows of the sample file to use (eg., "all"=all rows; "1-48"=rows1-48; "1,3,5-6"=rows1+3+5+6), (default: %(default)s)')
    groupIO.add_argument('--prefix', type=str, default='TECAN_Tn5-on-Bead',
                         help='Output file name prefix (default: %(default)s)')

    ## Reagents
    pcr_rgnt = parser.add_argument_group('PCR Reagents')
    pcr_rgnt.add_argument('--sup-volume', type=float, default=120.0,
                          help='Supernatant volume (default: %(default)s)')
    pcr_rgnt.add_argument('--mm-volume', type=float, default=23.0,
                          help='PCR MasterMix volume per well (default: %(default)s)')
    pcr_rgnt.add_argument('--primer-volume', type=float, default=6.0,
                          help='Primer volume per PCR, assuming foward+reverse are already combined (default: %(default)s)')
    pcr_rgnt.add_argument('--mm-labware-type', type=str, default='25ml_1 waste',
                          help='Labware type for mastermix (default: %(default)s)')

    # Liquid classes
    liq = parser.add_argument_group('Liquid classes')
    liq.add_argument('--sup-liq', type=str, default='Tn5-on-bead Supernatant Free Single',
                      help='Supernatant removal liquid class (default: %(default)s)')
    liq.add_argument('--mm-liq', type=str, default='MasterMix Free Single',
                      help='PCR: Mastermix liquid class (default: %(default)s)')
    liq.add_argument('--primer-liq', type=str, default='Water Contact Wet Single',
                     help='Primer liquid class (default: %(default)s)')

    misc = parser.add_argument_group('Misc')
    misc.add_argument('--error-perc', type=float, default=10.0,
                      help='Percent of extra total reagent volume to include (default: %(default)s)')

    # running test args
    if test_args:
        args = parser.parse_args(test_args)
        return args

    return parser

def main(args=None):
    """
    Main iterface
    """
    # Input
    if args is None:
        args = parse_args()
    check_args(args)

    # Import
    df_map = map2df(args.mapfile, args, row_select=args.rows)

    # Making destination dataframe
    df_map = add_dest(df_map)
    df_map = check_rack_labels(df_map)

    # PCR assay setup
    df_map, pcr_files = main_PCR(df_map, args)

    # Return
    return pcr_files

def main_PCR(df_map, args):
    """
    PCR step of the Tn5 method
    """
    # gwl construction
    TipTypes = ['FCA, 1000ul SBS', 'FCA, 200ul SBS',
                'FCA, 50ul SBS', 'FCA, 10ul SBS']
    gwl = Fluent.gwl(TipTypes)

    # Reordering dest if plate type is 384-well
    df_map = Utils.reorder_384well(df_map, gwl,
                                   labware_name_col='TECAN_dest_labware_name',
                                   labware_type_col='TECAN_dest_labware_type',
                                   position_col='TECAN_dest_target_position')

    ## PCR mastermix into tagmentation dest plate
    Tn5_onBead_pip.pip_mastermix(df_map, gwl,
                                 mm_labware_type=args.mm_labware_type,
                                 mm_volume=args.mm_volume,
                                 liq_cls=args.mm_liq,
                                 sup_volume=args.sup_volume,
                                 sup_rm_liq_cls=args.sup_liq)

    ## primers into tagmentation dest plate
    if args.primer_volume > 0:
        Tn5_onBead_pip.pip_primers(df_map, gwl,
                                   prm_volume=args.primer_volume,
                                   liq_cls=args.primer_liq)

    ## writing out worklist (gwl) file
    gwl_file = args.prefix + '_pcr.gwl'
    gwl.write(gwl_file)

    # Report (total volumes; sample truncation; samples)
    report_file = args.prefix + '_pcr_report.txt'
    with open(report_file, 'w') as repFH:
        write_pcr_report(df_map, outFH=repFH,
                         mm_volume=args.mm_volume,
                         prm_volume=args.primer_volume,
                         error_perc=args.error_perc)

    # making labware table
    lw = Labware.labware()
    lw.add_gwl(gwl)
    lw_df = lw.table()
    lw_file = args.prefix + '_pcr_labware.txt'
    lw_df.to_csv(lw_file, sep='\t', index=False)

    # Mapping file with destinations
    df_file = args.prefix + '_pcr_map.txt'
    df_map['TECAN_dest_target_position'] = df_map['TECAN_dest_target_position'].astype(int)
    df_map.to_csv(df_file, sep='\t', index=False, na_rep='NA')

    # Plate map file for Bio-Rad PrimePCR software (designates: sampleID <--> wellID)
    biorad_files = PrimerPCR_plate_map(df_map, prefix=args.prefix)

    # status on files written
    Utils.file_written(gwl_file)
    Utils.file_written(lw_file)
    Utils.file_written(report_file)
    Utils.file_written(df_file)
    for F in biorad_files:
        Utils.file_written(F)

    return df_map, [gwl_file, lw_file, report_file, df_file]

def check_args(args):
    """
    Checking user input
    """
    # destination start
    db = Fluent.db()
    #db.get_labware(args.dest_type)
    #wells = db.get_labware_wells(args.dest_type)
    #if args.dest_start < 1 or args.dest_start > wells:
    #    msg = 'Destination start well # must be in range: 1-{}'
    #    raise ValueError(msg.format(wells))

    # rows in mapping file
    args.rows = Utils.make_range(args.rows, set_zero_index=True)

    # volumes
    ## PCR
    ### mastermix
    if args.mm_volume < 0:
        args.mm_volume = 0
    ### primers
    if args.primer_volume < 0:
        args.primer_volume = 0

def map2df(mapfile, args, row_select=None):
    """
    Loading a mapping file as a pandas dataframe
    mapfile: string; mapping file path
    row_select: select particular rows of table in map file
    """
    # load via pandas IO
    if mapfile.endswith('.txt') or mapfile.endswith('.tsv'):
        df = pd.read_csv(mapfile, sep='\t')
    elif mapfile.endswith('.csv'):
        df = pd.read_csv(mapfile, sep=',')
    elif mapfile.endswith('.xls') or mapfile.endswith('.xlsx'):
        xls = pd.ExcelFile(mapfile)
        df = pd.read_excel(xls)
    else:
        raise ValueError('Mapping file not in usable format')

    # selecting particular rows
    if row_select is not None:
        df = df.iloc[row_select]

    # checking format
    df = check_df_map(df, args)

    # return
    return df

def missing_cols(df, req_cols):
    msg = 'Required column "{}" not found'
    for req_col in req_cols:
        if req_col not in df.columns.values:
            raise ValueError(msg.format(req_col))

def filter_nan_cols(df, col):
    """
    Filtering nan columns if present
    """
    if df[col].isnull().values.any():
        msg = 'WARNING: nan values found in column: "{}". Filtering these nan rows\n'
        sys.stderr.write(msg.format(col))

    return df.dropna(subset=[col])

def check_df_map(df_map, args):
    """
    Assertions of df_map object formatting
    * Assumes `sample` field = 1st column
    df_map: map dataframe
    """
    # checking columns
    ## universal
    to_rename = {}
    if 'TECAN_labware_name' in df_map.columns.values and 'TECAN_sample_labware_name' not in df_map.columns.values:
        to_rename['TECAN_labware_name'] = 'TECAN_sample_labware_name'
    if 'TECAN_labware_type' in df_map.columns.values and 'TECAN_sample_labware_type' not in df_map.columns.values:
        to_rename['TECAN_labware_type'] = 'TECAN_sample_labware_type'
    if 'TECAN_target_position' in df_map.columns.values and 'TECAN_sample_target_position' not in df_map.columns.values:
        to_rename['TECAN_target_position'] = 'TECAN_sample_target_position'
    df_map.rename(columns=to_rename, inplace=True)
    req_cols = ['TECAN_sample_labware_name', 'TECAN_sample_labware_type',
                'TECAN_sample_target_position', 'TECAN_primer_labware_name',
                'TECAN_primer_labware_type', 'TECAN_primer_target_position']
    missing_cols(df_map, req_cols)

    # adding samples column if not present
    if '#SampleID' in df_map.columns.values:
        df_map.rename(columns={'#SampleID':'SampleID'}, inplace=True)
    if 'SampleID' not in df_map.columns.values:
        df_map['SampleID'] = [x + 1 for x in range(df_map.shape[0])]

    # filtering nan columns if present
    for x in req_cols:
        df_map = filter_nan_cols(df_map, x)

    # checking for unique samples
    if any(df_map.duplicated('SampleID')):
        msg = 'WARNING: Duplicated sample values in the mapping file. Adding plate name to SampleID to make values unique'
        print(msg, file=sys.stderr)
        df_map['SampleID'] = df_map[['SampleID', 'TECAN_sample_labware_name']].apply(lambda x: '__'.join([str(y) for y in x]), axis=1)
        if any(df_map.duplicated('SampleID')):
            msg = 'ERROR: Duplicated sample values in the mapping file on the same plate! Not acceptable!'
            raise IOError(msg)

    # checking for unique barcode locations (NaN's filtered out)
    dups = df_map[req_cols].dropna().duplicated(keep=False)
    if any(dups):
        msg = 'WARNING: Duplicated barcodes in the mapping file!'
        print(msg, file=sys.stderr)

    # making sure labware names are "TECAN worklist friendly"
    df_map = Utils.rm_special_chars(df_map, 'TECAN_sample_labware_name')
    df_map = Utils.rm_special_chars(df_map, 'TECAN_primer_labware_name')

    # removing "tube" from end of labware type (if present)
    Utils.rm_tube(df_map, 'TECAN_sample_labware_type')
    Utils.rm_tube(df_map, 'TECAN_primer_labware_type')

    # return
    return df_map

def check_rack_labels(df_map):
    """Removing '.' for rack labels (causes execution failures)
    """
    cols = ['TECAN_sample_labware_name',
            'TECAN_primer_labware_name',
            'TECAN_dest_labware_name']
    for x in cols:
        df_map[x] = [y.replace('.', '_') for y in df_map[x].tolist()]
    return df_map

def add_dest(df_map):#, dest_labware, dest_type='384 Well Biorad PCR', dest_start=1):
    """
    Setting destination locations for samples & primers.
    Making a new dataframe with:
    [dest_labware, dest_location]
    Joining to df_map
    """
    df_map['TECAN_dest_labware_name'] = df_map['TECAN_sample_labware_name']
    df_map['TECAN_dest_labware_type'] = df_map['TECAN_sample_labware_type']
    df_map['TECAN_dest_target_position'] = df_map['TECAN_sample_target_position']
    return df_map

    # db = Fluent.db()
    # dest_start= int(dest_start)

    # # labware type found in DB?
    # db.get_labware(dest_type)
    # positions = db.get_labware_wells(dest_type)

    # # init destination df
    # sample_col = 'SampleID'
    # cols = [sample_col,
    #         'TECAN_dest_labware_name',
    #         'TECAN_dest_labware_type',
    #         'TECAN_dest_target_position']
    # ncol = len(cols)
    # nrow = df_map.shape[0]
    # df_dest = pd.DataFrame(np.nan, index=range(nrow), columns=cols)

    # # number of destination plates required
    # n_dest_plates = round(df_dest.shape[0] / positions + 0.5, 0)
    # if n_dest_plates > 1:
    #     msg = ('WARNING: Not enough wells for the number of samples.'
    #     ' Using multiple destination plates')
    #     print(msg, file=sys.stderr)

    # # filling destination df
    # orig_dest_labware = dest_labware
    # for i,sample in enumerate(df_map['SampleID']):
    #     # dest location
    #     dest_position = i + dest_start
    #     dest_position = positions if dest_position % positions == 0 else dest_position % positions

    #     # destination plate name
    #     if n_dest_plates > 1:
    #         x = round((i + dest_start) / positions + 0.499, 0)
    #         dest_labware = '{} {}'.format(orig_dest_labware, int(x))

    #     # adding values DF
    #     df_dest.iloc[i] = [sample, dest_labware, dest_type, dest_position]

    # # df join (map + destination)
    # assert df_map.shape[0] == df_dest.shape[0], 'df_map and df_dest are different lengths'
    # df_j = pd.merge(df_map, df_dest, on=sample_col, how='inner')
    # assert df_j.shape[0] == df_dest.shape[0], 'map-dest DF join error'
    # assert df_j.shape[0] > 0, 'DF has len=0 after adding destinations'

    # # return
    # return df_j

def reorder_384well(df, reorder_col):
    """Reorder values so that the odd, then the even locations are
    transferred. This is faster for a 384-well plate
    df: pandas.DataFrame
    reorder_col: column name to reorder
    """
    df['TECAN_sort_IS_EVEN'] = [x % 2 == 0 for x in df[reorder_col]]
    df.sort_values(by=['TECAN_sort_IS_EVEN', reorder_col], inplace=True)
    df = df.drop('TECAN_sort_IS_EVEN', 1)
    df.index = range(df.shape[0])
    return df

def PrimerPCR_plate_map(df_map, prefix='PrimerPCR', sep=','):
    """Create a PrimerPCR plate map table.
    This table is imported by PrimerPCR to designate: sampleID <--> wellID
    Table columns: Row     Column  *Target Name    *Sample Name
      "Row" : plate row
      "Column" : plate column
      "*Target Name" : Not needed (NA)
      "*Sample Name" : Sample in well
    Return: list of pandas dataframes (1 dataframe per file)
    """
    # Plate import file for Bio-Rad PrimePCR software
    dest_pos_max = 96 if df_map['TECAN_dest_target_position'].max() <= 96 else 384
    f = functools.partial(map2biorad, positions=dest_pos_max)
    df_biorad = df_map.groupby('TECAN_dest_labware_name').apply(f)
    biorad_files = []
    if isinstance(df_biorad.index, pd.MultiIndex):
        for labware in df_biorad.index.get_level_values(0).unique():
            biorad_file = prefix + '_BIORAD-{}.txt'.format(labware.replace(' ', '_'))
            df_biorad.loc[labware].to_csv(biorad_file, sep=sep, index=False, na_rep='')
            biorad_files.append(biorad_file)
    else:
        biorad_file = prefix + '_BIORAD.txt'
        df_biorad.to_csv(biorad_file, sep=sep, index=False, na_rep='')
        biorad_files.append(biorad_file)

    return biorad_files

def map2biorad(df_map, positions):
    """Making a table for loading into the Bio-Rad PrimePCR software
    columns are:  Row,Column,*Target Name,*Sample Name
    positions = max number of positions on qPCR plate
    Notes:
      Row = letter format
      Column = numeric
    """
    df_biorad = df_map.copy()
    df_biorad = df_biorad[['SampleID', 'TECAN_dest_target_position']]
    df_biorad.columns = ['*Sample Name', 'TECAN_dest_target_position']
    lw_utils = Labware.utils()
    f = functools.partial(lw_utils.position2well, wells = positions)
    x = df_map['TECAN_dest_target_position'].apply(f)
    x = pd.DataFrame([y for y in x], columns=['Row', 'Column'])
    df_biorad['Row'] = x.iloc[:,0].tolist()
    df_biorad['Column'] = x.iloc[:,1].tolist()

    df_biorad['*Target Name'] = np.nan
    df_biorad = df_biorad[['Row', 'Column', '*Target Name', '*Sample Name']]

    return df_biorad

def add_error(x, error_perc):
    if x is None:
        return None
    return x * (1.0 + error_perc / 100.0)

def write_report_line(outFH, subject, volume, round_digits=1, error_perc=None):
    if volume is None:
        v = 'NA'
    else:
        if error_perc is not None:
            volume = add_error(volume, error_perc)
        v = round(volume, round_digits)
    outFH.write('{}:\t{}\n'.format(subject, v))

def write_pcr_report(df_map, outFH, mm_volume=0.0,
                     prm_volume=0.0, error_perc=10.0):
    """Writing a report on pcr reagnets
    """
    # calculating total volumes
    n_rxn = df_map.shape[0]
    ## total mastermix
    total_mm_volume = mm_volume * n_rxn

    # report
    # number of samples
    outFH.write('# RXN REPORT\n')
    outFH.write('Number of total RXNs:\t{}\n'.format(n_rxn))
    ## rxn volumes
    outFH.write('\n# Volumes per RXN (ul)\n')
    write_report_line(outFH, 'Master Mix', mm_volume)
    write_report_line(outFH, 'Primers', prm_volume)
    ## raw total volumes
    outFH.write('\n# Total volumes (ul)\n')
    write_report_line(outFH, 'Master Mix', total_mm_volume)
    ## total volumes with error
    outFH.write('\n# Total volumes with (ul; {}% error)\n'.format(error_perc))
    write_report_line(outFH, 'Master Mix', total_mm_volume, error_perc=error_perc)
    # samples
    outFH.write('')

# main
if __name__ == '__main__':
    pass


text:
"""
    instabot example

    Workflow:
        Like rescent medias from your timeline feed.
"""

import sys
import os

sys.path.append(os.path.join(sys.path[0], '../'))

from instabot import Bot

bot = Bot()
bot.login()
bot.like_timeline()


text:
const os = require('os')
const fs = require('fs')

let IPAddress = process.argv[2]

if (IPAddress == undefined) {
  // Find out IP address
  const interfaces = os.networkInterfaces()
  const addresses = []
  for (let k in interfaces) {
    // $FlowIssue it will be there
    for (let k2 in interfaces[k]) {
      // $FlowIssue it will be there
      const address = interfaces[k][k2]
      if (address.family === 'IPv4' && !address.internal) addresses.push(address.address)
    }
  }

  if (addresses.length >= 0) IPAddress = addresses[0]
}

if (IPAddress != undefined) {
  console.log('IP Address:' + IPAddress)
  updateIPInFile(
    './ios/UniversalRelayBoilerplate/AppDelegate.m',
    'jsCodeLocation = [NSURL URLWithString:@"http:',
    '  jsCodeLocation = [NSURL URLWithString:@"http://' +
      IPAddress +
      ':8081/index.ios.bundle?platform=ios&dev=true"];',
  )
  updateIPInFile(
    './app/app.js',
    'let graphQLServerURL = "http://',
    'let graphQLServerURL = "http://' + IPAddress + ':5555/graphql";',
  )
  updateIPInFile('./.env', 'HOST=', 'HOST=' + IPAddress)
} else console.log('IP Address not specified and could not be found')

function updateIPInFile(fileName, searchString, newContentOfLine) {
  let fileLines = fs.readFileSync(fileName, 'utf8').split('\n')
  let index = 0

  while (index < fileLines.length) {
    if (fileLines[index].indexOf(searchString) > -1) {
      if (fileLines[index] == newContentOfLine)
        console.log('[' + fileName + '] is already up to date')
      else {
        fileLines[index] = newContentOfLine
        fs.writeFileSync(fileName, fileLines.join('\n'))

        console.log('[' + fileName + '] has been updated with local IP ' + IPAddress)
      }
      break
    } else index++
  }
}


text:
<?xml version="1.0" encoding="ISO-8859-1" ?>

<document>
    <properties>
        <title>Apache Synapse - Sample 256</title>
    </properties>

<definitions xmlns="http://ws.apache.org/ns/synapse">

    <proxy name="StockQuoteProxy" transports="mailto">

        <target>
            <inSequence>
                <property name="senderAddress" expression="get-property('transport', 'From')"/>
                <log level="full">
                    <property name="Sender Address" expression="get-property('senderAddress')"/>
                </log>
                <send>
                    <endpoint>
                        <address uri="http://localhost:9000/services/SimpleStockQuoteService"/>
                    </endpoint>
                </send>
            </inSequence>
            <outSequence>
                <property name="Subject" value="Custom Subject for Response" scope="transport"/>
                <header name="To" expression="fn:concat('mailto:', get-property('senderAddress'))"/>
                <log level="full">
                    <property name="message" value="Response message"/>
                    <property name="Sender Address" expression="get-property('senderAddress')"/>
                </log>
                <send/>
            </outSequence>
        </target>
        <publishWSDL uri="file:repository/conf/sample/resources/proxy/sample_proxy_1.wsdl"/>

        <parameter name="transport.mail.Address">synapse.demo.mail1@gmail.com</parameter>
        <parameter name="transport.mail.Protocol">pop3</parameter>
        <parameter name="transport.PollInterval">5</parameter>
        <parameter name="mail.pop3.host">pop.gmail.com</parameter>
        <parameter name="mail.pop3.port">995</parameter>
        <parameter name="mail.pop3.user">synapse.demo.mail1</parameter>
        <parameter name="mail.pop3.password">mailpassword</parameter>
        <parameter name="mail.pop3.socketFactory.class">javax.net.ssl.SSLSocketFactory</parameter>
        <parameter name="mail.pop3.socketFactory.fallback">false</parameter>
        <parameter name="mail.pop3.socketFactory.port">995</parameter>
        <parameter name="transport.mail.ContentType">application/xml</parameter>

    </proxy>

</definitions>

            <subsection name="Objective">

                    This sample show cases the mail transport of Synapse. The mail transport allows
                    Synapse to receive and send e-mails using common protocols like POP, IMAP and
                    SMTP.

            </subsection>
            <subsection name="Pre-requisites">

                            You need access to an e-mail account to try out this sample

                            Deploy the SimpleStockQuoteService in the sample Axis2 server and start Axis2

                            Enable the mail transport listener and mail transport sender for Synapse
                            (refer  Mail transport setup
                            guide for more details)

                            Start Synapse using the configuration numbered 256 (repository/conf/sample/synapse_sample_256.xml)

                                Unix/Linux: sh synapse.sh -sample 256

                                Windows: synapse.bat -sample 256

            </subsection>
            <subsection name="Executing the Client">

                    Send an e-mail to synapse.demo.mail1@gmail.com
                    with the following payload.

<getQuote xmlns="http://services.samples">
   <request>
       <symbol>IBM</symbol>
   </request>
</getQuote>

                    Synapse will be polling on the above e-mail account for any incoming requests. When
                    your mail arrives at this account, Synapse will pick it up and send the payload to
                    Axis2 over HTTP. The response will be mailed back to your e-mail account. Synapse
                    retrieves the sender information from the original request to determine the recipient
                    of the response mail.

                    Note that in this sample we used the transport.mail.ContentType property to make
                    sure that the transport parses the request message as POX. If you remove this
                    property, you may still be able to send requests using a standard mail client if
                    instead of writing the XML in the body of the message, you add it as an attachment.
                    In that case, you should use .xml as a suffix for the attachment and format the
                    request as a SOAP 1.1 message. Indeed, for a file with suffix .xml the mail client
                    will most likely use text/xml as the content type, exactly as required for SOAP 1.1.
                    Sending a POX message using this approach will be a lot trickier, because most
                    standard mail clients don't allow the user to explicitly set the content type.

            </subsection>

Back to Catalog

</document>


text:
class CreateLunchdates < ActiveRecord::Migration[5.1]
  def change
    create_table :lunchdates do |t|
      t.date :date
      t.time :time
      t.integer :seats
      t.references :group
      t.string :place
      t.float :longitude
      t.float :latitude
      t.boolean :completed, default: false

      t.timestamps
    end
  end
end


text:
chrome.runtime.onMessage.addListener(function (msg, sender) {
    // First, validate the message's structure
    if ((msg.from === 'content') && (msg.subject === 'showPageAction')) {
        // Enable the page-action for the requesting tab
        chrome.pageAction.show(sender.tab.id);
    }
});


text:
using System;
using System.Collections.Generic;
using System.Threading;
using static JM.LinqFaster.Utils.CustomPartition;

namespace JM.LinqFaster.Parallel
{
    public static partial class LinqFasterParallel
    {
        /// <summary>
        /// Combined Where and Select with the Where phase in parallel.
        /// </summary>
        /// <param name="source">The input sequence to filter then transform.</param>
        /// <param name="predicate">A function to use to filter the sequence.</param>
        /// <param name="selector">A function to transform the filtered elements.</param>
        /// <param name="batchSize">Optional. Specify a batch size for Tasks to operate over. </param>
        /// <returns>A sequence of filtered and transformed elements.</returns>
        public static TResult[] WhereSelectP<T, TResult>(this T[] source, Func<T, bool> predicate, Func<T, TResult> selector, int? batchSize = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (predicate == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            var isChosen = new bool[source.Length];
            int count = 0;
            var rangePartitioner = MakePartition(source.Length, batchSize);
            System.Threading.Tasks.Parallel.ForEach(rangePartitioner, () => 0,
                (range, loopState,acc) =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        if (predicate(source[i]))
                        {
                            isChosen[i] = true;
                            acc++;
                        }
                    }
                    return acc;
                },
                 acc =>
                 {
                     Interlocked.Add(ref count, acc);
                 });

            var result = new TResult[count];
            int idx = 0;
            for (int i = 0; i < isChosen.Length; i++)
            {
                if (isChosen[i])
                {
                    result[idx] = selector(source[i]);
                    idx++;
                }
            }
            return result;
        }

        /// <summary>
        /// Combined Where and Select with the Where phase in parallel using the
        /// index in the predicate and selector.
        /// </summary>
        /// <param name="source">The input sequence to filter then transform.</param>
        /// <param name="predicate">A function to use to filter the sequence.</param>
        /// <param name="selector">A function to transform the filtered elements.</param>
        /// <param name="batchSize">Optional. Specify a batch size for Tasks to operate over. </param>
        /// <returns>A sequence of filtered and transformed elements.</returns>
        public static TResult[] WhereSelectP<T, TResult>(this T[] source, Func<T,int, bool> predicate, Func<T,int, TResult> selector, int? batchSize = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (predicate == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            var isChosen = new bool[source.Length];
            int count = 0;
            var rangePartitioner = MakePartition(source.Length, batchSize);
            System.Threading.Tasks.Parallel.ForEach(rangePartitioner, () => 0,
                (range, loopState, acc) =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        if (predicate(source[i],i))
                        {
                            isChosen[i] = true;
                            acc++;
                        }
                    }
                    return acc;
                },
                 acc =>
                 {
                     Interlocked.Add(ref count, acc);
                 });

            var result = new TResult[count];
            int idx = 0;
            for (int i = 0; i < isChosen.Length; i++)
            {
                if (isChosen[i])
                {
                    result[idx] = selector(source[i],idx);
                    idx++;
                }
            }
            return result;
        }

        // -------------------------------- Lists ------------------------------------------

        /// <summary>
        /// Combined Where and Select with the Where phase in parallel.
        /// </summary>
        /// <param name="source">The input sequence to filter then transform.</param>
        /// <param name="predicate">A function to use to filter the sequence.</param>
        /// <param name="selector">A function to transform the filtered elements.</param>
        /// <param name="batchSize">Optional. Specify a batch size for Tasks to operate over. </param>
        /// <returns>A sequence of filtered and transformed elements.</returns>
        public static List<TResult> WhereSelectP<T, TResult>(this List<T> source, Func<T, bool> predicate, Func<T, TResult> selector, int? batchSize = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (predicate == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            var isChosen = new bool[source.Count];
            int count = 0;
            var rangePartitioner = MakePartition(source.Count, batchSize);
            System.Threading.Tasks.Parallel.ForEach(rangePartitioner, () => 0,
                (range, loopState, acc) =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        if (predicate(source[i]))
                        {
                            isChosen[i] = true;
                            acc++;
                        }
                    }
                    return acc;
                },
                 acc =>
                 {
                     Interlocked.Add(ref count, acc);
                 });

            var result = new List<TResult>(count);
            for (int i = 0; i < isChosen.Length; i++)
            {
                if (isChosen[i])
                {
                    result.Add(selector(source[i]));
                }
            }
            return result;
        }

        /// <summary>
        /// Combined Where and Select with the Where phase in parallel using the
        /// index in the predicate and selector.
        /// </summary>
        /// <param name="source">The input sequence to filter then transform.</param>
        /// <param name="predicate">A function to use to filter the sequence.</param>
        /// <param name="selector">A function to transform the filtered elements.</param>
        /// <param name="batchSize">Optional. Specify a batch size for Tasks to operate over. </param>
        /// <returns>A sequence of filtered and transformed elements.</returns>
        public static List<TResult> WhereSelectP<T, TResult>(this List<T> source, Func<T, int, bool> predicate, Func<T, int, TResult> selector, int? batchSize = null)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }

            if (predicate == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            if (selector == null)
            {
                throw Error.ArgumentNull("predicate");
            }

            var isChosen = new bool[source.Count];
            int count = 0;
            var rangePartitioner = MakePartition(source.Count, batchSize);
            System.Threading.Tasks.Parallel.ForEach(rangePartitioner, () => 0,
                (range, loopState, acc) =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        if (predicate(source[i], i))
                        {
                            isChosen[i] = true;
                            acc++;
                        }
                    }
                    return acc;
                },
                 acc =>
                 {
                     Interlocked.Add(ref count, acc);
                 });

            var result = new List<TResult>(count);
            int idx = 0;
            for (int i = 0; i < isChosen.Length; i++)
            {
                if (isChosen[i])
                {
                    result.Add(selector(source[i], idx));
                    idx++;
                }
            }
            return result;
        }

    }
}


text:
package org.apache.asterix.algebra.operators.physical;

import org.apache.asterix.common.transactions.JobId;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.runtime.base.IPushRuntime;
import org.apache.hyracks.algebricks.runtime.base.IPushRuntimeFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;

public class CommitRuntimeFactory implements IPushRuntimeFactory {

    private static final long serialVersionUID = 1L;

    private final JobId jobId;
    private final int datasetId;
    private final int[] primaryKeyFields;
    private final boolean isTemporaryDatasetWriteJob;
    private final boolean isWriteTransaction;

    public CommitRuntimeFactory(JobId jobId, int datasetId, int[] primaryKeyFields, boolean isTemporaryDatasetWriteJob,
            boolean isWriteTransaction) {
        this.jobId = jobId;
        this.datasetId = datasetId;
        this.primaryKeyFields = primaryKeyFields;
        this.isTemporaryDatasetWriteJob = isTemporaryDatasetWriteJob;
        this.isWriteTransaction = isWriteTransaction;
    }

    @Override
    public String toString() {
        return "commit";
    }

    @Override
    public IPushRuntime createPushRuntime(IHyracksTaskContext ctx) throws AlgebricksException {
        return new CommitRuntime(ctx, jobId, datasetId, primaryKeyFields, isTemporaryDatasetWriteJob,
                isWriteTransaction);
    }
}


text:
@charset "utf-8";
/* CSS Document */
body{margin:0;padding:0;font-family:"Microsoft YaHei" , "宋体";letter-spacing:0.1rem;color: rgb(51,51,51);background:url(../img/bg.png) no-repeat top left;background-size:100%;background-color: rgb(255,251,234);font-size:16px;}
.clearfix{content:'.'; display:block; height:0; clear:both; visibility:hidden;}
.fl{float:left;}
.fr{float:right;}

.container{position:relative;min-height:480px;}

/*视频信息*/
.intro{margin-top:16%;z-index:2}
.caption{width:100%;font-size:1.75em;color: rgb(152,28,8);text-align:center;}
.info{padding:0 4%;text-align:center;font-size:1.2em;}

.hongbao{width:100%;text-align:center;}
.hongbao p{width:100%;padding-top:61%;padding-bottom:32%;background:url(../img/hongbao.png) no-repeat top left;background-size:100%;line-height:1.25rem;font-size:1.25em;color: rgb(255,228,0)}
.hongbao p strong{font-size:1.5em;padding:0 2px;}
.hongbao button{display:block;margin-top:-20%;margin-left:auto;margin-right:auto;padding:18% 23%;border:medium none;background:url(../img/button.png) no-repeat center;background-size:100%;}
@media screen and (min-width:320px) {
	body{font-size:75%;}
}
@media screen and (min-width:480px) {
	body{font-size:87.5%;}
}
@media screen and (min-width:540px) {
	body{font-size:112.5%;}
}
@media screen and (min-width:550px) {
	body{font-size:125%;}
}
@media screen and (min-width:640px) {
	body{font-size:150%;}
}


text:
Client library for MailboxValidator Email Validation

## Installation and Usage
```bash
npm install --save @datafire/mailboxvalidator_validation
```
```js
let mailboxvalidator_validation = require('@datafire/mailboxvalidator_validation').create();

.then(data => {
  console.log(data);
});
```

## Description

The Single Validation API does validation on a single email address and returns all the validation results in either JSON or XML format. Refer to https://www.mailboxvalidator.com for further information.

## Actions

### v1.validation.single.get
The Single Validation API does validation on a single email address and returns all the validation results in either JSON or XML format.

```js
mailboxvalidator_validation.v1.validation.single.get({
  "email": "",
  "key": ""
}, context)
```

#### Input
* input `object`
  * format `string` (values: json, xml): Return the result in json (default) or xml format.
  * email **required** `string`: The email address to be validated.
  * key **required** `string`: API key.

#### Output
* output `string`

## Definitions

*This integration has no definitions*


text:
require 'spec_helper'

module Dustbag
  describe Item do
    include_context 'load xml from fixture'

    it_behaves_like 'a node'

    describe '#asin' do
      it { expect(subject.asin).to eq 'B00ZQVSKS2' }
    end

    describe '#parent_asin' do
      it { expect(subject.parent_asin).to eq 'B0127MKEAE' }
    end

    describe '#detail_page_url' do
      it { expect(subject.detail_page_url).to eq 'http://www.amazon.com/Motorola-Moto-3rd-Generation-Unlocked/dp/B00ZQVSKS2%3Fpsc%3D1%26SubscriptionId%3DMyAccessKeyId%26tag%3Daffiliate-tag%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB00ZQVSKS2' }
    end

    describe '#item_links' do
      it { expect(subject.item_links).to be_a_kind_of ItemLinks }
    end

    describe '#item_attributes' do
      it { expect(subject.item_attributes).to be_a_kind_of ItemAttributes }
    end

    context 'item response for the medium response group' do
      include_context 'load xml from fixture', 'item_medium'

      describe '#small_image' do
        it { expect(subject.small_image).to be_a_kind_of Image }
      end

      describe '#medium_image' do
        it { expect(subject.medium_image).to be_a_kind_of Image }
      end

      describe '#large_image' do
        it { expect(subject.large_image).to be_a_kind_of Image }
      end

      describe '#image_sets' do
        it { expect(subject.image_sets).to be_a_kind_of ImageSets }
      end

      describe '#offer_summary' do
        it { expect(subject.offer_summary).to be_a_kind_of OfferSummary }
      end
    end

    context 'item response for the large response group' do
      include_context 'load xml from fixture', 'item_large'

      describe '#sales_rank' do
        it { expect(subject.sales_rank).to eq 399 }
      end

      describe '#offers' do
        it { expect(subject.offers).to be_a_kind_of Offers }
      end

      describe '#customer_reviews' do
        it { expect(subject.customer_reviews).to be_a_kind_of CustomerReviews }
      end

      describe '#editorial_reviews' do
        it { expect(subject.editorial_reviews).to be_a_kind_of EditorialReviews }
      end

      describe '#similar_products' do
        it { expect(subject.similar_products).to be_a_kind_of SimilarProducts }
      end

      describe '#browse_nodes' do
        it { expect(subject.browse_nodes).to be_a_kind_of BrowseNodes }
      end
    end

    context 'item with accessories' do
      include_context 'load xml from fixture', 'item_with_accessories'

      describe '#accessories' do
        it { expect(subject.accessories).to be_a_kind_of(Accessories) }
        it { expect(subject.accessories).to_not be_empty }
      end
    end

    context 'item with variations' do
      include_context 'load xml from fixture', 'item_with_variations'

      describe '#variation_summary' do
        it { expect(subject.variation_summary).to be_a_kind_of VariationSummary }
      end

      describe '#variations' do
        it { expect(subject.variations).to be_a_kind_of Variations }
        it { expect(subject.variations).to_not be_empty }
      end
    end

    context 'item with variation attributes' do
      include_context 'load xml from fixture', 'item_with_variation_attributes'

      it { expect(subject.variation_attributes).to_not be_empty }
      it { expect(subject.variation_attributes).to be_a_kind_of VariationAttributes }
    end
  end
end