text:
package cloudade.server.auth.mongo.user.repositories;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Update.update;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import cloudade.server.auth.mongo.user.domain.User;

import com.mongodb.WriteResult;

@Component
public class UserRepositoryImpl implements UserRepositoryBase {

    private final MongoTemplate mongoTemplate;

    @Autowired
    public UserRepositoryImpl(final MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @Override
    public boolean changePassword(final String oldPassword,
                               final String newPassword,
                               final String username) {
        final Query searchUserQuery = new Query(where("username").is(username).andOperator(where("password").is(oldPassword)));
        final WriteResult result = mongoTemplate.updateFirst(searchUserQuery, update("password", newPassword), User.class);
        return result.getN() == 1? true : false;
    }
}


text:
. "${srcdir=.}/init.sh"; path_prepend_ ../parted

require_root_
require_scsi_debug_module_

grep '^#define USE_BLKID 1' "$CONFIG_HEADER" > /dev/null ||
  skip_ 'this system lacks a new-enough libblkid'

# create memory-backed device
scsi_debug_setup_ dev_size_mb=550 > dev-name ||
  skip_ 'failed to create scsi_debug device'
scsi_dev=$(cat dev-name)

# Create an empty partition of "type fat32", and then create an actual
# ext2 partition in it.  Then "unset" the already unset LVM flag on that
# partition and ensure that parted doesn't "helpfully" change the partition
# type to match the newly-detected FS type.

parted -s $scsi_dev mklabel msdos mkpart primary fat32 64s 80000s || fail=1

parted -s $scsi_dev u s p

p1=${scsi_dev}1
wait_for_dev_to_appear_ $p1 || fail=1
mkfs.ext2 $p1 || fail=1

# print as hex, the type of the first partition
msdos_p1_type() { od -An --skip=450 -N1 -tx1 "$1"; }

# Initially, it is 0x0c (FAT32).
type=$(msdos_p1_type $scsi_dev) || fail=1
type=${type# } # remove leading space
case $type in
  0c) ;;
  *) fail_ "expected initial type of 0c (FAT32)";;
esac

parted -s $scsi_dev u s p
parted -s $scsi_dev set 1 lvm off || fail=1

# Before parted-2.1, the above would mistakenly change it to 0x83,
# to match the file system now residing in that partition.
type=$(msdos_p1_type $scsi_dev) || fail=1
type=${type# } # remove leading space
case $type in
  0c) ;;
  *) fail_ "parted changed the type of partition 1 from 0c to $type";;
esac

# Ensure that setting the "lvm" flag still works.
parted -s $scsi_dev set 1 lvm on || fail=1
parted -s $scsi_dev u s p > out || fail=1
grep lvm out || { fail=1; cat out; }

Exit $fail

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>RaftLib: allocate.hpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

RaftLib
    0.3a

C++ Stream Processing Template Library

Main Page

Related Pages

Namespaces

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

allocate.hpp

    1

   25 #ifndef _ALLOCATE_HPP_

   26 #define _ALLOCATE_HPP_  1

   27

   28

   29 #include "kernel.hpp"

   30 #include "port_info.hpp"

   31 #include "fifo.hpp"

   32 #include <set>

   33

   34 class Map;

   35

   36 class Allocate

   37 {

   38 public:

   48    Allocate( Map &map, volatile bool &exit_alloc );

   49

   53    virtual ~Allocate();

   54

   60    virtual void run() = 0;

   61

   66    void waitTillReady();

   67

   68

   69 protected:

   81    void initialize( PortInfo *src, PortInfo *dst, FIFO *fifo );

   82

   87    void setReady();

   88

   90    std::set< raft::kernel* > &source_kernels;

   91    std::set< raft::kernel* > &all_kernels;

   92

   97    std::set< FIFO*   > allocated_fifo;

   98

  104    volatile bool &exit_alloc;

  105 private:

  106    volatile bool ready = false;

  107 };

  108 #endif /* END _ALLOCATE_HPP_ */

Allocate::exit_alloc

volatile bool & exit_alloc

Definition: allocate.hpp:104

Allocate::setReady

void setReady()

Definition: allocate.cpp:52

Allocate::source_kernels

std::set< raft::kernel * > & source_kernels

Definition: allocate.hpp:90

Allocate::waitTillReady

void waitTillReady()

Definition: allocate.cpp:46

Allocate::~Allocate

virtual ~Allocate()

Definition: allocate.cpp:37

Allocate::allocated_fifo

std::set< FIFO * > allocated_fifo

Definition: allocate.hpp:97

Allocate::run

virtual void run()=0

Allocate::initialize

void initialize(PortInfo *src, PortInfo *dst, FIFO *fifo)

Definition: allocate.cpp:58

Map

Definition: map.hpp:39

Allocate

Definition: allocate.hpp:36

Allocate::Allocate

Allocate(Map &map, volatile bool &exit_alloc)

Definition: allocate.cpp:30

PortInfo

Definition: port_info.hpp:39

FIFO

Definition: fifo.hpp:41

<address class="footer">
Generated on Thu Mar 19 2015 14:14:01 for RaftLib by

 1.8.8
</address>


text:
require 'git'
require 'yaml'
require "#{File.dirname(__FILE__)}/document"

class RepoFactory
  def self.create(klass, location, options)
    Object.const_get(klass).new(location, options)
  end
end

class Repo
  include Enumerable

  attr_reader :location
  attr_reader :origin
  attr_reader :documents
  attr_reader :repo_name
  attr_reader :klass
  attr_reader :fachklassen_strings
  attr_reader :textbausteine
  attr_accessor :category
  attr_accessor :enabled

  # Angabe des Pfads zum Repo
  def initialize(location, options)
    @location = location
    @origin = options[:origin]
    @repo_name = File.basename location
    @documents = get_repo_files
    @fachklassen_strings = get_fachklassen_strings
    @textbausteine = get_textbausteine
    @enabled = true
  end

  def check_and_load_yaml(files)
    file = files.find do |f|
      File.exist? f
    end
    YAML.load_file file if file
  end

  def abschnitt_fehlt
    Warnung.add "Dokument", "Schüler ohne Abschnitt. Fehler bei Bildungsgang/Textbausteinen"
  end

  def get_textbausteine
    f1 = @location+"/config/textbausteine.yml"
    f2 = @location+"/textbausteine.yml"
    check_and_load_yaml([f1, f2])
  end

  def textbaustein(abschnitt, key)
    return abschnitt_fehlt if abschnitt.nil?
    string = @textbausteine['Textbausteine'][key]
    if string.class == Hash
      zul_jahr = string.keys.sort.reverse
      treffer = zul_jahr.find{|j| j <= abschnitt.jahr}
      string = string[treffer]
    end
    return "|"+string
  end

  def get_fachklassen_strings
    f1 = @location+"/config/fachklassen.yml"
    f2 = @location+"/fachklassen.yml"
    check_and_load_yaml([f1, f2])
  end

  def fachklasse_info(abschnitt, *keys)
    return abschnitt_fehlt if abschnitt.nil?
    if abschnitt.fachklasse.nil?
      Warnung.add(abschnitt.schueler.name, "Schüler#{abschnitt.schueler.geschlecht == 3 ? "":"in"} ist keiner Fachklasse zugeordnet")
      return "Fachklasse nicht angegeben"
    end
    kennung = abschnitt.fachklasse && abschnitt.fachklasse.kennung
    if @fachklassen_strings[kennung]
      string = @fachklassen_strings[kennung]
    else
      string = @fachklassen_strings["default"]
      Warnung.add("Dokument", "Es sollten Einstellungen für den Bildungsgang #{abschnitt.fachklasse.kennung} in der Datei config/strings.yml vorgenommen werden") if @fachklassen_strings[kennung].nil?
    end
    return if string[keys.first].nil?
    keys.each {|k| string = string.fetch(k,nil)}
    if string.class == Hash
      zul_jahr = string.keys.sort.reverse
      treffer = zul_jahr.find{|j| j <= abschnitt.schueler.beginn_bildungsgang.year}
      string = string[treffer] || Warnung.add("Bildungsgang", "Es wurde kein gültiges Jahr für diesen String gefunden. Bitte anlegen")
    end
    return string
  end

  # alle template-Dateien eines Repos zurückgeben
  def get_repo_files
    return [] if File.exist?(@location+"/plugin.rb") || File.exist?(@location+"/"+@repo_name+".rb")
    files = Array.new
    files += Dir[location+"/views/*"].reject{|f| File.directory?(f) || !f[".slim"] || f['layout.slim']}
    files += Dir[location+"/*"].reject{|f| File.directory?(f) || !f[".slim"] || f['layout.slim']}
    files.map{|f| Document.new f}
  end

  def update
    @dokumente = get_repo_files
  end

  def each
    @documents && @documents.each{ |d| yield d }
  end

  def enabled?
    @enabled
  end
end

class LocalRepo < Repo; end

class DisabledRepo
  attr_reader :location
  attr_reader :repo_name
  attr_reader :origin
  attr_reader :category

  def initialize(location, options)
    @location = location
    @enabled = false
    @category = :disabled
    @origin = options[:origin]
    @repo_name = File.basename location
  end

  def enabled?
    @enabled
  end
end

class GitRepo < Repo
  def initialize(location, options)
    @klass = :GitRepo
    super
  end

  def update
    g = Git.open @location
    g.pull
    super
  end
end


text:
package firebase

import (
	"time"
)

const TOKEN_VERSION = 0
const TOKEN_SEP = "."

type Option struct {
	Key   string
	Value string
}

type TokenOptions struct {
	Issued  int64                  `json:"iat"`   // iat
	Data    map[string]interface{} `json:"d"`     // d
	Version int                    `json:"v"`     // v
	Debug   bool                   `json:"debug"` // debug
}

type TokenHeaders struct {
	Type string `json:"typ"`
	Algo string `json:"alg"`
}

func CreateTokenHeaders() TokenHeaders {
	return TokenHeaders{
		Type: "JWT",
		Algo: "HS256",
	}
}

func CreateTokenOptions(data map[string]interface{}, debug bool) TokenOptions {
	return TokenOptions{
		Issued:  time.Now().Unix(),
		Data:    data,
		Version: TOKEN_VERSION,
		Debug:   debug,
	}
}


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}

DOCUMENTATION = '''
---
module: vmware_guest_file_operation
short_description: Files operation in a VMware guest operating system without network
description:
    - Module to copy a file to a VM, fetch a file from a VM and create or delete a directory in the guest OS.
version_added: "2.5"
author:
  - Stéphane Travassac (@stravassac)
notes:
    - Tested on vSphere 6
    - Only the first match against vm_id is used, even if there are multiple matches
requirements:
    - "python >= 2.6"
    - PyVmomi
    - requests
options:
    datacenter:
        description:
            - The datacenter hosting the virtual machine.
            - If set, it will help to speed up virtual machine search.
    cluster:
        description:
            - The cluster hosting the virtual machine.
            - If set, it will help to speed up virtual machine search.
    folder:
        description:
            - Destination folder, absolute path to find an existing guest or create the new guest.
            - The folder should include the datacenter. ESX's datacenter is ha-datacenter
            - Used only if C(vm_id_type) is C(inventory_path).
            - 'Examples:'
            - '   folder: /ha-datacenter/vm'
            - '   folder: ha-datacenter/vm'
            - '   folder: /datacenter1/vm'
            - '   folder: datacenter1/vm'
            - '   folder: /datacenter1/vm/folder1'
            - '   folder: datacenter1/vm/folder1'
            - '   folder: /folder1/datacenter1/vm'
            - '   folder: folder1/datacenter1/vm'
            - '   folder: /folder1/datacenter1/vm/folder2'
            - '   folder: vm/folder2'
            - '   folder: folder2'
    vm_id:
        description:
            - Name of the virtual machine to work with.
        required: True
    vm_id_type:
        description:
            - The VMware identification method by which the virtual machine will be identified.
        default: vm_name
        choices:
            - 'uuid'
            - 'instance_uuid'
            - 'dns_name'
            - 'inventory_path'
            - 'vm_name'
    vm_username:
        description:
            - The user to login in to the virtual machine.
        required: True
    vm_password:
        description:
            - The password used to login-in to the virtual machine.
        required: True
    directory:
        description:
            - Create or delete a directory.
            - Can be used to create temp directory inside guest using mktemp operation.
            - mktemp sets variable C(dir) in the result with the name of the new directory.
            - mktemp operation option is added in version 2.8
            - 'Valid attributes are:'
            - '  operation (str): Valid values are: create, delete, mktemp'
            - '  path (str): directory path (required for create or remove)'
            - '  prefix (str): temporary directory prefix (required for mktemp)'
            - '  suffix (str): temporary directory suffix (required for mktemp)'
            - '  recurse (boolean): Not required, default (false)'
        required: False
    copy:
        description:
            - Copy file to vm without requiring network.
            - 'Valid attributes are:'
            - '  src: file source absolute or relative'
            - '  dest: file destination, path must be exist'
            - '  overwrite: False or True (not required, default False)'
        required: False
    fetch:
        description:
            - Get file from virtual machine without requiring network.
            - 'Valid attributes are:'
            - '  src: The file on the remote system to fetch. This I(must) be a file, not a directory'
            - '  dest: file destination on localhost, path must be exist'
        required: False
        version_added: 2.5

extends_documentation_fragment: vmware.documentation
'''

EXAMPLES = '''
- name: Create directory inside a vm
  vmware_guest_file_operation:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    datacenter: "{{ datacenter_name }}"
    validate_certs: no
    vm_id: "{{ guest_name }}"
    vm_username: "{{ guest_username }}"
    vm_password: "{{ guest_userpassword }}"
    directory:
      path: "/test"
      operation: create
      recurse: no
  delegate_to: localhost

- name: copy file to vm
  vmware_guest_file_operation:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    datacenter: "{{ datacenter_name }}"
    vm_id: "{{ guest_name }}"
    vm_username: "{{ guest_username }}"
    vm_password: "{{ guest_userpassword }}"
    copy:
        src: "files/test.zip"
        dest: "/root/test.zip"
        overwrite: False
  delegate_to: localhost

- name: fetch file from vm
  vmware_guest_file_operation:
    hostname: "{{ vcenter_hostname }}"
    username: "{{ vcenter_username }}"
    password: "{{ vcenter_password }}"
    datacenter: "{{ datacenter_name }}"
    vm_id: "{{ guest_name }}"
    vm_username: "{{ guest_username }}"
    vm_password: "{{ guest_userpassword }}"
    fetch:
        src: "/root/test.zip"
        dest: "files/test.zip"
  delegate_to: localhost
'''

RETURN = r'''
'''

try:
    from pyVmomi import vim, vmodl
except ImportError:
    pass

import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils import urls
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.vmware import (PyVmomi, find_cluster_by_name, find_datacenter_by_name,
                                         find_vm_by_id, vmware_argument_spec)

class VmwareGuestFileManager(PyVmomi):
    def __init__(self, module):
        super(VmwareGuestFileManager, self).__init__(module)
        datacenter_name = module.params['datacenter']
        cluster_name = module.params['cluster']
        folder = module.params['folder']

        datacenter = None
        if datacenter_name:
            datacenter = find_datacenter_by_name(self.content, datacenter_name)
            if not datacenter:
                module.fail_json(msg="Unable to find %(datacenter)s datacenter" % module.params)

        cluster = None
        if cluster_name:
            cluster = find_cluster_by_name(self.content, cluster_name, datacenter)
            if not cluster:
                module.fail_json(msg="Unable to find %(cluster)s cluster" % module.params)

        if module.params['vm_id_type'] == 'inventory_path':
            vm = find_vm_by_id(self.content, vm_id=module.params['vm_id'], vm_id_type="inventory_path", folder=folder)
        else:
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type=module.params['vm_id_type'],
                               datacenter=datacenter,
                               cluster=cluster)

        if not vm:
            module.fail_json(msg='Unable to find virtual machine.')

        self.vm = vm
        try:
            result = dict(changed=False)
            if module.params['directory']:
                result = self.directory()
            if module.params['copy']:
                result = self.copy()
            if module.params['fetch']:
                result = self.fetch()
            module.exit_json(**result)
        except vmodl.RuntimeFault as runtime_fault:
            module.fail_json(msg=to_native(runtime_fault.msg))
        except vmodl.MethodFault as method_fault:
            module.fail_json(msg=to_native(method_fault.msg))
        except Exception as e:
            module.fail_json(msg=to_native(e))

    def directory(self):
        result = dict(changed=True, uuid=self.vm.summary.config.uuid)
        vm_username = self.module.params['vm_username']
        vm_password = self.module.params['vm_password']

        recurse = bool(self.module.params['directory']['recurse'])
        operation = self.module.params['directory']['operation']
        path = self.module.params['directory']['path']
        prefix = self.module.params['directory']['prefix']
        suffix = self.module.params['directory']['suffix']
        creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)
        file_manager = self.content.guestOperationsManager.fileManager
        if operation in ("create", "mktemp"):
            try:
                if operation == "create":
                    file_manager.MakeDirectoryInGuest(vm=self.vm,
                                                      auth=creds,
                                                      directoryPath=path,
                                                      createParentDirectories=recurse)
                else:
                    newdir = file_manager.CreateTemporaryDirectoryInGuest(vm=self.vm, auth=creds,
                                                                          prefix=prefix, suffix=suffix)
                    result['dir'] = newdir
            except vim.fault.FileAlreadyExists as file_already_exists:
                result['changed'] = False
                result['msg'] = "Guest directory %s already exist: %s" % (path,
                                                                          to_native(file_already_exists.msg))
            except vim.fault.GuestPermissionDenied as permission_denied:
                self.module.fail_json(msg="Permission denied for path %s : %s" % (path,
                                                                                to_native(permission_denied.msg)),
                                      uuid=self.vm.summary.config.uuid)
            except vim.fault.InvalidGuestLogin as invalid_guest_login:
                self.module.fail_json(msg="Invalid guest login for user %s : %s" % (vm_username,
                                                                                to_native(invalid_guest_login.msg)),
                                      uuid=self.vm.summary.config.uuid)
            # other exceptions
            except Exception as e:
                self.module.fail_json(msg="Failed to Create directory into VM VMware exception : %s" % to_native(e),
                                      uuid=self.vm.summary.config.uuid)

        if operation == "delete":
            try:
                file_manager.DeleteDirectoryInGuest(vm=self.vm, auth=creds, directoryPath=path,
                                                    recursive=recurse)
            except vim.fault.FileNotFound as file_not_found:
                result['changed'] = False
                result['msg'] = "Guest directory %s not exists %s" % (path,
                                                                      to_native(file_not_found.msg))
            except vim.fault.FileFault as e:
                self.module.fail_json(msg="FileFault : %s" % e.msg,
                                      uuid=self.vm.summary.config.uuid)
            except vim.fault.GuestPermissionDenied as permission_denied:
                self.module.fail_json(msg="Permission denied for path %s : %s" % (path,
                                                                                to_native(permission_denied.msg)),
                                      uuid=self.vm.summary.config.uuid)
            except vim.fault.InvalidGuestLogin as invalid_guest_login:
                self.module.fail_json(msg="Invalid guest login for user %s : %s" % (vm_username,
                                                                                to_native(invalid_guest_login.msg)),
                                      uuid=self.vm.summary.config.uuid)
            # other exceptions
            except Exception as e:
                self.module.fail_json(msg="Failed to Delete directory into Vm VMware exception : %s" % to_native(e),
                                      uuid=self.vm.summary.config.uuid)

        return result

    def fetch(self):
        result = dict(changed=True, uuid=self.vm.summary.config.uuid)
        vm_username = self.module.params['vm_username']
        vm_password = self.module.params['vm_password']
        hostname = self.module.params['hostname']
        dest = self.module.params["fetch"]['dest']
        src = self.module.params['fetch']['src']
        creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)
        file_manager = self.content.guestOperationsManager.fileManager

        try:
            fileTransferInfo = file_manager.InitiateFileTransferFromGuest(vm=self.vm, auth=creds,
                                                                          guestFilePath=src)
            url = fileTransferInfo.url
            url = url.replace("*", hostname)
            resp, info = urls.fetch_url(self.module, url, method="GET")
            try:
                with open(dest, "wb") as local_file:
                    local_file.write(resp.read())
            except Exception as e:
                self.module.fail_json(msg="local file write exception : %s" % to_native(e),
                                      uuid=self.vm.summary.config.uuid)
        except vim.fault.FileNotFound as file_not_found:
            self.module.fail_json(msg="Guest file %s does not exist : %s" % (src, to_native(file_not_found.msg)),
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.FileFault as e:
            self.module.fail_json(msg="FileFault : %s" % to_native(e.msg),
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.GuestPermissionDenied:
            self.module.fail_json(msg="Permission denied to fetch file %s" % src,
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.InvalidGuestLogin:
            self.module.fail_json(msg="Invalid guest login for user %s" % vm_username,
                                  uuid=self.vm.summary.config.uuid)
        # other exceptions
        except Exception as e:
            self.module.fail_json(msg="Failed to Fetch file from Vm VMware exception : %s" % to_native(e),
                                  uuid=self.vm.summary.config.uuid)

        return result

    def copy(self):
        result = dict(changed=True, uuid=self.vm.summary.config.uuid)
        vm_username = self.module.params['vm_username']
        vm_password = self.module.params['vm_password']
        hostname = self.module.params['hostname']
        overwrite = self.module.params["copy"]["overwrite"]
        dest = self.module.params["copy"]['dest']
        src = self.module.params['copy']['src']
        b_src = to_bytes(src, errors='surrogate_or_strict')

        if not os.path.exists(b_src):
            self.module.fail_json(msg="Source %s not found" % src)
        if not os.access(b_src, os.R_OK):
            self.module.fail_json(msg="Source %s not readable" % src)
        if os.path.isdir(b_src):
            self.module.fail_json(msg="copy does not support copy of directory: %s" % src)

        data = None
        with open(b_src, "r") as local_file:
            data = local_file.read()
        file_size = os.path.getsize(b_src)

        creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)
        file_attributes = vim.vm.guest.FileManager.FileAttributes()
        file_manager = self.content.guestOperationsManager.fileManager
        try:
            url = file_manager.InitiateFileTransferToGuest(vm=self.vm, auth=creds, guestFilePath=dest,
                                                           fileAttributes=file_attributes, overwrite=overwrite,
                                                           fileSize=file_size)
            url = url.replace("*", hostname)
            resp, info = urls.fetch_url(self.module, url, data=data, method="PUT")

            status_code = info["status"]
            if status_code != 200:
                self.module.fail_json(msg='problem during file transfer, http message:%s' % info,
                                      uuid=self.vm.summary.config.uuid)
        except vim.fault.FileAlreadyExists:
            result['changed'] = False
            result['msg'] = "Guest file %s already exists" % dest
            return result
        except vim.fault.FileFault as e:
            self.module.fail_json(msg="FileFault:%s" % to_native(e.msg),
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.GuestPermissionDenied as permission_denied:
            self.module.fail_json(msg="Permission denied to copy file into "
                                      "destination %s : %s" % (dest, to_native(permission_denied.msg)),
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.InvalidGuestLogin as invalid_guest_login:
            self.module.fail_json(msg="Invalid guest login for user"
                                      " %s : %s" % (vm_username, to_native(invalid_guest_login.msg)))
        # other exceptions
        except Exception as e:
            self.module.fail_json(msg="Failed to Copy file to Vm VMware exception : %s" % to_native(e),
                                  uuid=self.vm.summary.config.uuid)
        return result

def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(dict(
        datacenter=dict(type='str'),
        cluster=dict(type='str'),
        folder=dict(type='str'),
        vm_id=dict(type='str', required=True),
        vm_id_type=dict(
            default='vm_name',
            type='str',
            choices=['inventory_path', 'uuid', 'instance_uuid', 'dns_name', 'vm_name']),
        vm_username=dict(type='str', required=True),
        vm_password=dict(type='str', no_log=True, required=True),
        directory=dict(
            type='dict',
            default=None,
            options=dict(
                operation=dict(required=True, type='str', choices=['create', 'delete', 'mktemp']),
                path=dict(required=False, type='str'),
                prefix=dict(required=False, type='str'),
                suffix=dict(required=False, type='str'),
                recurse=dict(required=False, type='bool', default=False)
            )
        ),
        copy=dict(
            type='dict',
            default=None,
            options=dict(src=dict(required=True, type='str'),
                         dest=dict(required=True, type='str'),
                         overwrite=dict(required=False, type='bool', default=False)
                         )
        ),
        fetch=dict(
            type='dict',
            default=None,
            options=dict(
                src=dict(required=True, type='str'),
                dest=dict(required=True, type='str'),
            )
        )
    )
    )

    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False,
                           required_if=[['vm_id_type', 'inventory_path', ['folder']]],
                           mutually_exclusive=[['directory', 'copy', 'fetch']],
                           required_one_of=[['directory', 'copy', 'fetch']],
                           )

    if module.params['directory']:
        if module.params['directory']['operation'] in ('create', 'delete') and not module.params['directory']['path']:
            module.fail_json(msg='directory.path is required when operation is "create" or "delete"')
        if module.params['directory']['operation'] == 'mktemp' and not (module.params['directory']['prefix'] and module.params['directory']['suffix']):
            module.fail_json(msg='directory.prefix and directory.suffix are required when operation is "mktemp"')

    if module.params['vm_id_type'] == 'inventory_path' and not module.params['folder']:
        module.fail_json(msg='Folder is required parameter when vm_id_type is inventory_path')

    vmware_guest_file_manager = VmwareGuestFileManager(module)

if __name__ == '__main__':
    main()


text:
package org.apache.isis.applib.fixturescripts;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collections;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.google.common.io.CharSource;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.format.ISODateTimeFormat;

public class ExecutionParameters {

    private final static Pattern keyEqualsValuePattern = Pattern.compile("([^=]*)=(.*)");

    private final String parameters;
    private final Map<String, String> parameterMap;

    public ExecutionParameters(final String parameters) {
        this.parameters = parameters;
        this.parameterMap = asKeyValueMap(parameters);
    }

    static Map<String, String> asKeyValueMap(final String parameters) {
        final Map<String, String> keyValues = Maps.newLinkedHashMap();
        if (parameters != null) {
            try {
                final ImmutableList<String> lines = CharSource.wrap(parameters).readLines();
                for (final String line : lines) {
                    if (line == null) {
                        continue;
                    }
                    final Matcher matcher = keyEqualsValuePattern.matcher(line);
                    if (matcher.matches()) {
                        keyValues.put(matcher.group(1).trim(), matcher.group(2).trim());
                    }
                }
            } catch (final IOException e) {
                // ignore, shouldn't happen
            }
        }
        return keyValues;
    }

    public String getParameters() {
        return parameters;
    }

    public String getParameter(final String parameterName) {
        return parameterMap.get(parameterName);
    }

    public <T> T getParameterAsT(final String parameterName, final Class<T> cls) {
        T value = null;
        if (Enum.class.isAssignableFrom(cls)) {
            Class enumClass = cls;
            value = (T) getParameterAsEnum(parameterName, enumClass);
        } else if (cls == Boolean.class) {
            value = (T) getParameterAsBoolean(parameterName);
        } else if (cls == Byte.class) {
            value = (T) getParameterAsByte(parameterName);
        } else if (cls == Short.class) {
            value = (T) getParameterAsShort(parameterName);
        } else if (cls == Integer.class) {
            value = (T) getParameterAsInteger(parameterName);
        } else if (cls == Long.class) {
            value = (T) getParameterAsLong(parameterName);
        } else if (cls == Float.class) {
            value = (T) getParameterAsFloat(parameterName);
        } else if (cls == Double.class) {
            value = (T) getParameterAsDouble(parameterName);
        } else if (cls == Character.class) {
            value = (T) getParameterAsCharacter(parameterName);
        } else if (cls == BigDecimal.class) {
            value = (T) getParameterAsBigDecimal(parameterName);
        } else if (cls == BigInteger.class) {
            value = (T) getParameterAsBigInteger(parameterName);
        } else if (cls == LocalDate.class) {
            value = (T) getParameterAsLocalDate(parameterName);
        } else if (cls == LocalDateTime.class) {
            value = (T) getParameterAsLocalDateTime(parameterName);
        } else if (cls == String.class) {
            value = (T) getParameter(parameterName);
        }
        return value;
    }

    public Boolean getParameterAsBoolean(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Boolean.valueOf(value);
    }

    public Byte getParameterAsByte(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Byte.valueOf(value);
    }

    public Short getParameterAsShort(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Short.valueOf(value);
    }

    public Integer getParameterAsInteger(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Integer.valueOf(value);
    }

    public Long getParameterAsLong(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Long.valueOf(value);
    }

    public Float getParameterAsFloat(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Float.valueOf(value);
    }

    public Double getParameterAsDouble(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Double.valueOf(value);
    }

    public Character getParameterAsCharacter(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return Character.valueOf(value.charAt(0));
    }

    public BigInteger getParameterAsBigInteger(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return new BigInteger(value);
    }

    public BigDecimal getParameterAsBigDecimal(final String parameterName) {
        final String value = getParameter(parameterName);
        if (Strings.isNullOrEmpty(value)) {
            return null;
        }
        return new BigDecimal(value);
    }

    public LocalDate getParameterAsLocalDate(final String parameterName) {
        final String value = getParameter(parameterName);
        if (value == null) {
            return null;
        }
        return LocalDate.parse(value);
    }

    public LocalDateTime getParameterAsLocalDateTime(final String parameterName) {
        final String value = getParameter(parameterName);
        if (value == null) {
            return null;
        }
        return LocalDateTime.parse(value);
    }

    public <T extends Enum<T>> T getParameterAsEnum(final String parameterName, final Class<T> enumClass) {
        final String value = getParameter(parameterName);
        return valueOfElseNull(enumClass, value);
    }

    private static <T extends Enum<T>> T valueOfElseNull(final Class<T> enumClass, final String value) {
        if (value == null) {
            return null;
        }
        final T[] enumConstants = enumClass.getEnumConstants();
        for (T enumConstant : enumConstants) {
            if (enumConstant.name().equals(value)) {
                return enumConstant;
            }
        }
        return null;
    }

    public Map<String, String> getParameterMap() {
        return Collections.unmodifiableMap(parameterMap);
    }

    public void setParameterIfNotPresent(final String parameterName, final String parameterValue) {
        if (parameterName == null) {
            throw new IllegalArgumentException("parameterName required");
        }
        if (parameterValue == null) {
            // ignore
            return;
        }
        if (parameterMap.containsKey(parameterName)) {
            // ignore; the existing parameter take precedence
            return;
        }
        parameterMap.put(parameterName, parameterValue);
    }

    public void setParameter(final String parameterName, final Boolean parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Byte parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Short parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Integer parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Long parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Float parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Double parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Character parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final BigInteger parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final java.util.Date parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final java.sql.Date parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final LocalDate parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final LocalDateTime parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final DateTime parameterValue) {
        final StringBuffer buf = new StringBuffer();
        ISODateTimeFormat.dateTimeParser().printTo(buf, parameterValue);
        setParameter(parameterName, parameterValue != null ? buf.toString() : null);
    }

    public void setParameter(final String parameterName, final BigDecimal parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.toString() : null);
    }

    public void setParameter(final String parameterName, final Enum<?> parameterValue) {
        setParameter(parameterName, parameterValue != null ? parameterValue.name() : null);
    }

    public void setParameter(final String parameterName, final String parameterValue) {
        if (parameterName == null) {
            throw new IllegalArgumentException("parameterName required");
        }
        if (parameterValue == null) {
            // ignore
            return;
        }
        parameterMap.put(parameterName, parameterValue);
    }

}


text:
import ctypes
import mock
import os
import pytest
import subprocess
import sys
import tempfile
import time

from cuckoo.common.exceptions import CuckooStartupError
from cuckoo.common.files import Files
from cuckoo.common.structures import Structure
from cuckoo.main import cuckoo_create
from cuckoo.misc import (
    dispatch, cwd, set_cwd, getuser, mkdir, Popen, drop_privileges, make_list,
    HAVE_PWD, is_linux, is_windows, is_macosx, decide_cwd, Pidfile,
    format_command
)

def return_value(value):
    return value

def sleep2(value):
    time.sleep(2)
    return value

def test_dispatch():
    assert dispatch(return_value, (1,)) == 1
    assert dispatch(return_value, ("foo",)) == "foo"

    assert dispatch(sleep2, (2,)) == 2
    assert dispatch(sleep2, (2,), timeout=1) is None

    with pytest.raises(RuntimeError):
        dispatch(None, args=None)

    with pytest.raises(RuntimeError):
        dispatch(None, kwargs=None)

    with pytest.raises(RuntimeError):
        dispatch(None, process=False)

def test_cwd():
    set_cwd("/tmp/foo")
    assert cwd() == "/tmp/foo"
    assert cwd("a") == os.path.join("/tmp/foo", "a")
    assert cwd("a", "b") == os.path.join("/tmp/foo", "a", "b")

    set_cwd("/home/user/.cuckoo", "~/.cuckoo")
    assert cwd(raw=True) == "~/.cuckoo"
    assert cwd(root=True) == "/home/user/.cuckoo"
    assert cwd("dump.pcap", analysis=1234) == os.path.join(
        "/home/user/.cuckoo", "storage", "analyses", "1234", "dump.pcap"
    )

    assert os.path.exists(cwd("guids.txt", private=True))

    with pytest.raises(RuntimeError):
        cwd("foo", private=False)

    with pytest.raises(RuntimeError):
        cwd("foo", raw=False)

    with pytest.raises(RuntimeError):
        cwd("foo", root=False)

    with pytest.raises(RuntimeError):
        cwd("foo", analysis=None)

@pytest.mark.skipif(not HAVE_PWD, reason="This test is not for Windows")
def test_getuser():
    # TODO This probably doesn't work on all platforms.
    assert getuser() == subprocess.check_output(["id", "-un"]).strip()

def test_mkdir():
    dirpath = tempfile.mkdtemp()
    assert os.path.isdir(dirpath)
    mkdir(dirpath)
    assert os.path.isdir(dirpath)

    dirpath = tempfile.mktemp()
    assert not os.path.exists(dirpath)
    mkdir(dirpath)
    assert os.path.isdir(dirpath)

@pytest.mark.skipif("sys.platform != 'win32'")
def test_is_windows():
    assert is_windows() is True
    assert is_linux() is False
    assert is_macosx() is False

@pytest.mark.skipif("sys.platform != 'darwin'")
def test_is_macosx():
    assert is_windows() is False
    assert is_linux() is False
    assert is_macosx() is True

@pytest.mark.skipif("sys.platform != 'linux2'")
def test_is_linux():
    assert is_windows() is False
    assert is_linux() is True
    assert is_macosx() is False

def test_platforms():
    """Ensure that the above unit tests are complete (for our supported
    platforms)."""
    assert sys.platform in ("win32", "linux2", "darwin")

def test_popen():
    """Ensures that Popen is working properly."""
    with mock.patch("subprocess.Popen") as p:
        p.return_value = None
        Popen(["foo", "bar"])

    p.assert_called_once_with(["foo", "bar"])

    with mock.patch("subprocess.Popen") as p:
        p.return_value = None
        Popen(
            ["foo", "bar"], close_fds=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

    if is_windows():
        p.assert_called_once_with(
            ["foo", "bar"],
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
    else:
        p.assert_called_once_with(
            ["foo", "bar"], close_fds=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )

    # Test that the method actually works.
    p = Popen("echo 123", stdout=subprocess.PIPE, shell=True)
    out, err = p.communicate()
    assert out.strip() == "123" and not err

    # The following would normally throw an exception on Windows.
    p = Popen("echo 1234", close_fds=True, stdout=subprocess.PIPE, shell=True)
    out, err = p.communicate()
    assert out.strip() == "1234" and not err

def test_decide_cwd():
    orig_cuckoo_cwd = os.environ.pop("CUCKOO_CWD", None)
    orig_cuckoo = os.environ.pop("CUCKOO", None)

    dirpath1 = tempfile.mkdtemp()
    dirpath2 = tempfile.mkdtemp()
    dirpath3 = tempfile.mkdtemp()

    assert decide_cwd(dirpath1) == dirpath1

    assert decide_cwd() == os.path.abspath(os.path.expanduser("~/.cuckoo"))

    curdir = os.getcwd()
    os.chdir(dirpath2)
    open(".cwd", "wb").write("A"*40)

    assert decide_cwd() == os.path.abspath(".")
    os.chdir(curdir)

    os.environ["CUCKOO"] = dirpath2
    assert decide_cwd(dirpath1) == dirpath1
    assert decide_cwd() == dirpath2

    os.environ["CUCKOO_CWD"] = dirpath3
    assert decide_cwd(dirpath1) == dirpath1
    assert decide_cwd() == dirpath3

    with pytest.raises(CuckooStartupError) as e:
        decide_cwd(tempfile.mktemp(), exists=True)
    e.match("is not present")

    with pytest.raises(CuckooStartupError) as e:
        decide_cwd(dirpath1, exists=True)
    e.match("is not a proper CWD")

    Files.create(dirpath1, ".cwd", "A"*40)
    assert decide_cwd(dirpath1, exists=True) == dirpath1

    # Cleanup.
    if orig_cuckoo:
        os.environ["CUCKOO"] = orig_cuckoo
    else:
        os.environ.pop("CUCKOO", None)

    if orig_cuckoo_cwd:
        os.environ["CUCKOO_CWD"] = orig_cuckoo_cwd
    else:
        os.environ.pop("CUCKOO_CWD", None)

@pytest.mark.skipif("sys.platform != 'linux2'")
@mock.patch("cuckoo.misc.pwd")
@mock.patch("cuckoo.misc.os")
def test_drop_privileges(p, q):
    drop_privileges("username")
    q.getpwnam.assert_called_once_with("username")
    p.setgroups.assert_called_once()
    p.setgid.assert_called_once()
    p.setuid.assert_called_once()
    p.putenv.assert_called_once()

def test_structure():
    class S1(Structure):
        _pack_ = 1
        _fields_ = [
            ("a", ctypes.c_ubyte),
            ("b", ctypes.c_ushort),
            ("c", ctypes.c_uint),
            ("d", ctypes.c_ubyte * 128),
        ]

    class S2(Structure):
        _pack_ = 1
        _fields_ = [
            ("a", S1),
            ("b", ctypes.c_ulonglong),
            ("c", ctypes.c_char * 32),
        ]

    a = S2.from_buffer_copy("A"*175)
    assert a.a.a == 0x41
    assert a.a.b == 0x4141
    assert a.a.c == 0x41414141
    assert a.a.d[:] == [0x41] * 128
    assert a.b == 0x4141414141414141
    assert a.c == "A"*32
    assert a.as_dict() == {
        "a": {
            "a": 0x41,
            "b": 0x4141,
            "c": 0x41414141,
            "d": [0x41] * 128,
        },
        "b": 0x4141414141414141,
        "c": "A"*32,
    }

def test_create_pidfile():
    set_cwd(tempfile.mkdtemp())
    cuckoo_create()

    Pidfile("test1").create()
    assert int(open(cwd("pidfiles", "test1.pid"), "rb").read()) == os.getpid()

def test_remove_pidfile():
    set_cwd(tempfile.mkdtemp())
    cuckoo_create()

    Pidfile("test2").create()
    assert os.path.exists(cwd("pidfiles", "test2.pid"))

    Pidfile("test2").remove()
    assert not os.path.exists(cwd("pidfiles", "test2.pid"))

def test_pidfile_exists_false():
    set_cwd(tempfile.mkdtemp())
    cuckoo_create()
    assert not Pidfile("test3").exists()

def test_pidfile_exists_true():
    set_cwd(tempfile.mkdtemp())
    cuckoo_create()

    p = Pidfile("test4")
    p.create()
    assert p.exists() and p.pid == os.getpid()

def test_pidfile_none():
    set_cwd(tempfile.mkdtemp())
    cuckoo_create()

    p = Pidfile("test5")
    p.create()

    open(cwd("pidfiles", "test5.pid"), "wb").write("notapid")
    assert p.read() is None

def test_proc_exists():
    assert Pidfile("hello").proc_exists(os.getpid())
    # Chances are possible, but slim.
    assert not Pidfile("hello").proc_exists(13337)

    assert not Pidfile("hello)").proc_exists(None)
    assert not Pidfile("hello)").proc_exists("")

@mock.patch("cuckoo.misc.sys")
def test_pid_exists_unsupported_platform(p):
    p.platform = "DogeOS"
    assert Pidfile("hello").proc_exists(os.getpid()) is None

def test_active_pids():
    set_cwd(tempfile.mkdtemp())
    cuckoo_create()

    Pidfile("test6").create()
    assert Pidfile.get_active_pids() == {
        "test6": os.getpid(),
    }

def test_make_list():
    assert make_list("hello") == ["hello"]
    assert make_list(1) == [1]
    assert make_list((1, 2)) == [1, 2]
    assert make_list([3, 4]) == [3, 4]

def test_format_command():
    set_cwd(tempfile.mkdtemp(), ".")
    assert format_command("community") == "cuckoo community"

    set_cwd(tempfile.mkdtemp(), "~/.cuckoo")
    assert format_command("community") == "cuckoo community"

    dirpath = tempfile.mkdtemp()
    set_cwd(dirpath, dirpath)
    assert format_command("community") == "cuckoo --cwd %s community" % cwd()

    dirpath = tempfile.mkdtemp("foo bar")
    set_cwd(dirpath, dirpath)
    assert format_command("community") == 'cuckoo --cwd "%s" community' % cwd()

    dirpath = tempfile.mkdtemp("foo ' bar")
    set_cwd(dirpath, dirpath)
    assert format_command("community") == 'cuckoo --cwd "%s" community' % cwd()


text:
/*
 * jsPlumb 1.0.4-RC1
 *
 * Provides a way to visually connect elements on an HTML page.
 *
 * http://morrisonpitt.com/jsPlumb/demo.html
 * http://code.google.com/p/jsPlumb
 *
 */
if (!Array.prototype.indexOf) {
	Array.prototype.indexOf = function( v, b, s ) {
	 for( var i = +b || 0, l = this.length; i < l; i++ ) {
	  if( this[i]===v || s && this[i]==v ) { return i; }
	 }
	 return -1;
	};
}
(function() {

	var repaintFunction = function() { jsPlumb.repaintEverything(); };
	var automaticRepaint = true;
    function repaintEverything() {
    	if (automaticRepaint)
    		repaintFunction();
    };
    var resizeTimer = null;
    $(window).bind('resize', function() {
    	if (resizeTimer) clearTimeout(resizeTimer);
	    resizeTimer = setTimeout(repaintEverything, 100);
     });

	var connections = {};
	var draggableStates = {};
	var _draggableByDefault = true;
	var offsets = [];
	var sizes = [];

	var DEFAULT_NEW_CANVAS_SIZE = 1200; // only used for IE; a canvas needs a size before the init call to excanvas (for some reason. no idea why.)

	/**
     * applies all the styles to the given context.  this just wraps the $.extend function.
     *
     * @param context
     * @param styles
     */
    var applyPaintStyle = function(context, styles) {
        $.extend(context, styles);
    };

    /**
     * Handles the drawing of an element.
     * @param element jQuery element
     * @param ui UI object from jQuery's event system. may be null.
     */
    var _draw = function(element, ui) {
    	var id = element.attr("id");
    	var l = connections[id];
    	for (var i = 0; i < l.length; i++)
    		l[i].paint(id, ui);
    };

    /**
     * Sets whether or not the given element(s) should be draggable, regardless of what a particular
     * plumb command may request.
     *
     * @param element May be a string, an jQuery object, or a list of strings.
     * @param draggable Whether or not the given element(s) should be draggable.
     */
    var _setDraggable = function(element, draggable) {

    	var _helper = function(el, id) {
    		draggableStates[id] = draggable;
        	if (el.draggable) {
        		el.draggable("option", "disabled", !draggable);
        	}
    	};

    	if (typeof element == 'object' && element.length) {
    		for (var i = 0; i < element.length; i++) {
    			_helper($(element[i]), element[i]);
    		}
    	}
    	else {
	    	var el = typeof element == 'string' ? $("#" + element) : element;
	    	var id = el.attr("id");
	    	_helper(el, id);
    	}
    };

	/**
	 * private method to do the business of hiding/showing.
	 * @param elId Id of the element in question
	 * @param state String specifying a value for the css 'display' property ('block' or 'none').
	 */
	var _setVisible = function(elId, state) {
    	var jpcs = connections[elId];
    	for (var i = 0; i < jpcs.length; i++) {
    		jpcs[i].canvas.style.display=state;
    		if (jpcs[i].drawEndpoints) {
    			jpcs[i].sourceEndpointCanvas.style.display=state;
    			jpcs[i].targetEndpointCanvas.style.display=state;
    		}
    	}
    };

    /**
     * helper to create a canvas.
     * @param clazz optional class name for the canvas.
     */
    var _newCanvas = function(clazz) {
        var canvas = document.createElement("canvas");
        document.body.appendChild(canvas);
        canvas.style.position="absolute";
        if (clazz) { canvas.className=clazz; }

        if (/MSIE/.test(navigator.userAgent) && !window.opera) {
        	// for IE we have to set a big canvas size. actually you can override this, too, if 1200 pixels
        	// is not big enough for the biggest connector/endpoint canvas you have at startup.
        	jsPlumb.sizeCanvas(canvas, 0, 0, DEFAULT_NEW_CANVAS_SIZE, DEFAULT_NEW_CANVAS_SIZE);
        	canvas = G_vmlCanvasManager.initElement(canvas);
        }

        return canvas;
    };

    /**
     * helper to remove a canvas from the DOM.
     */
    var _removeCanvas = function(canvas) {
    	if (canvas != null) {
    		try { document.body.removeChild(canvas); }
    		catch (e) { }
    	}

    };

	/**
	 * generic anchor - can be situated anywhere.  params should contain three values, and may optionally have an 'offsets' argument:
	 *
	 * x - the x location of the anchor as a percentage of the total width.
	 * y - the y location of the anchor as a percentage of the total height.
	 * orientation - an [x,y] array indicating the general direction a connection from the anchor should go in.
	 * offsets - an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out.  may be null.
	 *
	 */
	var Anchor = function(params) {
		var self = this;
		this.x = params.x || 0; this.y = params.y || 0; this.orientation = params.orientation || [0,0]; this.offsets = params.offsets || [0,0];
		this.compute = function(xy, wh, txy, twh) {
			return [ xy[0] + (self.x * wh[0]) + self.offsets[0], xy[1] + (self.y * wh[1]) + self.offsets[1] ];
		}
	};

	/**
	 * jsPlumb public API
	 */
    var jsPlumb = window.jsPlumb = {

	connectorClass : '_jsPlumb_connector',
	endpointClass : '_jsPlumb_endpoint',
	DEFAULT_PAINT_STYLE : { lineWidth : 10, strokeStyle : "red" },
    DEFAULT_ENDPOINT_STYLE : { fillStyle : null }, // meaning it will be derived from the stroke style of the connector.
    DEFAULT_ENDPOINT_STYLES : [ null, null ], // meaning it will be derived from the stroke style of the connector.
    DEFAULT_DRAG_OPTIONS : { },
    DEFAULT_CONNECTOR : null,
    DEFAULT_ENDPOINT : null,
    DEFAULT_ENDPOINTS : [null, null],  // new in 0.0.4, the ability to specify diff. endpoints.  DEFAULT_ENDPOINT is here for backwards compatibility.

    /**
    * Places you can anchor a connection to.  These are helpers for common locations; they all just return an instance
    * of Anchor that has been configured appropriately.
    *
    * You can write your own one of these; you
    * just need to provide a 'compute' method and an 'orientation'.  so you'd say something like this:
    *
    * jsPlumb.Anchors.MY_ANCHOR = {
    * 	compute : function(xy, wh, txy, twh) { return some mathematics on those variables; },
    *   orientation : [ox, oy]
    * };
    *
    * compute takes the [x,y] position of the top left corner of the anchored element,
    * and the element's [width,height] (all in pixels), as well as the location and dimension of the element it's plumbed to,
    * and returns where the anchor should be located.
    *
    * the 'orientation' array (returned here as [ox,oy]) indicates the general direction a connection from the anchor
    * should go in, if possible.  it is an [x,y] matrix where a value of 0 means no preference,
    * -1 means go in a negative direction for the given axis, and 1 means go in a positive
    * direction.  so consider a TopCenter anchor: the orientation matrix for it is [0,-1],
    * meaning connections naturally want to go upwards on screen.  in a Bezier implementation, for example,
    * the curve would start out going in that direction, before bending towards the target anchor.
    */
    Anchors :
	{
    	TopCenter : new Anchor({x:0.5, y:0, orientation:[0,-1] }),
    	BottomCenter : new Anchor({x:0.5, y:1, orientation:[0, 1] }),
    	LeftMiddle: new Anchor({x:0, y:0.5, orientation:[-1,0] }),
    	RightMiddle : new Anchor({x:1, y:0.5, orientation:[1,0] }),
    	Center : new Anchor({x:0.5, y:0.5, orientation:[0,0] }),
    	TopRight : new Anchor({x:1, y:0, orientation:[0,-1] }),
    	BottomRight : new Anchor({x:1, y:1, orientation:[0,1] }),
    	TopLeft : new Anchor({x:0, y:0, orientation:[0,-1] }),
    	BottomLeft : new Anchor({x:0, y:1, orientation:[0,1] })
    },

    /**
     * Types of connectors, eg. Straight, Bezier.
     */
    Connectors :
    {
        /**
         * The Straight connector draws a simple straight line between the two anchor points.
         */
        Straight : function() {

    		var self = this;

            /**
             * Computes the new size and position of the canvas.
             * @param sourceAnchor Absolute position on screen of the source object's anchor.
             * @param targetAnchor Absolute position on screen of the target object's anchor.
             * @param positionMatrix  Indicates the relative positions of the left,top of the
             *  two plumbed objects.  so [0,0] indicates that the source is to the left of, and
             *  above, the target.  [1,0] means the source is to the right and above.  [0,1] means
             *  the source is to the left and below.  [1,1] means the source is to the right
             *  and below.  this is used to figure out which direction to draw the connector in.
             * @returns an array of positioning information.  the first two values are
             * the [left, top] absolute position the canvas should be placed on screen.  the
             * next two values are the [width,height] the canvas should be.  after that each
             * Connector can put whatever it likes into the array:it will be passed back in
             * to the paint call.  This particular function stores the origin and destination of
             * the line it is going to draw.  a more involved implementation, like a Bezier curve,
             * would store the control point info in this array too.
             */
            this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth) {
    			var w = Math.abs(sourcePos[0] - targetPos[0]);
                var h = Math.abs(sourcePos[1] - targetPos[1]);
                // these are padding to ensure the whole connector line appears
                var xo = 0.45 * w, yo = 0.45 * h;
                // these are padding to ensure the whole connector line appears
                w *= 1.9; h *=1.9;

                var x = Math.min(sourcePos[0], targetPos[0]) - xo;
                var y = Math.min(sourcePos[1], targetPos[1]) - yo;

                if (w < 2 * lineWidth) {
            		// minimum size is 2 * line Width
            		w = 2 * lineWidth;
            		// if we set this then we also have to place the canvas
            		x = sourcePos[0]  + ((targetPos[0] - sourcePos[0]) / 2) - lineWidth;
            		xo = (w - Math.abs(sourcePos[0]-targetPos[0])) / 2;;
            	}
                if (h < 2 * lineWidth) {
            		// minimum size is 2 * line Width
            		h = 2 * lineWidth;
            		// if we set this then we also have to place the canvas
            		y = sourcePos[1]  + ((targetPos[1] - sourcePos[1]) / 2) - lineWidth;
            		yo = (h - Math.abs(sourcePos[1]-targetPos[1])) / 2;;
            	}

                var sx = sourcePos[0] < targetPos[0] ? w-xo : xo;
                var sy = sourcePos[1] < targetPos[1] ? h-yo : yo;
                var tx = sourcePos[0] < targetPos[0] ? xo : w-xo;
                var ty = sourcePos[1] < targetPos[1] ? yo : h-yo;
                var retVal = [ x, y, w, h, sx, sy, tx, ty ];

                // return [canvasX, canvasY, canvasWidth, canvasHeight,
                //         sourceX, sourceY, targetX, targetY]
                return retVal;
            };

            this.paint = function(dimensions, ctx)
            {
                ctx.beginPath();
                ctx.moveTo(dimensions[4], dimensions[5]);
                ctx.lineTo(dimensions[6], dimensions[7]);
                ctx.stroke();
            };
        },

        /**
         * This Connector draws a Bezier curve with two control points.
         * @param curviness How 'curvy' you want the curve to be! This is a directive for the
         * placement of control points, not endpoints of the curve, so your curve does not
         * actually touch the given point, but it has the tendency to lean towards it.  the larger
         * this value, the greater the curve is pulled from a straight line.
         *
         * a future implementation of this could take the control points as arguments, rather
         * than fixing the curve to one basic shape.
         */
        Bezier : function(curviness) {

        	var self = this;
        	this.majorAnchor = curviness || 150;
            this.minorAnchor = 10;

            this._findControlPoint = function(point, sourceAnchorPosition, targetAnchorPosition, sourceAnchor, targetAnchor) {
            	// determine if the two anchors are perpendicular to each other in their orientation.  we swap the control
            	// points around if so (code could be tightened up)
            	var perpendicular = sourceAnchor.orientation[0] != targetAnchor.orientation[0] || sourceAnchor.orientation[1] == targetAnchor.orientation[1];
                var p = [];
                var ma = self.majorAnchor, mi = self.minorAnchor;
                if (!perpendicular) {
	                  if (sourceAnchor.orientation[0] == 0) // X
	                    p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + mi : point[0] - mi);
	                else p.push(point[0] - (ma * sourceAnchor.orientation[0]));

	                 if (sourceAnchor.orientation[1] == 0) // Y
	                	p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + mi : point[1] - mi);
	                else p.push(point[1] + (ma * targetAnchor.orientation[1]));
                }
                 else {
	                if (targetAnchor.orientation[0] == 0) // X
	                	p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + mi : point[0] - mi);
	                else p.push(point[0] + (ma * targetAnchor.orientation[0]));

	                if (targetAnchor.orientation[1] == 0) // Y
	                	p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + mi : point[1] - mi);
	                else p.push(point[1] + (ma * sourceAnchor.orientation[1]));
                 }

                return p;
            };

            this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth)
            {
            	lineWidth = lineWidth || 0;
                var w = Math.abs(sourcePos[0] - targetPos[0]) + lineWidth, h = Math.abs(sourcePos[1] - targetPos[1]) + lineWidth;
                var canvasX = Math.min(sourcePos[0], targetPos[0])-(lineWidth/2), canvasY = Math.min(sourcePos[1], targetPos[1])-(lineWidth/2);
                var sx = sourcePos[0] < targetPos[0] ? w - (lineWidth/2): (lineWidth/2), sy = sourcePos[1] < targetPos[1] ? h-(lineWidth/2) : (lineWidth/2);
                var tx = sourcePos[0] < targetPos[0] ? (lineWidth/2) : w-(lineWidth/2), ty = sourcePos[1] < targetPos[1] ? (lineWidth/2) : h-(lineWidth/2);
                var CP = self._findControlPoint([sx,sy], sourcePos, targetPos, sourceAnchor, targetAnchor);
                var CP2 = self._findControlPoint([tx,ty], targetPos, sourcePos, targetAnchor, sourceAnchor);
                var minx1 = Math.min(sx,tx); var minx2 = Math.min(CP[0], CP2[0]); var minx = Math.min(minx1,minx2);
                var maxx1 = Math.max(sx,tx); var maxx2 = Math.max(CP[0], CP2[0]); var maxx = Math.max(maxx1,maxx2);

                if (maxx > w) w = maxx;
                if (minx < 0) {
                    canvasX += minx; var ox = Math.abs(minx);
                    w += ox; CP[0] += ox; sx += ox; tx +=ox; CP2[0] += ox;
                }

                var miny1 = Math.min(sy,ty); var miny2 = Math.min(CP[1], CP2[1]); var miny = Math.min(miny1,miny2);
                var maxy1 = Math.max(sy,ty); var maxy2 = Math.max(CP[1], CP2[1]); var maxy = Math.max(maxy1,maxy2);
                if (maxy > h) h = maxy;
                if (miny < 0) {
                    canvasY += miny; var oy = Math.abs(miny);
                    h += oy; CP[1] += oy; sy += oy; ty +=oy; CP2[1] += oy;
                }

                // return [ canvasx, canvasy, canvasWidth, canvasHeight,
                //          sourceX, sourceY, targetX, targetY,
                //          controlPoint1_X, controlPoint1_Y, controlPoint2_X, controlPoint2_Y
                return [canvasX, canvasY, w, h, sx, sy, tx, ty, CP[0], CP[1], CP2[0], CP2[1] ];
            };

            this.paint = function(d, ctx) {
	            ctx.beginPath();
	            ctx.moveTo(d[4],d[5]);
	            ctx.bezierCurveTo(d[8],d[9],d[10],d[11],d[6],d[7]);
	            ctx.stroke();
            }
        }
    },

    /**
     * Types of endpoint UIs.  we supply three - a circle of default radius 10px, a rectangle of
     * default size 20x20, and an image (with no default).  you can supply others of these if you want to - see the documentation
     * for a howto.
     */
    Endpoints : {

    	/**
    	 * a round endpoint, with default radius 10 pixels.
    	 */
    	Dot : function(params) {

    		params = params || { radius:10 };
    		var self = this;
    		this.radius = params.radius;
    		var defaultOffset = 0.5 * this.radius;
    		var defaultInnerRadius = this.radius / 3;

    		var parseValue = function(value) {
    			try {
					return parseInt(value);
				}
				catch(e) {
					if (value.substring(value.length - 1) == '%')
						return parseInt(value.substring(0, value - 1));
				}
    		}

    		var calculateAdjustments = function(gradient) {
    			var offsetAdjustment = defaultOffset;
    			var innerRadius = defaultInnerRadius;
    			if (gradient.offset) offsetAdjustment = parseValue(gradient.offset);
            	if(gradient.innerRadius) innerRadius = parseValue(gradient.innerRadius);
            	return [offsetAdjustment, innerRadius];
    		};

	    	this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
    			var radius = endpointStyle.radius || self.radius;
    			var x = anchorPoint[0] - radius;
    			var y = anchorPoint[1] - radius;
    			jsPlumb.sizeCanvas(canvas, x, y, radius * 2, radius * 2);
    			var ctx = canvas.getContext('2d');
    			var style = {};
    			applyPaintStyle(style, endpointStyle);
    			if (style.fillStyle ==  null) style.fillStyle = connectorPaintStyle.strokeStyle;
    			applyPaintStyle(ctx, style);

    			var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
                if (endpointStyle.gradient && !ie) {

                	var adjustments = calculateAdjustments(endpointStyle.gradient);
                	var yAdjust = orientation[1] == 1 ? adjustments[0] * -1 : adjustments[0];
                	var xAdjust = orientation[0] == 1 ? adjustments[0] * -1:  adjustments[0];
                	var g = ctx.createRadialGradient(radius, radius, radius, radius + xAdjust, radius + yAdjust, adjustments[1]);
    	            for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
    	            	g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
    	            ctx.fillStyle = g;
                }

    			ctx.beginPath();
    			ctx.arc(radius, radius, radius, 0, Math.PI*2, true);
    			ctx.closePath();
    			ctx.fill();
	    	};
    	},

    	/**
    	 * A Rectangular endpoint, with default size 20x20.
    	 */
    	Rectangle : function(params) {

    		params = params || { width:20, height:20 };
    		var self = this;
    		this.width = params.width;
    		this.height = params.height;

	    	this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
    			var width = endpointStyle.width || self.width;
    			var height = endpointStyle.height || self.height;
    			var x = anchorPoint[0] - (width/2);
    			var y = anchorPoint[1] - (height/2);
    			jsPlumb.sizeCanvas(canvas, x, y, width, height);
    			var ctx = canvas.getContext('2d');
    			//todo: the fillStyle needs some thought. we want to support a few options:
    			// 1. nothing supplied; use the stroke color or the default if no stroke color.
    			// 2. a fill color supplied - use it
    			// 3. a gradient supplied - use it
    			// 4. setting the endpoint to the same color as the bg of the element it is attached to.
    			var style = {};
    			applyPaintStyle(style, endpointStyle);
    			if (style.fillStyle ==  null) style.fillStyle = connectorPaintStyle.strokeStyle;
    			applyPaintStyle(ctx, style);

    			var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
                if (endpointStyle.gradient && !ie) {
                	// first figure out which direction to run the gradient in (it depends on the orientation of the anchors)
                	var y1 = orientation[1] == 1 ? height : orientation[1] == 0 ? height / 2 : 0;
                	var y2 = orientation[1] == -1 ? height : orientation[1] == 0 ? height / 2 : 0;
                	var x1 = orientation[0] == 1 ? width : orientation[0] == 0 ? width / 2 : 0;
                	var x2 = orientation[0] == -1 ? width : orientation[0] == 0 ? height / 2 : 0;
    	            var g = ctx.createLinearGradient(x1,y1,x2,y2);
    	            for (var i = 0; i < endpointStyle.gradient.stops.length; i++)
    	            	g.addColorStop(endpointStyle.gradient.stops[i][0], endpointStyle.gradient.stops[i][1]);
    	            ctx.fillStyle = g;
                }

    			ctx.beginPath();
    			ctx.rect(0, 0, width, height);
    			ctx.closePath();
    			ctx.fill();
	    	};
    	},

    	/**
    	 * Image endpoint - draws an image as the endpoint.  You must provide a 'url' property in the params object..
    	 */
    	Image : function(params) {
    		var self = this;
    		this.img = new Image();
    		var ready = false;
    		this.img.onload = function() {
    			self.ready = true;
    		};
    		this.img.src = params.url;

    		var actuallyPaint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
    			var width = self.img.width || endpointStyle.width;
    			var height = self.img.height || endpointStyle.height;
    			var x = anchorPoint[0] - (width/2);
    			var y = anchorPoint[1] - (height/2);
    			jsPlumb.sizeCanvas(canvas, x, y, width, height);
    			var ctx = canvas.getContext('2d');
    			ctx.drawImage(self.img,0,0);
    		};

    		this.paint = function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) {
    			if (self.ready) {
	    			actuallyPaint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle)
    			}
    			else
    				window.setTimeout(function() {
    					self.paint(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle);
    				}, 200);
    		};
    	}
    },

    /**
     * establishes a connection between two elements.
     * @param params object containing setup for the connection.  see documentation.
     */
    connect : function(params) {
    	var jpc = new jsPlumbConnection(params);
    	var key = jpc.sourceId + "_" + jpc.targetId;
    	connections[key] = jpc;
    	var addToList = function(elId, jpc) {
    		var l = connections[elId];
    		if (l == null) {
    			l = [];
    			connections[elId] = l;
    		}
    		l.push(jpc);
    	};

    	// register this connection.
    	addToList(jpc.sourceId, jpc);
    	addToList(jpc.targetId, jpc);
    },

    /**
     * Remove one connection to an element.
     * @param sourceId id of the first window in the connection
     * @param targetId id of the second window in the connection
     */
    detach : function(sourceId, targetId) {
    	var jpcs = connections[sourceId];
    	var idx = -1;
    	for (var i = 0; i < jpcs.length; i++) {
    		if ((jpcs[i].sourceId == sourceId && jpcs[i].targetId == targetId) || (jpcs[i].targetId == sourceId && jpcs[i].sourceId == targetId)) {
    			_removeCanvas(jpcs[i].canvas);
    			if (jpcs[i].drawEndpoints) {
    				_removeCanvas(jpcs[i].targetEndpointCanvas);
    				_removeCanvas(jpcs[i].sourceEndpointCanvas);
    			}
    			idx = i;
    			break;
    		}
    	}
    	if (idx != -1)
    		jpcs.splice(idx, 1);

    	// todo - dragging?  if no more connections for an object turn off dragging by default, but
    	// allow an override on it?
    },

    /**
     * remove all an element's connections.
     */
    detachAll : function(elId) {
    	var jpcs = connections[elId];
    	for (var i = 0; i < jpcs.length; i++) {
	    	_removeCanvas(jpcs[i].canvas);
			if (jpcs[i].drawEndpoints) {
				_removeCanvas(jpcs[i].targetEndpointCanvas);
				_removeCanvas(jpcs[i].sourceEndpointCanvas);
			}
    	}
    	delete connections[elId];
    	connections[elId] = [];
    },

    /**
     * remove all connections.
     */
    detachEverything : function() {
    	for (var elId in connections) {
	    	var jpcs = connections[elId];
	    	if (jpcs.length) {
	    		try {
			    	for (var i = 0; i < jpcs.length; i++) {

				    	_removeCanvas(jpcs[i].canvas);
						if (jpcs[i].drawEndpoints) {
							_removeCanvas(jpcs[i].targetEndpointCanvas);
							_removeCanvas(jpcs[i].sourceEndpointCanvas);
						}

			    	}
	    		} catch (e) { }
	    	}
    	}
    	delete connections;
    	connections = [];
    },

    getConnections : function(elId) {
    	return connections[elId];
    },

    /**
     * Set an element's connections to be hidden.
     */
    hide : function(elId) {
    	_setVisible(elId, "none");
    },

    /**
     * Creates an anchor with the given params.
     * x - the x location of the anchor as a percentage of the total width.
	 * y - the y location of the anchor as a percentage of the total height.
	 * orientation - an [x,y] array indicating the general direction a connection from the anchor should go in.
	 * offsets - an [x,y] array of fixed offsets that should be applied after the x,y position has been figured out.  optional. defaults to [0,0].
     */
    makeAnchor : function(x, y, xOrientation, yOrientation, xOffset, yOffset) {
    	// backwards compatibility here.  we used to require an object passed in but that makes the call very verbose.  easier to use
    	// by just passing in four values.  but for backwards compatibility if we are given only one value we assume it's a call in the old form.
    	var params = {};
    	if (arguments.length == 1) $.extend(params, x);
    	else {
    		params = {x:x, y:y};
    		if (arguments.length >= 4) {
    			params.orientation = [arguments[2], arguments[3]];
    		}
    		if (arguments.length == 6) params.offsets = [arguments[4], arguments[5]];
    	}
    	return new Anchor(params);
    },

    /**
     * repaint element and its connections. element may be an id or the actual jQuery object.
     * this method gets new sizes for the elements before painting anything.
     */
    repaint : function(el) {
    	var _repaint = function(el, elId) {
	    	var jpcs = connections[elId];
	    	var idx = -1;
	    	var loc = {'absolutePosition': el.offset()};
	    	for (var i = 0; i < jpcs.length; i++) {
	    		jpcs[i].paint(elId, loc, true);
	    	}
    	};

    	var _processElement = function(el) {
    		var ele = typeof(el)=='string' ? $("#" + el) : el;
	    	var eleId = ele.attr("id");
	    	_repaint(ele, eleId);
    	};

    	// TODO: support a jQuery result object too!

    	// support both lists...
    	if (typeof el =='object') {
    		for (var i = 0; i < el.length; i++)
    			_processElement(el[i]);
    	} // ...and single strings.
    	else _processElement(el);
    },

    /**
     * repaint all connections.
     */
    repaintEverything : function() {
    	for (var elId in connections) {
	    	var jpcs = connections[elId];
	    	if (jpcs.length) {
	    		try {
			    	for (var i = 0; i < jpcs.length; i++) {
			    		jpcs[i].repaint();
			    	}
	    		} catch (e) { }
	    	}
    	}
    },

    /**
     * sets/unsets automatic repaint on window resize.
     */
    setAutomaticRepaint : function(value) {
    	automaticRepaint = value;
    },

    /**
     * Sets the default size jsPlumb will use for a new canvas (we create a square canvas so
     * one value is all that is required).  This is a hack for IE, because ExplorerCanvas seems
     * to need for a canvas to be larger than what you are going to draw on it at initialisation
     * time.  The default value of this is 1200 pixels, which is quite large, but if for some
     * reason you're drawing connectors that are bigger, you should adjust this value appropriately.
     */
    setDefaultNewCanvasSize : function(size) {
    	DEFAULT_NEW_CANVAS_SIZE = size;
    },

    /**
     * Sets whether or not a given element is draggable, regardless of what any plumb command
     * may request.
     */
    setDraggable: function(element, draggable) {
    	_setDraggable(element, draggable);
    },

    /**
     * Sets whether or not elements are draggable by default.  Default for this is true.
     */
    setDraggableByDefault: function(draggable) {
    	_draggableByDefault = draggable;
    },

    /**
     * Sets the function to fire when the window size has changed and a repaint was fired.
     */
    setRepaintFunction : function(f) {
    	repaintFunction = f;
    },

    /**
     * Set an element's connections to be visible.
     */
    show : function(elId) {
    	_setVisible(elId, "block");
    },

    /**
     * helper to size a canvas.
     */
    sizeCanvas : function(canvas, x, y, w, h) {
        canvas.style.height = h + "px"; canvas.height = h;
        canvas.style.width = w + "px"; canvas.width = w;
        canvas.style.left = x + "px"; canvas.style.top = y + "px";
    },

    /**
     * Toggles visibility of an element's connections.
     */
    toggle : function(elId) {
    	var jpcs = connections[elId];
    	if (jpcs.length > 0)
    		_setVisible(elId, "none" == jpcs[0].canvas.style.display ? "block" : "none");
    },

    /**
     * Unloads jsPlumb, deleting all storage.  You should call this
     */
    unload : function() {
    	delete connections;
		delete offsets;
		delete sizes;
		delete draggableStates;
    }
};

// ************** connection
// ****************************************
/**
* allowed params:
* source:	source element (string or a jQuery element) (required)
* target:	target element (string or a jQuery element) (required)
* anchors: optional array of anchor placements. defaults to BottomCenter for source
*          and TopCenter for target.
*/
var jsPlumbConnection = function(params) {

// ************** get the source and target and register the connection. *******************
    var self = this;
    // get source and target as jQuery objects
    this.source = (typeof params.source == 'string') ? $("#" + params.source) : params.source;
    this.target = (typeof params.target == 'string') ? $("#" + params.target) : params.target;
    this.sourceId = $(this.source).attr("id");
    this.targetId = $(this.target).attr("id");
    this.drawEndpoints = params.drawEndpoints != null ? params.drawEndpoints : true;
    this.endpointsOnTop = params.endpointsOnTop != null ? params.endpointsOnTop : true;

 // get anchor
    this.anchors = params.anchors || jsPlumb.DEFAULT_ANCHORS || [jsPlumb.Anchors.BottomCenter, jsPlumb.Anchors.TopCenter];
    // make connector
    this.connector = params.connector || jsPlumb.DEFAULT_CONNECTOR || new jsPlumb.Connectors.Bezier();
    this.paintStyle = params.paintStyle || jsPlumb.DEFAULT_PAINT_STYLE;
    // init endpoints
    this.endpoints = [];
    if(!params.endpoints) params.endpoints = [null,null];
    this.endpoints[0] = params.endpoints[0] || params.endpoint || jsPlumb.DEFAULT_ENDPOINTS[0] || jsPlumb.DEFAULT_ENDPOINT || new jsPlumb.Endpoints.Dot();
    this.endpoints[1] = params.endpoints[1] || params.endpoint || jsPlumb.DEFAULT_ENDPOINTS[1] ||jsPlumb.DEFAULT_ENDPOINT || new jsPlumb.Endpoints.Dot();
    this.endpointStyles = [];
    if (!params.endpointStyles) params.endpointStyles = [null,null];
    this.endpointStyles[0] = params.endpointStyles[0] || params.endpointStyle || jsPlumb.DEFAULT_ENDPOINT_STYLES[0] || jsPlumb.DEFAULT_ENDPOINT_STYLE;
    this.endpointStyles[1] = params.endpointStyles[1] || params.endpointStyle || jsPlumb.DEFAULT_ENDPOINT_STYLES[1] || jsPlumb.DEFAULT_ENDPOINT_STYLE;

    offsets[this.sourceId] = this.source.offset();
    sizes[this.sourceId] = [this.source.outerWidth(), this.source.outerHeight()];
    offsets[this.targetId] = this.target.offset();
    sizes[this.targetId] = [this.target.outerWidth(), this.target.outerHeight()];

// *************** create canvases on which the connection will be drawn ************
    var canvas = _newCanvas(jsPlumb.connectorClass);
    this.canvas = canvas;
    // create endpoint canvases
    if (this.drawEndpoints) {
	    this.sourceEndpointCanvas = _newCanvas(jsPlumb.endpointClass);
	    this.targetEndpointCanvas = _newCanvas(jsPlumb.endpointClass);
	    // sit them on top of the underlying element?
	    var setZIndex = function(canvas, source, above) {
    	   var adj = above ? 1 : -1;
    	   var zIndex = $(source).css("zIndex");
    	   $(canvas).css("zIndex", zIndex != "auto" ? zIndex + adj : "auto");
    	};

    	setZIndex(this.sourceEndpointCanvas, this.source, this.endpointsOnTop);
    	setZIndex(this.targetEndpointCanvas, this.target, this.endpointsOnTop);
    }
// ************** store the anchors

    /**
     * paints the connection.
     * @param elId Id of the element that is in motion
     * @param ui jQuery's event system ui object (present if we came from a drag to get here)
     * @param recalc whether or not to recalculate element sizes. this is true if a repaint caused this to be painted.
     */
    this.paint = function(elId, ui, recalc) {
    	// if the moving object is not the source we must transpose the two references.
    	var swap = !(elId == this.sourceId);
    	var tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId;
    	var tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;

    	if (this.canvas.getContext) {

    		if (recalc) {
	    		// get the current sizes of the two elements.
	    		var s = $("#" + elId);
	    		var t = $("#" + tId);
	    		sizes[elId] = [s.outerWidth(), s.outerHeight()];
	    		sizes[tId] = [t.outerWidth(), t.outerHeight()];
	    		offsets[elId] = s.offset();
	    		offsets[tId] = t.offset();
    		} else {
    			// faster to use the ui element if it was passed in.  offset is a fallback.
    			// fix for change in 1.8 (absolutePosition renamed to offset). plugin is compatible with
    			// 1.8 and 1.7.
    			var pos = ui.absolutePosition || ui.offset;
        		var anOffset = ui != null ? pos : $("#" + elId).offset();
        		offsets[elId] = anOffset;
    		}

    		var myOffset = offsets[elId];
    		var otherOffset = offsets[tId];
    		var myWH = sizes[elId];
            var otherWH = sizes[tId];

    		var ctx = canvas.getContext('2d');
            var sAnchorP = this.anchors[sIdx].compute([myOffset.left, myOffset.top], myWH, [otherOffset.left, otherOffset.top], otherWH);
            var sAnchorO = this.anchors[sIdx].orientation;
            var tAnchorP = this.anchors[tIdx].compute([otherOffset.left, otherOffset.top], otherWH, [myOffset.left, myOffset.top], myWH);
            var tAnchorO = this.anchors[tIdx].orientation;
            var dim = this.connector.compute(sAnchorP, tAnchorP, this.anchors[sIdx], this.anchors[tIdx], this.paintStyle.lineWidth);
            jsPlumb.sizeCanvas(canvas, dim[0], dim[1], dim[2], dim[3]);
            applyPaintStyle(ctx, this.paintStyle);

            var ie = (/MSIE/.test(navigator.userAgent) && !window.opera);
            if (this.paintStyle.gradient && !ie) {
	            var g = swap ? ctx.createLinearGradient(dim[4], dim[5], dim[6], dim[7]) : ctx.createLinearGradient(dim[6], dim[7], dim[4], dim[5]);
	            for (var i = 0; i < this.paintStyle.gradient.stops.length; i++)
	            	g.addColorStop(this.paintStyle.gradient.stops[i][0],this.paintStyle.gradient.stops[i][1]);
	            ctx.strokeStyle = g;
            }

            this.connector.paint(dim, ctx);

            if (this.drawEndpoints) {
            	var style = this.endpointStyle || this.paintStyle;
            	var sourceCanvas = swap ? this.targetEndpointCanvas : this.sourceEndpointCanvas;
            	var targetCanvas = swap ? this.sourceEndpointCanvas : this.targetEndpointCanvas;
            	this.endpoints[swap ? 1 : 0].paint(sAnchorP, sAnchorO, sourceCanvas, this.endpointStyles[swap ? 1 : 0] || this.paintStyle, this.paintStyle);
            	this.endpoints[swap ? 0 : 1].paint(tAnchorP, tAnchorO, targetCanvas, this.endpointStyles[swap ? 0 : 1] || this.paintStyle, this.paintStyle);
            }
    	}
    };

    this.repaint = function() {
    	this.paint(this.sourceId, null, true);
    };

    // dragging
    var draggable = params.draggable == null ? _draggableByDefault : params.draggable;
    if (draggable && self.source.draggable) {
    	var dragOptions = params.dragOptions || jsPlumb.DEFAULT_DRAG_OPTIONS;
    	var dragCascade = dragOptions.drag || function(e,u) {};
    	var initDrag = function(element, dragFunc) {
    		var opts = $.extend({drag:dragFunc}, dragOptions);
    		var draggable = draggableStates[element.attr("id")];
    		opts.disabled = draggable == null ? false : !draggable;
        	element.draggable(opts);
    	};
    	initDrag(this.source, function(event, ui) {
    		_draw(self.source, ui);
    		dragCascade(event, ui);
    	});
    	initDrag(this.target, function(event, ui) {
    		_draw(self.target, ui);
    		dragCascade(event, ui);
    	});
    }

    // resizing (using the jquery.ba-resize plugin). todo: decide whether to include or not.
    if (this.source.resize) {
    	this.source.resize(function(e) {
    		jsPlumb.repaint(self.sourceId);
    	});
    }

    // finally, draw it.
    var o = this.source.offset();
    this.paint(this.sourceId, {'absolutePosition': this.source.offset()});
};

})();

// jQuery plugin code
(function($){
    $.fn.plumb = function(options) {
        var defaults = { };
        var options = $.extend(defaults, options);

        return this.each(function()
        {
            var obj = $(this);
            var params = {};
            params.source = obj;
            for (var i in options) {
                params[i] = options[i];
            }
            jsPlumb.connect(params);
        });
  };

  $.fn.detach = function(options) {
	  return this.each(function()
	  {
		 var id = $(this).attr("id");
		 if (typeof options == 'string') options = [options];
		 for (var i = 0; i < options.length; i++)
			 jsPlumb.detach(id, options[i]);
	  });
  };

  $.fn.detachAll = function(options) {
	  return this.each(function()
	  {
		 var id = $(this).attr("id");
		 jsPlumb.detachAll(id);
	  });
  };
})(jQuery);


text:
require("./dom.spec");
require("./gestureemitter.spec");
require("./gesturehandler.spec");
require("./gesturehandlergroup.spec");
require("./mouseenterleaveemitter.spec");
require("./mouseoveroutemitter.spec");
require("./mousewheelemitter.spec");
require("./panemitter.spec");
require("./pressemitter.spec");
require("./swipeemitter.spec");
require("./tapemitter.spec");


text:
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/calc/calc_sequence.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------

OPEN_RDO_RUNTIME_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqInit
// --------------------------------------------------------------------------------
RDOCalcSeqInit::RDOCalcSeqInit(int base, RandGenerator* gen)
    : m_base(base)
    , m_gen (gen )
{}

void RDOCalcSeqInit::setBase(int base)
{
    m_base = base;
}

RDOValue RDOCalcSeqInit::doCalc(const LPRDORuntime& /*pRuntime*/)
{
    m_gen->setSeed(m_base);
    return RDOValue();
}

RDOCalcSeqInit::~RDOCalcSeqInit()
{
//    delete m_gen;
}

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqNext
// --------------------------------------------------------------------------------
RDOCalcSeqNext::Range::Range()
    : m_min(0)
    , m_max(0)
{}

RDOCalcSeqNext::Range::Range(const double& min, const double& max)
    : m_min(min)
    , m_max(max)
{}

RDOCalcSeqNext::RDOCalcSeqNext()
    : m_res_real(true )
{}

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqNextUniform
// --------------------------------------------------------------------------------
RDOValue RDOCalcSeqNextUniform::getNextValue(const LPRDORuntime& pRuntime)
{
    RDOValue from = pRuntime->getFuncArgument(0);
    RDOValue to   = pRuntime->getFuncArgument(1);
    if (from > to)
    {
        pRuntime->error().push(
            rdo::format("Для последовательности типа uniform нижняя граница диапазона должна быть меньше либо равна верхней, текущие значения: %s..%s"
                , from.getAsString().c_str()
                , to  .getAsString().c_str())
            , srcInfo()
        );
    }
    return m_gen->next(from.getDouble(), to.getDouble());
}

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqNextNormal
// --------------------------------------------------------------------------------
RDOValue RDOCalcSeqNextNormal::getNextValue(const LPRDORuntime& pRuntime)
{
    return m_gen->next(pRuntime->getFuncArgument(0).getDouble(), pRuntime->getFuncArgument(1).getDouble());
}

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqNextExponential
// --------------------------------------------------------------------------------
RDOValue RDOCalcSeqNextExponential::getNextValue(const LPRDORuntime& pRuntime)
{
    return m_gen->next(pRuntime->getFuncArgument(0).getDouble());
}

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqNextTriangular
// --------------------------------------------------------------------------------
RDOValue RDOCalcSeqNextTriangular::getNextValue(const LPRDORuntime& pRuntime)
{
    RDOValue from = pRuntime->getFuncArgument(0);
    RDOValue top  = pRuntime->getFuncArgument(1);
    RDOValue to   = pRuntime->getFuncArgument(2);
    if ((from > top) || (top > to))
    {
        pRuntime->error().push(
            rdo::format("Для треуголного закона распределения нужно указать левую границу, точку под высотой треугольника, правую границу: %s, %s, %s"
                , from.getAsString().c_str()
                , top.getAsString().c_str()
                , to.getAsString().c_str())
            , srcInfo()
        );
    }
    return m_gen->next(from.getDouble(), top.getDouble(), to.getDouble());
}

// --------------------------------------------------------------------------------
// -------------------- RDOCalcSeqNextByHist
// --------------------------------------------------------------------------------
RDOValue RDOCalcSeqNextByHist::getNextValue(const LPRDORuntime& /*pRuntime*/)
{
    return m_gen->next();
}

CLOSE_RDO_RUNTIME_NAMESPACE


text:
using System;

namespace Scrutor;

internal sealed class OpenGenericDecorationStrategy : DecorationStrategy
{
    public OpenGenericDecorationStrategy(Type serviceType, Type? decoratorType, Func<object, IServiceProvider, object>? decoratorFactory) : base(serviceType)
    {
        DecoratorType = decoratorType;
        DecoratorFactory = decoratorFactory;
    }

    private Type? DecoratorType { get; }

    private Func<object, IServiceProvider, object>? DecoratorFactory { get; }

    public override bool CanDecorate(Type serviceType) =>
        serviceType.IsGenericType
            && !serviceType.IsGenericTypeDefinition
            && serviceType.GetGenericTypeDefinition() == ServiceType.GetGenericTypeDefinition()
            && (DecoratorType is null || serviceType.HasCompatibleGenericArguments(DecoratorType));

    public override Func<IServiceProvider, object> CreateDecorator(Type serviceType)
    {
        if (DecoratorType is not null)
        {
            var genericArguments = serviceType.GetGenericArguments();
            var closedDecorator = DecoratorType.MakeGenericType(genericArguments);

            return TypeDecorator(serviceType, closedDecorator);
        }

        if (DecoratorFactory is not null)
        {
            return FactoryDecorator(serviceType, DecoratorFactory);
        }

        throw new InvalidOperationException($"Both serviceType and decoratorFactory can not be null.");
    }
}