repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
BeenzSyed/tempest
tempest/scenario/test_aggregates_basic_ops.py
1
5542
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from tempest.common import tempest_fixtures as fixtures from tempest.common.utils.data_utils import rand_name from tempest.openstack.common import log as logging from tempest.scenario import manager from tempest import test LOG = logging.getLogger(__name__) class TestAggregatesBasicOps(manager.OfficialClientTest): """ Creates an aggregate within an availability zone Adds a host to the aggregate Checks aggregate details Updates aggregate's name Removes host from aggregate Deletes aggregate """ @classmethod def credentials(cls): return cls.admin_credentials() def _create_aggregate(self, aggregate_name, availability_zone=None): aggregate = self.compute_client.aggregates.create(aggregate_name, availability_zone) self.assertEqual(aggregate.name, aggregate_name) self.assertEqual(aggregate.availability_zone, availability_zone) self.set_resource(aggregate.id, aggregate) LOG.debug("Aggregate %s created." % (aggregate.name)) return aggregate def _delete_aggregate(self, aggregate): self.compute_client.aggregates.delete(aggregate.id) self.remove_resource(aggregate.id) LOG.debug("Aggregate %s deleted. " % (aggregate.name)) def _get_host_name(self): hosts = self.compute_client.hosts.list() self.assertTrue(len(hosts) >= 1) hostname = hosts[0].host_name return hostname def _add_host(self, aggregate_name, host): aggregate = self.compute_client.aggregates.add_host(aggregate_name, host) self.assertIn(host, aggregate.hosts) LOG.debug("Host %s added to Aggregate %s." % (host, aggregate.name)) def _remove_host(self, aggregate_name, host): aggregate = self.compute_client.aggregates.remove_host(aggregate_name, host) self.assertNotIn(host, aggregate.hosts) LOG.debug("Host %s removed to Aggregate %s." % (host, aggregate.name)) def _check_aggregate_details(self, aggregate, aggregate_name, azone, hosts, metadata): aggregate = self.compute_client.aggregates.get(aggregate.id) self.assertEqual(aggregate_name, aggregate.name) self.assertEqual(azone, aggregate.availability_zone) self.assertEqual(aggregate.hosts, hosts) for meta_key in metadata.keys(): self.assertIn(meta_key, aggregate.metadata) self.assertEqual(metadata[meta_key], aggregate.metadata[meta_key]) LOG.debug("Aggregate %s details match." % aggregate.name) def _set_aggregate_metadata(self, aggregate, meta): aggregate = self.compute_client.aggregates.set_metadata(aggregate.id, meta) for key, value in meta.items(): self.assertEqual(meta[key], aggregate.metadata[key]) LOG.debug("Aggregate %s metadata updated successfully." % aggregate.name) def _update_aggregate(self, aggregate, aggregate_name, availability_zone): values = {} if aggregate_name: values.update({'name': aggregate_name}) if availability_zone: values.update({'availability_zone': availability_zone}) if values.keys(): aggregate = self.compute_client.aggregates.update(aggregate.id, values) for key, values in values.items(): self.assertEqual(getattr(aggregate, key), values) return aggregate @test.services('compute') def test_aggregate_basic_ops(self): self.useFixture(fixtures.LockFixture('availability_zone')) az = 'foo_zone' aggregate_name = rand_name('aggregate-scenario') aggregate = self._create_aggregate(aggregate_name, az) metadata = {'meta_key': 'meta_value'} self._set_aggregate_metadata(aggregate, metadata) host = self._get_host_name() self._add_host(aggregate, host) self._check_aggregate_details(aggregate, aggregate_name, az, [host], metadata) aggregate_name = rand_name('renamed-aggregate-scenario') aggregate = self._update_aggregate(aggregate, aggregate_name, None) additional_metadata = {'foo': 'bar'} self._set_aggregate_metadata(aggregate, additional_metadata) metadata.update(additional_metadata) self._check_aggregate_details(aggregate, aggregate.name, az, [host], metadata) self._remove_host(aggregate, host) self._delete_aggregate(aggregate)
apache-2.0
hexxter/home-assistant
homeassistant/components/zeroconf.py
10
1452
""" This module exposes Home Assistant via Zeroconf. For more details about this component, please refer to the documentation at https://home-assistant.io/components/zeroconf/ """ import logging import socket import voluptuous as vol from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__) _LOGGER = logging.getLogger(__name__) DEPENDENCIES = ['api'] DOMAIN = 'zeroconf' REQUIREMENTS = ['zeroconf==0.17.6'] ZEROCONF_TYPE = '_home-assistant._tcp.local.' CONFIG_SCHEMA = vol.Schema({ DOMAIN: vol.Schema({}), }, extra=vol.ALLOW_EXTRA) def setup(hass, config): """Set up Zeroconf and make Home Assistant discoverable.""" from zeroconf import Zeroconf, ServiceInfo zeroconf = Zeroconf() zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE) requires_api_password = hass.config.api.api_password is not None params = { 'version': __version__, 'base_url': hass.config.api.base_url, 'requires_api_password': requires_api_password, } info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, socket.inet_aton(hass.config.api.host), hass.config.api.port, 0, 0, params) zeroconf.register_service(info) def stop_zeroconf(event): """Stop Zeroconf.""" zeroconf.unregister_service(info) zeroconf.close() hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf) return True
mit
sivel/ansible-modules-extras
system/known_hosts.py
10
11796
#!/usr/bin/python """ Ansible module to manage the ssh known_hosts file. Copyright(c) 2014, Matthew Vernon <mcv21@cam.ac.uk> This module is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this module. If not, see <http://www.gnu.org/licenses/>. """ ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: known_hosts short_description: Add or remove a host from the C(known_hosts) file description: - The M(known_hosts) module lets you add or remove a host keys from the C(known_hosts) file. - Starting at Ansible 2.2, multiple entries per host are allowed, but only one for each key type supported by ssh. This is useful if you're going to want to use the M(git) module over ssh, for example. - If you have a very large number of host keys to manage, you will find the M(template) module more useful. version_added: "1.9" options: name: aliases: [ 'host' ] description: - The host to add or remove (must match a host specified in key) required: true default: null key: description: - The SSH public host key, as a string (required if state=present, optional when state=absent, in which case all keys for the host are removed). The key must be in the right format for ssh (see sshd(1), section "SSH_KNOWN_HOSTS FILE FORMAT") required: false default: null path: description: - The known_hosts file to edit required: no default: "(homedir)+/.ssh/known_hosts" hash_host: description: - Hash the hostname in the known_hosts file required: no default: no version_added: "2.3" state: description: - I(present) to add the host key, I(absent) to remove it. choices: [ "present", "absent" ] required: no default: present requirements: [ ] author: "Matthew Vernon (@mcv21)" ''' EXAMPLES = ''' - name: tell the host about our servers it might want to ssh to known_hosts: path: /etc/ssh/ssh_known_hosts name: foo.com.invalid key: "{{ lookup('file', 'pubkeys/foo.com.invalid') }}" ''' # Makes sure public host keys are present or absent in the given known_hosts # file. # # Arguments # ========= # name = hostname whose key should be added (alias: host) # key = line(s) to add to known_hosts file # path = the known_hosts file to edit (default: ~/.ssh/known_hosts) # hash_host = yes|no (default: no) hash the hostname in the known_hosts file # state = absent|present (default: present) import os import os.path import tempfile import errno import re from ansible.module_utils.pycompat24 import get_exception from ansible.module_utils.basic import * def enforce_state(module, params): """ Add or remove key. """ host = params["name"] key = params.get("key",None) port = params.get("port",None) path = params.get("path") hash_host = params.get("hash_host") state = params.get("state") #Find the ssh-keygen binary sshkeygen = module.get_bin_path("ssh-keygen",True) # Trailing newline in files gets lost, so re-add if necessary if key and key[-1] != '\n': key+='\n' if key is None and state != "absent": module.fail_json(msg="No key specified when adding a host") sanity_check(module,host,key,sshkeygen) found,replace_or_add,found_line,key=search_for_host_key(module,host,key,hash_host,path,sshkeygen) #We will change state if found==True & state!="present" #or found==False & state=="present" #i.e found XOR (state=="present") #Alternatively, if replace is true (i.e. key present, and we must change it) if module.check_mode: module.exit_json(changed = replace_or_add or (state=="present") != found) #Now do the work. #Only remove whole host if found and no key provided if found and key is None and state=="absent": module.run_command([sshkeygen,'-R',host,'-f',path], check_rc=True) params['changed'] = True #Next, add a new (or replacing) entry if replace_or_add or found != (state=="present"): try: inf=open(path,"r") except IOError: e = get_exception() if e.errno == errno.ENOENT: inf=None else: module.fail_json(msg="Failed to read %s: %s" % \ (path,str(e))) try: outf=tempfile.NamedTemporaryFile(dir=os.path.dirname(path)) if inf is not None: for line_number, line in enumerate(inf, start=1): if found_line==line_number and (replace_or_add or state=='absent'): continue # skip this line to replace its key outf.write(line) inf.close() if state == 'present': outf.write(key) outf.flush() module.atomic_move(outf.name,path) except (IOError,OSError): e = get_exception() module.fail_json(msg="Failed to write to file %s: %s" % \ (path,str(e))) try: outf.close() except: pass params['changed'] = True return params def sanity_check(module,host,key,sshkeygen): '''Check supplied key is sensible host and key are parameters provided by the user; If the host provided is inconsistent with the key supplied, then this function quits, providing an error to the user. sshkeygen is the path to ssh-keygen, found earlier with get_bin_path ''' #If no key supplied, we're doing a removal, and have nothing to check here. if key is None: return #Rather than parsing the key ourselves, get ssh-keygen to do it #(this is essential for hashed keys, but otherwise useful, as the #key question is whether ssh-keygen thinks the key matches the host). #The approach is to write the key to a temporary file, #and then attempt to look up the specified host in that file. try: outf=tempfile.NamedTemporaryFile() outf.write(key) outf.flush() except IOError: e = get_exception() module.fail_json(msg="Failed to write to temporary file %s: %s" % \ (outf.name,str(e))) rc,stdout,stderr=module.run_command([sshkeygen,'-F',host, '-f',outf.name], check_rc=True) try: outf.close() except: pass if stdout=='': #host not found module.fail_json(msg="Host parameter does not match hashed host field in supplied key") def search_for_host_key(module,host,key,hash_host,path,sshkeygen): '''search_for_host_key(module,host,key,path,sshkeygen) -> (found,replace_or_add,found_line) Looks up host and keytype in the known_hosts file path; if it's there, looks to see if one of those entries matches key. Returns: found (Boolean): is host found in path? replace_or_add (Boolean): is the key in path different to that supplied by user? found_line (int or None): the line where a key of the same type was found if found=False, then replace is always False. sshkeygen is the path to ssh-keygen, found earlier with get_bin_path ''' if os.path.exists(path)==False: return False, False, None, key sshkeygen_command=[sshkeygen,'-F',host,'-f',path] #openssh >=6.4 has changed ssh-keygen behaviour such that it returns #1 if no host is found, whereas previously it returned 0 rc,stdout,stderr=module.run_command(sshkeygen_command, check_rc=False) if stdout=='' and stderr=='' and (rc==0 or rc==1): return False, False, None, key #host not found, no other errors if rc!=0: #something went wrong module.fail_json(msg="ssh-keygen failed (rc=%d,stdout='%s',stderr='%s')" % (rc,stdout,stderr)) #If user supplied no key, we don't want to try and replace anything with it if key is None: return True, False, None, key lines=stdout.split('\n') new_key = normalize_known_hosts_key(key) sshkeygen_command.insert(1,'-H') rc,stdout,stderr=module.run_command(sshkeygen_command,check_rc=False) if rc!=0: #something went wrong module.fail_json(msg="ssh-keygen failed to hash host (rc=%d,stdout='%s',stderr='%s')" % (rc,stdout,stderr)) hashed_lines=stdout.split('\n') for lnum,l in enumerate(lines): if l=='': continue elif l[0]=='#': # info output from ssh-keygen; contains the line number where key was found try: # This output format has been hardcoded in ssh-keygen since at least OpenSSH 4.0 # It always outputs the non-localized comment before the found key found_line = int(re.search(r'found: line (\d+)', l).group(1)) except IndexError: e = get_exception() module.fail_json(msg="failed to parse output of ssh-keygen for line number: '%s'" % l) else: found_key = normalize_known_hosts_key(l) if hash_host==True: if found_key['host'][:3]=='|1|': new_key['host']=found_key['host'] else: hashed_host=normalize_known_hosts_key(hashed_lines[lnum]) found_key['host']=hashed_host['host'] key=key.replace(host,found_key['host']) if new_key==found_key: #found a match return True, False, found_line, key #found exactly the same key, don't replace elif new_key['type'] == found_key['type']: # found a different key for the same key type return True, True, found_line, key #No match found, return found and replace, but no line return True, True, None, key def normalize_known_hosts_key(key): ''' Transform a key, either taken from a known_host file or provided by the user, into a normalized form. The host part (which might include multiple hostnames or be hashed) gets replaced by the provided host. Also, any spurious information gets removed from the end (like the username@host tag usually present in hostkeys, but absent in known_hosts files) ''' k=key.strip() #trim trailing newline k=key.split() d = dict() #The optional "marker" field, used for @cert-authority or @revoked if k[0][0] == '@': d['options'] = k[0] d['host']=k[1] d['type']=k[2] d['key']=k[3] else: d['host']=k[0] d['type']=k[1] d['key']=k[2] return d def main(): module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str', aliases=['host']), key = dict(required=False, type='str'), path = dict(default="~/.ssh/known_hosts", type='path'), hash_host = dict(required=False, type='bool' ,default=False), state = dict(default='present', choices=['absent','present']), ), supports_check_mode = True ) results = enforce_state(module,module.params) module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
vbshah1992/microblog
flask/lib/python2.7/site-packages/whoosh/util/testing.py
95
4517
# Copyright 2007 Matt Chaput. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. import os.path import random import shutil import sys import tempfile from contextlib import contextmanager from whoosh.filedb.filestore import FileStorage from whoosh.util import now, random_name class TempDir(object): def __init__(self, basename="", parentdir=None, ext=".whoosh", suppress=frozenset(), keepdir=False): self.basename = basename or random_name(8) self.parentdir = parentdir dirname = parentdir or tempfile.mkdtemp(ext, self.basename) self.dir = os.path.abspath(dirname) self.suppress = suppress self.keepdir = keepdir def __enter__(self): if not os.path.exists(self.dir): os.makedirs(self.dir) return self.dir def cleanup(self): pass def __exit__(self, exc_type, exc_val, exc_tb): self.cleanup() if not self.keepdir: try: shutil.rmtree(self.dir) except OSError: e = sys.exc_info()[1] #sys.stderr.write("Can't remove temp dir: " + str(e) + "\n") #if exc_type is None: # raise if exc_type is not None: if self.keepdir: sys.stderr.write("Temp dir=" + self.dir + "\n") if exc_type not in self.suppress: return False class TempStorage(TempDir): def __init__(self, debug=False, **kwargs): TempDir.__init__(self, **kwargs) self._debug = debug def cleanup(self): self.store.close() def __enter__(self): dirpath = TempDir.__enter__(self) self.store = FileStorage(dirpath, debug=self._debug) return self.store class TempIndex(TempStorage): def __init__(self, schema, ixname='', storage_debug=False, **kwargs): TempStorage.__init__(self, basename=ixname, debug=storage_debug, **kwargs) self.schema = schema def __enter__(self): fstore = TempStorage.__enter__(self) return fstore.create_index(self.schema, indexname=self.basename) def is_abstract_method(attr): """Returns True if the given object has __isabstractmethod__ == True. """ return (hasattr(attr, "__isabstractmethod__") and getattr(attr, "__isabstractmethod__")) def check_abstract_methods(base, subclass): """Raises AssertionError if ``subclass`` does not override a method on ``base`` that is marked as an abstract method. """ for attrname in dir(base): if attrname.startswith("_"): continue attr = getattr(base, attrname) if is_abstract_method(attr): oattr = getattr(subclass, attrname) if is_abstract_method(oattr): raise Exception("%s.%s not overridden" % (subclass.__name__, attrname)) @contextmanager def timing(name=None): t = now() yield t = now() - t print("%s: %0.06f s" % (name or '', t))
bsd-3-clause
MadsJensen/agency_connectivity
phase_analysis_wide.py
1
5708
# -*- coding: utf-8 -*- """ @author: mje @emai: mads@cnru.dk """ import numpy as np # import mne import matplotlib.pyplot as plt import pandas as pd from my_settings import * plt.style.use("ggplot") b_df = pd.read_csv( "/Users/au194693/projects/agency_connectivity/data/behavioural_results.csv") def calc_ISPC_time_between(data, chan_1=52, chan_2=1): result = np.empty([data.shape[0]]) for i in range(data.shape[0]): result[i] = np.abs( np.mean( np.exp(1j * (np.angle(data[i, chan_1, window_start:window_end]) - np.angle(data[i, chan_2, window_start: window_end]))))) return result label_dict = {"ba_1_4_r": [1, 52], "ba_1_4_l": [0, 51], "ba_4_4": [51, 52], "ba_1_1": [0, 1]} # "ba_4_39_l": [49, 51], # "ba_4_39_r": [50, 52], # "ba_39_39": [49, 50]} # bands = ["delta", "theta", "alpha", "beta", "gamma1", "gamma2"] bands = ["beta"] # subjects = ["p9"] labels = list(np.load(data_path + "label_names.npy")) times = np.arange(-2000, 2001, 1.95325) times = times / 1000. window_length = 153 step_length = 15 results_all = pd.DataFrame() for subject in subjects: print("Working on: " + subject) # ht_vol = np.load(tf_folder + "/%s_vol_HT-comp.npy" % # subject) ht_testing = np.load(tf_folder + "%s_inv_HT-comp.npy" % subject) b_tmp = b_df[(b_df.subject == subject) & (b_df.condition == "invol" )].reset_index() b_tmp = b_tmp[-89:] for k, band in enumerate(bands): k = 3 # results_testing = {} ht_testing_band = ht_testing[-89:, :, :, k] step = 1 j = 768 # times index to start while times[window_length + j] < times[1040]: window_start = j window_end = j + window_length res = pd.DataFrame( calc_ISPC_time_between( ht_testing_band, chan_1=label_dict["ba_1_4_r"][0], chan_2=label_dict["ba_1_4_r"][1]), columns=["ba_1_4_r"]) res["step"] = step res["subject"] = subject res["binding"] = b_tmp.binding.get_values() res["trial_status"] = b_tmp.trial_status.get_values() res["condition"] = "testing" res["band"] = band # res["trial_nr"] = np.arange(1, 90, 1) res["ba_1_4_l"] = calc_ISPC_time_between( ht_testing_band, chan_1=label_dict["ba_1_4_l"][0], chan_2=label_dict["ba_1_4_l"][1]) res["ba_1_1"] = calc_ISPC_time_between( ht_testing_band, chan_1=label_dict["ba_1_1"][0], chan_2=label_dict["ba_1_1"][1]) res["ba_4_4"] = calc_ISPC_time_between( ht_testing_band, chan_1=label_dict["ba_4_4"][0], chan_2=label_dict["ba_4_4"][1]) results_all = results_all.append(res) j += step_length step += 1 print("Working on: " + subject) # ht_vol = np.load(tf_folder + "/%s_vol_HT-comp.npy" % # subject) ht_learning = np.load(tf_folder + "%s_vol_HT-comp.npy" % subject) b_tmp = b_df[(b_df.subject == subject) & (b_df.condition == "vol" )].reset_index() b_tmp = b_tmp[-89:] for k, band in enumerate(bands): k = 3 # Results_learning = {} ht_learning_band = ht_learning[-89:, :, :, k] j = 768 # times index to start step = 1 while times[window_length + j] < times[1040]: window_start = j window_end = j + window_length res = pd.DataFrame( calc_ISPC_time_between( ht_learning_band, chan_1=label_dict["ba_1_4_r"][0], chan_2=label_dict["ba_1_4_r"][1]), columns=["ba_1_4_r"]) res["step"] = step res["subject"] = subject res["binding"] = b_tmp.binding.get_values() res["trial_status"] = b_tmp.trial_status.get_values() res["condition"] = "learning" res["band"] = band # res["trial_nr"] = np.arange(1, 90, 1) res["ba_1_4_l"] = calc_ISPC_time_between( ht_learning_band, chan_1=label_dict["ba_1_4_l"][0], chan_2=label_dict["ba_1_4_l"][1]) res["ba_1_1"] = calc_ISPC_time_between( ht_learning_band, chan_1=label_dict["ba_1_1"][0], chan_2=label_dict["ba_1_1"][1]) res["ba_4_4"] = calc_ISPC_time_between( ht_learning_band, chan_1=label_dict["ba_4_4"][0], chan_2=label_dict["ba_4_4"][1]) results_all = results_all.append(res) j += step_length step += 1 # combine condition to predict testing from learning res_testing = results_all[results_all.condition == "testing"] res_learning = results_all[results_all.condition == "learning"] res_combined = res_testing.copy() res_combined["ba_1_1_learning"] = res_learning["ba_1_1"] res_combined["ba_4_4_learning"] = res_learning["ba_4_4"] res_combined["ba_1_4_l_learning"] = res_learning["ba_1_4_l"] res_combined["ba_1_4_r_learning"] = res_learning["ba_1_4_r"] tmp = res_combined[res_combined.step == 8] X = tmp[["ba_1_1", "ba_4_4", "ba_1_4_l", "ba_1_4_r", "ba_1_1_learning", "ba_4_4_learning", "ba_1_4_l_learning", "ba_1_4_r_learning"]].get_values() y = tmp[["binding"]]
bsd-3-clause
LFPy/LFPy
LFPy/cell.py
1
106760
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright (C) 2012 Computational Neuroscience Group, NMBU. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. """ import os import neuron from neuron import units import numpy as np import scipy.stats import sys import posixpath from warnings import warn import pickle from .run_simulation import _run_simulation_with_probes from .run_simulation import _collect_geometry_neuron from .alias_method import alias_method # check neuron version: try: try: assert neuron.version >= '7.7.2' except AttributeError: warn('Could not read NEURON version info. v7.7.2 or newer required') except TypeError: # workaround for doc build neuron Mock module pass except AssertionError: warn('LFPy requires NEURON v7.7.2 or newer. Found v{}'.format( neuron.version)) class Cell(object): """ The main cell class used in LFPy. Parameters ---------- morphology: str or neuron.h.SectionList File path of morphology on format that NEURON can understand (w. file ending .hoc, .asc, .swc or .xml), or neuron.h.SectionList instance filled with references to neuron.h.Section instances. v_init: float Initial membrane potential. Defaults to -70 mV. Ra: float or None Axial resistance. Defaults to None (unit Ohm*cm) cm: float Membrane capacitance. Defaults to None (unit uF/cm2) passive: bool Passive mechanisms are initialized if True. Defaults to False passive_parameters: dict parameter dictionary with values for the passive membrane mechanism in NEURON ('pas'). The dictionary must contain keys 'g_pas' [S/cm^2] and 'e_pas' [mV], like the default: passive_parameters=dict(g_pas=0.001, e_pas=-70) extracellular: bool Switch for NEURON's extracellular mechanism. Defaults to False dt: float simulation timestep. Defaults to 2^-4 ms tstart: float Initialization time for simulation <= 0 ms. Defaults to 0. tstop: float Stop time for simulation > 0 ms. Defaults to 100 ms. nsegs_method: 'lambda100' or 'lambda_f' or 'fixed_length' or None nseg rule, used by NEURON to determine number of compartments. Defaults to 'lambda100' max_nsegs_length: float or None Maximum segment length for method 'fixed_length'. Defaults to None lambda_f: int AC frequency for method 'lambda_f'. Defaults to 100 d_lambda: float Parameter for d_lambda rule. Defaults to 0.1 delete_sections: bool Delete pre-existing section-references. Defaults to True custom_code: list or None List of model-specific code files ([.py/.hoc]). Defaults to None custom_fun: list or None List of model-specific functions with args. Defaults to None custom_fun_args: list or None List of args passed to custom_fun functions. Defaults to None pt3d: bool Use pt3d-info of the cell geometries switch. Defaults to False celsius: float or None Temperature in celsius. If nothing is specified here or in custom code it is 6.3 celcius verbose: bool Verbose output switch. Defaults to False Examples -------- Simple example of how to use the Cell class with a passive-circuit morphology (modify morphology path accordingly): >>> import os >>> import LFPy >>> cellParameters = { >>> 'morphology': os.path.join('examples', 'morphologies', >>> 'L5_Mainen96_LFPy.hoc'), >>> 'v_init': -65., >>> 'cm': 1.0, >>> 'Ra': 150, >>> 'passive': True, >>> 'passive_parameters': {'g_pas': 1./30000, 'e_pas': -65}, >>> 'dt': 2**-3, >>> 'tstart': 0, >>> 'tstop': 50, >>> } >>> cell = LFPy.Cell(**cellParameters) >>> cell.simulate() >>> print(cell.somav) See also -------- TemplateCell NetworkCell """ def __init__(self, morphology, v_init=-70., Ra=None, cm=None, passive=False, passive_parameters=None, extracellular=False, tstart=0., tstop=100., dt=2**-4, nsegs_method='lambda100', lambda_f=100, d_lambda=0.1, max_nsegs_length=None, delete_sections=True, custom_code=None, custom_fun=None, custom_fun_args=None, pt3d=False, celsius=None, verbose=False, **kwargs): self.verbose = verbose self.pt3d = pt3d if passive_parameters is None: passive_parameters = dict(g_pas=0.001, e_pas=-70.) # check if there are un-used keyword arguments present in kwargs for key, value in kwargs.items(): raise ValueError('keyword/argument {}={}'.format(key, value), 'is invalid input to class LFPy.Cell') if passive: assert isinstance(passive_parameters, dict), \ 'passive_parameters must be a dictionary' for key in ['g_pas', 'e_pas']: assert key in passive_parameters.keys(), \ 'key {} not found in passive_parameters'.format(key) if not hasattr(neuron.h, 'd_lambda'): neuron.h.load_file('stdlib.hoc') # NEURON std. library neuron.h.load_file('import3d.hoc') # import 3D morphology lib if not hasattr(neuron.h, 'continuerun'): neuron.h.load_file('stdrun.hoc') # NEURON stdrun library if delete_sections: if not isinstance(morphology, type(neuron.h.SectionList)): if self.verbose: print('%s existing sections deleted from memory' % sum(1 for sec in neuron.h.allsec())) neuron.h('forall delete_section()') else: if not isinstance(morphology, type(neuron.h.SectionList)): mssg = "%s sections detected! " % sum( 1 for sec in neuron.h.allsec()) \ + "Consider setting 'delete_sections=True'" warn(mssg) # load morphology assert morphology is not None, \ ('deprecated keyword argument morphology==None, value must be ' + 'a file path or neuron.h.SectionList instance with ' + 'neuron.h.Section instances') if "win32" in sys.platform and isinstance(morphology, str): # fix Path on windows morphology = morphology.replace(os.sep, posixpath.sep) self.morphology = morphology if isinstance(self.morphology, str): if os.path.isfile(self.morphology): self._load_geometry() else: raise Exception('non-existent file %s' % self.morphology) else: assert isinstance(self.morphology, type(neuron.h.SectionList)), \ ("Could not recognize Cell keyword argument morphology as " + "neuron.h.SectionList instance") # instantiate 3D geometry of all sections neuron.h.define_shape() # set some additional attributes self._create_sectionlists() # Some parameters and lists initialised assert tstart <= 0, 'tstart must be <= 0.' try: assert dt in 2.**np.arange(-16, -1) except AssertionError: if tstart == 0.: if self.verbose: print('int(1./dt) not factorizable in base 2. cell.tvec ' 'errors may occur, continuing initialization.') elif tstart < 0: raise AssertionError( 'int(1./dt) must be factorizable in base 2 if tstart < 0.') self.dt = dt self.tstart = tstart self.tstop = tstop self.synapses = [] self.synidx = [] self.pointprocesses = [] self.pointprocess_idx = [] self.v_init = v_init self.default_rotation = self.__get_rotation() # Set axial resistance and membrane capacitance self.Ra = Ra self.cm = cm self.__set_ra_and_cm() # Set passive properties, insert passive on all segments self.passive_parameters = passive_parameters if passive: self.__set_passive() else: if self.verbose: print('No passive properties added') # run user specified code and functions if argument given if custom_code is not None or custom_fun is not None: self.__run_custom_codes(custom_code, custom_fun, custom_fun_args) # Insert extracellular mech on all segments self.extracellular = extracellular if self.extracellular: self.__set_extracellular() else: if self.verbose: print("no extracellular mechanism inserted") # set number of segments accd to rule, and calculate the number self.__set_negs(nsegs_method, lambda_f, d_lambda, max_nsegs_length) self.totnsegs = self.__calc_totnsegs() if self.verbose: print("Total number of segments: %i" % self.totnsegs) # extract pt3d info from NEURON, and set these with the same rotation # and position in space as in our simulations, assuming RH rule, which # NEURON do NOT use in shape plot if self.pt3d: self.x3d, self.y3d, self.z3d, self.diam3d = self._collect_pt3d() # Gather geometry, set position and rotation of morphology if self.pt3d: self._update_pt3d() else: # self._update_pt3d makes a call to self._collect_geometry() self._collect_geometry() if hasattr(self, 'somapos'): self.set_pos() else: if self.verbose: print('no soma, using the midpoint if initial segment.') self.set_rotation(**self.default_rotation) if celsius is not None: if neuron.h.celsius != 6.3: print("Changing temperature %1.2f to %1.2f" % (neuron.h.celsius, celsius)) neuron.h.celsius = celsius # initialize membrane voltage in all segments. neuron.h.finitialize(self.v_init * units.mV) self._neuron_tvec = None def __del__(self): """Cell finalizer""" self.strip_hoc_objects() def strip_hoc_objects(self): """Destroy any NEURON hoc objects in the cell object""" if not (isinstance(neuron, type(None)) or isinstance(neuron.nrn, type(None))): nrntypes = (neuron.nrn.Segment, neuron.nrn.Section, neuron.nrn.Mechanism, type(neuron.h.List())) for key in self.__dict__.keys(): if isinstance(getattr(self, key), nrntypes): setattr(self, key, None) if self.verbose: print('{}.{} = None'.format(self.__name__, key)) def _load_geometry(self): """Load the morphology-file in NEURON""" # import the morphology, try and determine format fileEnding = self.morphology.split('.')[-1] if fileEnding == 'hoc' or fileEnding == 'HOC': neuron.h.load_file(1, self.morphology) else: neuron.h('objref this') if fileEnding == 'asc' or fileEnding == 'ASC': Import = neuron.h.Import3d_Neurolucida3() if not self.verbose: Import.quiet = 1 elif fileEnding == 'swc' or fileEnding == 'SWC': Import = neuron.h.Import3d_SWC_read() elif fileEnding == 'xml' or fileEnding == 'XML': Import = neuron.h.Import3d_MorphML() else: raise ValueError('%s not a recognised morphology file format' % self.morphology).with_traceback( 'Should be either .hoc, .asc, .swc, .xml') # assuming now that morphologies file is the correct format try: Import.input(self.morphology) except BaseException: if not hasattr(neuron, 'neuroml'): raise Exception('Can not import, try and copy the ' 'nrn/share/lib/python/neuron/neuroml ' 'folder into %s' % neuron.__path__[0]) else: raise Exception('something wrong with file, see output') try: imprt = neuron.h.Import3d_GUI(Import, 0) except BaseException: raise Exception('See output, try to correct the file') imprt.instantiate(neuron.h.this) neuron.h.define_shape() self._create_sectionlists() def __run_custom_codes(self, custom_code, custom_fun, custom_fun_args): """Execute custom model code and functions with arguments""" # load custom codes if custom_code is not None: for code in custom_code: if "win32" in sys.platform: code = code.replace(os.sep, posixpath.sep) if code.split('.')[-1] == 'hoc': try: neuron.h.xopen(code) except RuntimeError: ERRMSG = '\n'.join( [ '', 'Could not load custom model code (%s)' % code, 'while creating a Cell object.', 'One possible cause is NEURON mechanisms have', 'not been compiled, ', 'try running nrnivmodl or mknrndll (Windows) ', 'in the .mod-file containing folder. ', ]) raise Exception(ERRMSG) elif code.split('.')[-1] == 'py': exec(code) else: raise Exception('%s not a .hoc- nor .py-file' % code) # run custom functions with arguments i = 0 if custom_fun is not None: for fun in custom_fun: fun(self, **custom_fun_args[i]) i += 1 # recreate sectionlists in case something changed neuron.h.define_shape() self._create_sectionlists() def __set_negs(self, nsegs_method, lambda_f, d_lambda, max_nsegs_length): """Set number of segments per section according to the lambda-rule, or according to maximum length of segments""" if nsegs_method == 'lambda100': self.__set_nsegs_lambda100(d_lambda) elif nsegs_method == 'lambda_f': self.__set_nsegs_lambda_f(lambda_f, d_lambda) elif nsegs_method == 'fixed_length': self.__set_nsegs_fixed_length(max_nsegs_length) else: if self.verbose: print('No nsegs_method applied (%s)' % nsegs_method) def __get_rotation(self): """Check if there exists a corresponding file with rotation angles""" if isinstance(self.morphology, str): base = os.path.splitext(self.morphology)[0] if os.path.isfile(base + '.rot'): rotation_file = base + '.rot' rotation_data = open(rotation_file) rotation = {} for line in rotation_data: var, val = line.split('=') val = val.strip() val = float(str(val)) rotation[var] = val else: rotation = {} else: rotation = {} return rotation def _create_sectionlists(self): """Create section lists for different kinds of sections""" # list with all sections self.allsecnames = [] if not isinstance(self.morphology, type(neuron.h.SectionList)): self.allseclist = neuron.h.SectionList() for sec in neuron.h.allsec(): self.allsecnames.append(sec.name()) self.allseclist.append(sec=sec) else: self.allseclist = self.morphology for sec in neuron.h.allsec(): self.allsecnames.append(sec.name()) # list of soma sections, assuming it is named on the format "soma*" self.nsomasec = 0 self.somalist = neuron.h.SectionList() for sec in neuron.h.allsec(): if sec.name().find('soma') >= 0: self.somalist.append(sec=sec) self.nsomasec += 1 def __get_idx(self, seclist): """Return boolean vector which indexes where segments in seclist matches segments in neuron.h.allsec(), rewritten from LFPy.hoc function get_idx()""" if neuron.h.allsec() == seclist: return np.ones(self.totnsegs, dtype=bool) else: idxvec = np.zeros(self.totnsegs, dtype=bool) # get sectionnames from seclist seclistnames = [] for sec in seclist: seclistnames.append(sec.name()) seclistnames = np.array(seclistnames, dtype='|S128') segnames = np.empty(self.totnsegs, dtype='|S128') i = 0 for sec in self.allseclist: secname = sec.name() for seg in sec: segnames[i] = secname i += 1 for name in seclistnames: idxvec[segnames == name] = True return idxvec def __set_nsegs_lambda_f(self, frequency=100, d_lambda=0.1): """Set the number of segments for section according to the d_lambda-rule for a given input frequency Parameters ---------- frequency: float frequency at which AC length constant is computed d_lambda: float """ neuron.h.pop_section() # dirty fix, see NEURON doc for sec in self.allseclist: sec.nseg = int( (sec.L / (d_lambda * neuron.h.lambda_f(frequency, sec=sec)) + .9) / 2) * 2 + 1 if self.verbose: print("set nsegs using lambda-rule with frequency %i." % frequency) def __set_nsegs_lambda100(self, d_lambda=0.1): """Set the numbers of segments using d_lambda(100)""" self.__set_nsegs_lambda_f(frequency=100, d_lambda=d_lambda) def __set_nsegs_fixed_length(self, maxlength): """Set nseg for sections so that every segment L < maxlength""" for sec in self.allseclist: sec.nseg = int(sec.L / maxlength) + 1 def __calc_totnsegs(self): """Calculate the number of segments in the allseclist""" i = 0 for sec in self.allseclist: i += sec.nseg return i def __check_currents(self): """Check that the sum of all membrane and electrode currents over all segments is sufficiently close to zero""" raise NotImplementedError('this function need to be written') def __set_ra_and_cm(self): """Insert ra and cm on all segments""" for sec in self.allseclist: if self.Ra is not None: sec.Ra = self.Ra if self.cm is not None: sec.cm = self.cm def __set_passive(self): """Insert passive mechanism on all segments""" for sec in self.allseclist: sec.insert('pas') sec.g_pas = self.passive_parameters['g_pas'] sec.e_pas = self.passive_parameters['e_pas'] def __set_extracellular(self): """Insert extracellular mechanism on all sections to set an external potential V_ext as boundary condition. """ for sec in self.allseclist: sec.insert('extracellular') self.extracellular = True def set_synapse(self, idx, syntype, record_current=False, record_potential=False, weight=None, **kwargs): """Insert synapse on cell segment Parameters ---------- idx: int Index of compartment where synapse is inserted syntype: str Type of synapse. Built-in types in NEURON: ExpSyn, Exp2Syn record_current: bool If True, record synapse current record_potential: bool If True, record postsynaptic potential seen by the synapse weight: float Strength of synapse kwargs arguments passed on from class Synapse Returns ------- int index of synapse object on cell """ if not hasattr(self, '_hoc_synlist'): self._hoc_synlist = neuron.h.List() if not hasattr(self, '_synitorecord'): self._synitorecord = [] if not hasattr(self, '_synvtorecord'): self._synvtorecord = [] if not hasattr(self, '_hoc_netstimlist'): self._hoc_netstimlist = neuron.h.List() if not hasattr(self, '_hoc_netconlist'): self._hoc_netconlist = neuron.h.List() if not hasattr(self, '_sptimeslist'): self._sptimeslist = [] # need to append w. one empty array per synapse self._sptimeslist.append(np.array([])) i = 0 cmd = 'neuron.h.{}(seg.x, sec=sec)' for sec in self.allseclist: for seg in sec: if i == idx: command = cmd.format(syntype) syn = eval(command, locals(), globals()) for param in list(kwargs.keys()): try: setattr(syn, param, kwargs[param]) except BaseException: pass self._hoc_synlist.append(syn) # create NetStim (generator) and NetCon (connection) # objects self._hoc_netstimlist.append(neuron.h.NetStim(0.5)) self._hoc_netstimlist[-1].number = 0 nc = neuron.h.NetCon(self._hoc_netstimlist[-1], syn) nc.weight[0] = weight self._hoc_netconlist.append(nc) # record current if record_current: self._synitorecord.append( self._hoc_synlist.count() - 1) # record potential if record_potential: self._synvtorecord.append( self._hoc_synlist.count() - 1) i += 1 return self._hoc_synlist.count() - 1 def set_point_process(self, idx, pptype, record_current=False, record_potential=False, **kwargs): """Insert pptype-electrode type pointprocess on segment numbered idx on cell object Parameters ---------- idx: int Index of compartment where point process is inserted pptype: str Type of pointprocess. Examples: SEClamp, VClamp, IClamp, SinIClamp, ChirpIClamp record_current: bool Decides if current is stored kwargs Parameters passed on from class StimIntElectrode Returns ------- int index of point process on cell """ if not hasattr(self, '_hoc_stimlist'): self._hoc_stimlist = neuron.h.List() if not hasattr(self, '_stimitorecord'): self._stimitorecord = [] if not hasattr(self, '_stimvtorecord'): self._stimvtorecord = [] i = 0 cmd1 = 'neuron.h.' cmd2 = '(seg.x, sec=sec)' ppset = False for sec in self.allseclist: for seg in sec: if i == idx: command = cmd1 + pptype + cmd2 stim = eval(command, locals(), globals()) for key, value in kwargs.items(): try: itr = enumerate(iter(value)) except TypeError: setattr(stim, key, value) else: for i, v in itr: getattr(stim, key)[i] = v self._hoc_stimlist.append(stim) # record current if record_current: self._stimitorecord.append( self._hoc_stimlist.count() - 1) # record potential if record_potential: self._stimvtorecord.append( self._hoc_stimlist.count() - 1) ppset = True break i += 1 if ppset: break return self._hoc_stimlist.count() - 1 def _collect_geometry(self): """Collects x, y, z-coordinates from NEURON""" # None-type some attributes if they do not exist: if not hasattr(self, 'x'): self.x = None self.y = None self.z = None self.area = None self.d = None self.length = None _collect_geometry_neuron(self) self.somaidx = self.get_idx(section='soma') if self.somaidx.size > 1: xmids = self.x[self.somaidx].mean(axis=-1) ymids = self.y[self.somaidx].mean(axis=-1) zmids = self.z[self.somaidx].mean(axis=-1) self.somapos = np.zeros(3) self.somapos[0] = xmids.mean() self.somapos[1] = ymids.mean() self.somapos[2] = zmids.mean() elif self.somaidx.size == 1: self.somapos = np.zeros(3) self.somapos[0] = self.x[self.somaidx].mean() self.somapos[1] = self.y[self.somaidx].mean() self.somapos[2] = self.z[self.somaidx].mean() elif self.somaidx.size == 0: if self.verbose: warn("There is no soma!" + "Using first segment as root point") self.somaidx = np.array([0]) self.somapos = np.zeros(3) self.somapos[0] = self.x[self.somaidx].mean() self.somapos[1] = self.y[self.somaidx].mean() self.somapos[2] = self.z[self.somaidx].mean() else: raise Exception('Huh?!') def get_idx(self, section='allsec', z_min=-np.inf, z_max=np.inf): """ Returns compartment idx of segments from sections with names that match the pattern defined in input section on interval [z_min, z_max]. Parameters ---------- section: str Any entry in cell.allsecnames or just 'allsec'. z_min: float Depth filter. Specify minimum z-position z_max: float Depth filter. Specify maximum z-position Returns ------- ndarray, dtype=int segment indices Examples -------- >>> idx = cell.get_idx(section='allsec') >>> print(idx) >>> idx = cell.get_idx(section=['soma', 'dend', 'apic']) >>> print(idx) """ if section == 'allsec': seclist = neuron.h.allsec() else: seclist = neuron.h.SectionList() if isinstance(section, str): for sec in self.allseclist: if sec.name().find(section) >= 0: seclist.append(sec=sec) elif isinstance(section, list): for secname in section: for sec in self.allseclist: if sec.name().find(secname) >= 0: seclist.append(sec=sec) else: if self.verbose: print('%s did not match any section name' % str(section)) idx = self.__get_idx(seclist) sel_z_idx = ( self.z[idx].mean( axis=- 1) > z_min) & ( self.z[idx].mean( axis=- 1) < z_max) return np.arange(self.totnsegs)[idx][sel_z_idx] def get_closest_idx(self, x=0., y=0., z=0., section='allsec'): """Get the index number of a segment in specified section which midpoint is closest to the coordinates defined by the user Parameters ---------- x: float x-coordinate y: float y-coordinate z: float z-coordinate section: str String matching a section-name. Defaults to 'allsec'. Returns ------- int segment index """ idx = self.get_idx(section) dist = ((self.x[idx].mean(axis=-1) - x)**2 + (self.y[idx].mean(axis=-1) - y)**2 + (self.z[idx].mean(axis=-1) - z)**2) return idx[np.argmin(dist)] def get_rand_idx_area_norm(self, section='allsec', nidx=1, z_min=-1E6, z_max=1E6): """Return nidx segment indices in section with random probability normalized to the membrane area of segment on interval [z_min, z_max] Parameters ---------- section: str String matching a section-name nidx: int Number of random indices z_min: float Depth filter z_max: float Depth filter Returns ------- ndarray, dtype=int segment indices """ poss_idx = self.get_idx(section=section, z_min=z_min, z_max=z_max) if nidx < 1: print('nidx < 1, returning empty array') return np.array([]) elif poss_idx.size == 0: print('No possible segment idx match quiery - returning ' 'empty array') return np.array([]) else: area = self.area[poss_idx] area /= area.sum() return alias_method(poss_idx, area, nidx) def get_rand_idx_area_and_distribution_norm(self, section='allsec', nidx=1, z_min=-1E6, z_max=1E6, fun=scipy.stats.norm, funargs=dict(loc=0, scale=100), funweights=None): """ Return nidx segment indices in section with random probability normalized to the membrane area of each segment multiplied by the value of the probability density function of "fun", a function in the scipy.stats module with corresponding function arguments in "funargs" on the interval [z_min, z_max] Parameters ---------- section: str string matching a section name nidx: int number of random indices z_min: float lower depth interval z_max: float upper depth interval fun: function or str, or iterable of function or str if function a scipy.stats method, if str, must be method in scipy.stats module with the same name (like 'norm'), if iterable (list, tuple, numpy.array) of function or str some probability distribution in scipy.stats module funargs: dict or iterable iterable (list, tuple, numpy.array) of dict, arguments to fun.pdf method (e.g., w. keys 'loc' and 'scale') funweights: None or iterable iterable (list, tuple, numpy.array) of floats, scaling of each individual fun (i.e., introduces layer specificity) Examples -------- >>> import LFPy >>> import numpy as np >>> import scipy.stats as ss >>> import matplotlib.pyplot as plt >>> from os.path import join >>> cell = LFPy.Cell(morphology=join('cells', 'cells', 'j4a.hoc')) >>> cell.set_rotation(x=4.99, y=-4.33, z=3.14) >>> idx = cell.get_rand_idx_area_and_distribution_norm( nidx=10000, fun=ss.norm, funargs=dict(loc=0, scale=200)) >>> bins = np.arange(-30, 120)*10 >>> plt.hist(cell.zmid[idx], bins=bins, alpha=0.5) >>> plt.show() """ poss_idx = self.get_idx(section=section, z_min=z_min, z_max=z_max) if nidx < 1: print('nidx < 1, returning empty array') return np.array([]) elif poss_idx.size == 0: print('No possible segment idx match query - returning ' 'empty array') return np.array([]) else: p = self.area[poss_idx] # scale with density function if type(fun) in [list, tuple, np.ndarray]: assert type(funargs) in [list, tuple, np.ndarray] assert type(funweights) in [list, tuple, np.ndarray] assert len(fun) == len(funargs) & len(fun) == len(funweights) mod = np.zeros(poss_idx.shape) for f, args, scl in zip(fun, funargs, funweights): if isinstance(f, str) and f in dir(scipy.stats): f = getattr(scipy.stats, f) df = f(**args) mod += df.pdf(x=self.z[poss_idx].mean(axis=-1)) * scl p *= mod else: if isinstance(fun, str) and fun in dir(scipy.stats): fun = getattr(scipy.stats, fun) df = fun(**funargs) p *= df.pdf(x=self.z[poss_idx].mean(axis=-1)) # normalize p /= p.sum() return alias_method(poss_idx, p, nidx) def enable_extracellular_stimulation( self, electrode, t_ext=None, n=1, model='inf'): r""" Enable extracellular stimulation with 'extracellular' mechanism. Extracellular potentials are computed from the electrode currents using the pointsource approximation. If 'model' is 'inf' (default), potentials are computed as (:math:`r_i` is the position of a comparment i, :math:`r_e` is the position of an elextrode e, :math:`\sigma` is the conductivity of the medium): .. math:: V_e(r_i) = \sum_n \frac{I_n}{4 \pi \sigma |r_i - r_n|} If model is 'semi', the method of images is used: .. math:: V_e(r_i) = \sum_n \frac{I_n}{2 \pi \sigma |r_i - r_n|} Parameters ---------- electrode: RecExtElectrode Electrode object with stimulating currents t_ext: np.ndarray or list Time im ms corrisponding to step changes in the provided currents. If None, currents are assumed to have the same time steps as NEURON simulation. n: int Points per electrode to compute spatial averaging model: str 'inf' or 'semi'. If 'inf' the medium is assumed to be infinite and homogeneous. If 'semi', the method of images is used. Returns ------- v_ext: np.ndarray Computed extracellular potentials at cell mid points """ # access electrode object and append mapping if electrode is not None: # put electrode argument in list if needed if isinstance(electrode, list): electrodes = electrode else: electrodes = [electrode] else: print("'electrode' is None") return assert model in ['inf', 'semi'], "'model' can be 'inf' or 'semi'" # extracellular stimulation if np.any([np.any(el.probe.currents != 0) for el in electrodes]): cell_mid_points = np.array([self.x.mean(axis=-1), self.y.mean(axis=-1), self.z.mean(axis=-1)]).T n_tsteps = int(self.tstop / self.dt + 1) t_cell = np.arange(n_tsteps) * self.dt if t_ext is None: print("Assuming t_ext is the same as simulation time") t_ext = t_cell for electrode in electrodes: assert electrode.probe.currents.shape[1] == len(t_cell), \ ("Discrepancy between t_ext and cell simulation time" + "steps. Provide the 't_ext' argument") else: assert len(t_ext) < len(t_cell), \ "Stimulation time steps greater than cell simulation steps" v_ext = np.zeros((self.totnsegs, len(t_ext))) for electrode in electrodes: if np.any(np.any(electrode.probe.currents != 0)): electrode.probe.points_per_electrode = int(n) electrode.probe.model = model ve = electrode.probe.compute_field(cell_mid_points) if len(electrode.probe.currents.shape) == 1: ve = ve[:, np.newaxis] v_ext += ve self.__set_extracellular() self.insert_v_ext(v_ext, np.array(t_ext)) else: v_ext = None return v_ext def simulate(self, probes=None, rec_imem=False, rec_vmem=False, rec_ipas=False, rec_icap=False, rec_variables=[], variable_dt=False, atol=0.001, rtol=0., to_memory=True, to_file=False, file_name=None, **kwargs): """ This is the main function running the simulation of the NEURON model. Start NEURON simulation and record variables specified by arguments. Parameters ---------- probes: list of :obj:, optional None or list of LFPykit.RecExtElectrode like object instances that each have a public method `get_transformation_matrix` returning a matrix that linearly maps each compartments' transmembrane current to corresponding measurement as .. math:: \\mathbf{P} = \\mathbf{M} \\mathbf{I} rec_imem: bool If true, segment membrane currents will be recorded If no electrode argument is given, it is necessary to set rec_imem=True in order to make predictions later on. Units of (nA). rec_vmem: bool Record segment membrane voltages (mV) rec_ipas: bool Record passive segment membrane currents (nA) rec_icap: bool Record capacitive segment membrane currents (nA) rec_variables: list List of segment state variables to record, e.g. arg=['cai', ] variable_dt: bool Use NEURON's variable timestep method atol: float Absolute local error tolerance for NEURON variable timestep method rtol: float Relative local error tolerance for NEURON variable timestep method to_memory: bool Only valid with probes=[:obj:], store measurements as `:obj:.data` to_file: bool Only valid with probes, save simulated data in hdf5 file format file_name: str Name of hdf5 file, '.h5' is appended if it doesnt exist """ for key in kwargs.keys(): if key in ['electrode', 'rec_current_dipole_moment', 'dotprodcoeffs', 'rec_isyn', 'rec_vmemsyn', 'rec_istim', 'rec_vmemstim']: warn('Cell.simulate parameter {} is deprecated.'.format(key)) # set up integrator, use the CVode().fast_imem method by default # as it doesn't hurt sim speeds much if at all. cvode = neuron.h.CVode() try: cvode.use_fast_imem(1) except AttributeError: raise Exception('neuron.h.CVode().use_fast_imem() method not ' 'found. Update NEURON to v.7.4 or newer') if not variable_dt: dt = self.dt else: dt = None self._set_soma_volt_recorder(dt) if rec_imem: self._set_imem_recorders(dt) if rec_vmem: self._set_voltage_recorders(dt) if rec_ipas: self._set_ipas_recorders(dt) if rec_icap: self._set_icap_recorders(dt) if len(rec_variables) > 0: self._set_variable_recorders(rec_variables, dt) if hasattr(self, '_stimitorecord'): if len(self._stimitorecord) > 0: self.__set_ipointprocess_recorders(dt) if hasattr(self, '_stimvtorecord'): if len(self._stimvtorecord) > 0: self.__set_vpointprocess_recorders(dt) if hasattr(self, '_synitorecord'): if len(self._synitorecord) > 0: self.__set_isyn_recorders(dt) if hasattr(self, '_synvtorecord'): if len(self._synvtorecord) > 0: self.__set_vsyn_recorders(dt) # set time recorder from NEURON self.__set_time_recorders(dt) # run fadvance until t >= tstop, and calculate LFP if asked for if probes is None or len(probes) == 0: if not rec_imem and self.verbose: print("rec_imem = %s, membrane currents will not be recorded!" % str(rec_imem)) self.__run_simulation(cvode, variable_dt, atol, rtol) else: # simulate with probes saving to memory and/or file: _run_simulation_with_probes(self, cvode, probes, variable_dt, atol, rtol, to_memory, to_file, file_name) # somatic trace if self.nsomasec >= 1: self.somav = np.array(self.somav) self.__collect_tvec() if rec_imem: self._calc_imem() if rec_ipas: self._calc_ipas() if rec_icap: self._calc_icap() if rec_vmem: self._collect_vmem() if hasattr(self, '_hoc_stimireclist'): self._collect_istim() if hasattr(self, '_hoc_stimvreclist'): self.__collect_vstim() if hasattr(self, '_hoc_synireclist'): self._collect_isyn() if hasattr(self, '_hoc_synvreclist'): self._collect_vsyn() if len(rec_variables) > 0: self._collect_rec_variables(rec_variables) if hasattr(self, '_hoc_netstimlist'): self._hoc_netstimlist = None del self._hoc_netstimlist self.__purge_hoc_pointprocesses() def __purge_hoc_pointprocesses(self): """ Empty lists which may store point process objects in `hoc` name space. This is needed to avoid "Segmentation Fault 11" """ if hasattr(self, '_hoc_synlist'): self._hoc_synlist.remove_all() if hasattr(self, '__hoc_stimlist'): self._hoc_stimlist.remove_all() def __run_simulation(self, cvode, variable_dt=False, atol=0.001, rtol=0.): """ Running the actual simulation in NEURON, simulations in NEURON is now interruptable. """ neuron.h.dt = self.dt # variable dt method if variable_dt: cvode.active(1) cvode.atol(atol) cvode.rtol(rtol) else: cvode.active(0) # re-initialize state neuron.h.finitialize(self.v_init * units.mV) # initialize current- and record if cvode.active(): cvode.re_init() else: neuron.h.fcurrent() neuron.h.frecord_init() # Starting simulation at t != 0 neuron.h.t = self.tstart self._load_spikes() # advance simulation until tstop neuron.h.continuerun(self.tstop * units.ms) # for consistency with 'old' behaviour where tstop is included in tvec: if neuron.h.t < self.tstop: neuron.h.fadvance() def __collect_tvec(self): """ Set the tvec to be a monotonically increasing numpy array after sim. """ self.tvec = np.array(self._neuron_tvec.to_python()) self._neuron_tvec = None del self._neuron_tvec def _calc_imem(self): """ Fetch the vectors from the memireclist and calculate self.imem containing all the membrane currents. """ self.imem = np.array(self._hoc_memireclist) self._hoc_memireclist = None del self._hoc_memireclist def _calc_ipas(self): """ Get the passive currents """ self.ipas = np.array(self._hoc_memipasreclist) for i in range(self.ipas.shape[0]): self.ipas[i, ] *= self.area[i] * 1E-2 self._hoc_memipasreclist = None del self._hoc_memipasreclist def _calc_icap(self): """ Get the capacitive currents """ self.icap = np.array(self._hoc_memicapreclist) for i in range(self.icap.shape[0]): self.icap[i, ] *= self.area[i] * 1E-2 self._hoc_memicapreclist = None del self._hoc_memicapreclist def _collect_vmem(self): """ Get the membrane currents """ self.vmem = np.array(self._hoc_memvreclist) self._hoc_memvreclist = None del self._hoc_memvreclist def _collect_isyn(self): """ Get the synaptic currents """ for syn in self.synapses: if syn.record_current: syn.collect_current(self) self._hoc_synireclist = None del self._hoc_synireclist def _collect_vsyn(self): """ Collect the membrane voltage of segments with synapses """ for syn in self.synapses: if syn.record_potential: syn.collect_potential(self) self._hoc_synvreclist = None del self._hoc_synvreclist def _collect_istim(self): """ Get the pointprocess currents """ for pp in self.pointprocesses: if pp.record_current: pp.collect_current(self) self._hoc_stimireclist = None del self._hoc_stimireclist def __collect_vstim(self): """ Collect the membrane voltage of segments with stimulus """ for pp in self.pointprocesses: if pp.record_potential: pp.collect_potential(self) self._hoc_stimvreclist = None del self._hoc_stimvreclist def _collect_rec_variables(self, rec_variables): """ Create dict of np.arrays from recorded variables, each dictionary element named as the corresponding recorded variable name, i.e 'cai' """ self.rec_variables = {} i = 0 for values in self._hoc_recvariablesreclist: self.rec_variables.update({rec_variables[i]: np.array(values)}) if self.verbose: print('collected recorded variable %s' % rec_variables[i]) i += 1 del self._hoc_recvariablesreclist def _load_spikes(self): """ Initialize spiketimes from netcon if they exist """ if hasattr(self, '_hoc_synlist'): if len(self._hoc_synlist) == len(self._sptimeslist): for i in range(int(self._hoc_synlist.count())): for spt in self._sptimeslist[i]: self._hoc_netconlist.o(i).event(spt) def _set_soma_volt_recorder(self, dt): """Record somatic membrane potential""" if self.nsomasec == 0: if self.verbose: warn('Cell instance appears to have no somatic section. ' 'No somav attribute will be set.') elif self.nsomasec == 1: if dt is not None: self.somav = neuron.h.Vector(int(self.tstop / self.dt + 1)) for sec in self.somalist: self.somav.record(sec(0.5)._ref_v, self.dt) else: self.somav = neuron.h.Vector() for sec in self.somalist: self.somav.record(sec(0.5)._ref_v) elif self.nsomasec > 1: if dt is not None: self.somav = neuron.h.Vector(int(self.tstop / self.dt + 1)) nseg = self.get_idx('soma').size i, j = divmod(nseg, 2) k = 1 for sec in self.somalist: for seg in sec: if nseg == 2 and k == 1: # if 2 segments, record from the first one: self.somav.record(seg._ref_v, self.dt) else: if k == i * 2: # record from one of the middle segments: self.somav.record(seg._ref_v, self.dt) k += 1 else: self.somav = neuron.h.Vector() nseg = self.get_idx('soma').size i, j = divmod(nseg, 2) k = 1 for sec in self.somalist: for seg in sec: if nseg == 2 and k == 1: # if 2 segments, record from the first one: self.somav.record(seg._ref_v) else: if k == i * 2: # record from one of the middle segments: self.somav.record(seg._ref_v) k += 1 def _set_imem_recorders(self, dt): """ Record membrane currents for all segments """ self._hoc_memireclist = neuron.h.List() for sec in self.allseclist: for seg in sec: if dt is not None: memirec = neuron.h.Vector(int(self.tstop / self.dt + 1)) memirec.record(seg._ref_i_membrane_, self.dt) else: memirec = neuron.h.Vector() memirec.record(seg._ref_i_membrane_) self._hoc_memireclist.append(memirec) def __set_time_recorders(self, dt): """ Record time of simulation """ if dt is not None: self._neuron_tvec = neuron.h.Vector(int(self.tstop / self.dt + 1)) self._neuron_tvec.record(neuron.h._ref_t, self.dt) else: self._neuron_tvec = neuron.h.Vector() self._neuron_tvec.record(neuron.h._ref_t) def _set_ipas_recorders(self, dt): """ Record passive membrane currents for all segments """ self._hoc_memipasreclist = neuron.h.List() for sec in self.allseclist: for seg in sec: if dt is not None: memipasrec = neuron.h.Vector(int(self.tstop / self.dt + 1)) memipasrec.record(seg._ref_i_pas, self.dt) else: memipasrec = neuron.h.Vector() memipasrec.record(seg._ref_i_pas) self._hoc_memipasreclist.append(memipasrec) def _set_icap_recorders(self, dt): """ Record capacitive membrane currents for all segments """ self._hoc_memicapreclist = neuron.h.List() for sec in self.allseclist: for seg in sec: if dt is not None: memicaprec = neuron.h.Vector(int(self.tstop / self.dt + 1)) memicaprec.record(seg._ref_i_cap, self.dt) else: memicaprec = neuron.h.Vector() memicaprec.record(seg._ref_i_cap) self._hoc_memicapreclist.append(memicaprec) def __set_ipointprocess_recorders(self, dt): """ Record point process current """ self._hoc_stimireclist = neuron.h.List() for idx, pp in enumerate(self.pointprocesses): if idx in self._stimitorecord: stim = self._hoc_stimlist[idx] if dt is not None: stimirec = neuron.h.Vector(int(self.tstop / self.dt + 1)) stimirec.record(stim._ref_i, self.dt) else: stimirec = neuron.h.Vector() stimirec.record(stim._ref_i) else: stimirec = neuron.h.Vector(0) self._hoc_stimireclist.append(stimirec) def __set_vpointprocess_recorders(self, dt): """ Record point process membrane """ self._hoc_stimvreclist = neuron.h.List() for idx, pp in enumerate(self.pointprocesses): if idx in self._stimvtorecord: stim = self._hoc_stimlist[idx] seg = stim.get_segment() if dt is not None: stimvrec = neuron.h.Vector(int(self.tstop / self.dt + 1)) stimvrec.record(seg._ref_v, self.dt) else: stimvrec = neuron.h.Vector() stimvrec.record(seg._ref_v) else: stimvrec = neuron.h.Vector(0) self._hoc_stimvreclist.append(stimvrec) def __set_isyn_recorders(self, dt): """ Record point process current """ self._hoc_synireclist = neuron.h.List() for idx, pp in enumerate(self.synapses): if idx in self._synitorecord: syn = self._hoc_synlist[idx] if dt is not None: synirec = neuron.h.Vector(int(self.tstop / self.dt + 1)) synirec.record(syn._ref_i, self.dt) else: synirec = neuron.h.Vector() synirec.record(syn._ref_i) else: synirec = neuron.h.Vector(0) self._hoc_synireclist.append(synirec) def __set_vsyn_recorders(self, dt): """ Record point process membrane """ self._hoc_synvreclist = neuron.h.List() for idx, pp in enumerate(self.synapses): if idx in self._synvtorecord: syn = self._hoc_synlist[idx] seg = syn.get_segment() if dt is not None: synvrec = neuron.h.Vector(int(self.tstop / self.dt + 1)) synvrec.record(seg._ref_v, self.dt) else: synvrec = neuron.h.Vector() synvrec.record(seg._ref_v) else: synvrec = neuron.h.Vector(0) self._hoc_synvreclist.append(synvrec) def _set_voltage_recorders(self, dt): """ Record membrane potentials for all segments """ self._hoc_memvreclist = neuron.h.List() for sec in self.allseclist: for seg in sec: if dt is not None: memvrec = neuron.h.Vector(int(self.tstop / self.dt + 1)) memvrec.record(seg._ref_v, self.dt) else: memvrec = neuron.h.Vector() memvrec.record(seg._ref_v) self._hoc_memvreclist.append(memvrec) def __set_current_dipole_moment_array(self, dt): """ Creates container for current dipole moment, an empty n_timesteps x 3 `numpy.ndarray` that will be filled with values during the course of each simulation """ if dt is not None: self.current_dipole_moment = np.zeros( (int(self.tstop / self.dt + 1), 3)) else: self.current_dipole_moment = [] def _set_variable_recorders(self, rec_variables, dt): """ Create a recorder for each variable name in list rec_variables Variables is stored in nested list self._hoc_recvariablesreclist """ self._hoc_recvariablesreclist = neuron.h.List() for variable in rec_variables: variablereclist = neuron.h.List() self._hoc_recvariablesreclist.append(variablereclist) for sec in self.allseclist: for seg in sec: if dt is not None: recvector = neuron.h.Vector( int(self.tstop / self.dt + 1)) else: recvector = neuron.h.Vector() try: if dt is not None: recvector.record( getattr( seg, '_ref_%s' % variable), self.dt) else: recvector.record( getattr( seg, '_ref_%s' % variable)) except(NameError, AttributeError): print('non-existing variable %s, section %s.%f' % (variable, sec.name(), seg.x)) variablereclist.append(recvector) def set_pos(self, x=0., y=0., z=0.): """Set the cell position. Move the cell geometry so that midpoint of soma section is in (x, y, z). If no soma pos, use the first segment Parameters ---------- x: float x position defaults to 0.0 y: float y position defaults to 0.0 z: float z position defaults to 0.0 """ diffx = x - self.somapos[0] diffy = y - self.somapos[1] diffz = z - self.somapos[2] # also update the pt3d_pos: if self.pt3d and hasattr(self, 'x3d'): self._set_pt3d_pos(diffx, diffy, diffz) else: self.somapos[0] = x self.somapos[1] = y self.somapos[2] = z self.x[:, 0] += diffx self.y[:, 0] += diffy self.z[:, 0] += diffz self.x[:, -1] += diffx self.y[:, -1] += diffy self.z[:, -1] += diffz self.__update_synapse_positions() def cellpickler(self, filename, pickler=pickle.dump): """Save data in cell to filename, using cPickle. It will however destroy any ``neuron.h`` objects upon saving, as c-objects cannot be pickled Parameters ---------- filename: str Where to save cell Examples -------- >>> # To save a cell, issue: >>> cell.cellpickler('cell.cpickle') >>> # To load this cell again in another session: >>> import cPickle >>> with file('cell.cpickle', 'rb') as f: >>> cell = cPickle.load(f) Returns ------- None or pickle """ self.strip_hoc_objects() if pickler == pickle.dump: filen = open(filename, 'wb') pickler(self, filen, protocol=2) filen.close() return None elif pickler == pickle.dumps: return pickle.dumps(self) def __update_synapse_positions(self): """ Update synapse positions after rotation of morphology """ for i in range(len(self.synapses)): self.synapses[i].update_pos(self) def set_rotation(self, x=None, y=None, z=None, rotation_order='xyz'): """ Rotate geometry of cell object around the x-, y-, z-axis in the order described by rotation_order parameter. Parameters ---------- x: float or None rotation angle in radians. Default: None y: float or None rotation angle in radians. Default: None z: float or None rotation angle in radians. Default: None rotation_order: str string with 3 elements containing x, y and z e.g. 'xyz', 'zyx'. Default: 'xyz' Examples -------- >>> cell = LFPy.Cell(**kwargs) >>> rotation = {'x': 1.233, 'y': 0.236, 'z': np.pi} >>> cell.set_rotation(**rotation) """ if not isinstance(rotation_order, str): raise AttributeError('rotation_order must be a string') elif not np.all([u in rotation_order for u in 'xyz']): raise AttributeError("'x', 'y', and 'z' must be in rotation_order") elif len(rotation_order) != 3: raise AttributeError( "rotation_order should have 3 elements (e.g. 'zyx')") for ax in rotation_order: if ax == 'x' and x is not None: theta = -x rotation_x = np.array([[1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)]]) rel_start, rel_end = self._rel_positions() rel_start = np.dot(rel_start, rotation_x) rel_end = np.dot(rel_end, rotation_x) self._real_positions(rel_start, rel_end) if self.verbose: print( 'Rotated geometry %g radians around x-axis' % (-theta)) else: if self.verbose: print('Geometry not rotated around x-axis') if ax == 'y' and y is not None: phi = -y rotation_y = np.array([[np.cos(phi), 0, np.sin(phi)], [0, 1, 0], [-np.sin(phi), 0, np.cos(phi)]]) rel_start, rel_end = self._rel_positions() rel_start = np.dot(rel_start, rotation_y) rel_end = np.dot(rel_end, rotation_y) self._real_positions(rel_start, rel_end) if self.verbose: print('Rotated geometry %g radians around y-axis' % (-phi)) else: if self.verbose: print('Geometry not rotated around y-axis') if ax == 'z' and z is not None: gamma = -z rotation_z = np.array([[np.cos(gamma), -np.sin(gamma), 0], [np.sin(gamma), np.cos(gamma), 0], [0, 0, 1]]) rel_start, rel_end = self._rel_positions() rel_start = np.dot(rel_start, rotation_z) rel_end = np.dot(rel_end, rotation_z) self._real_positions(rel_start, rel_end) if self.verbose: print( 'Rotated geometry %g radians around z-axis' % (-gamma)) else: if self.verbose: print('Geometry not rotated around z-axis') # rotate the pt3d geometry accordingly if self.pt3d and hasattr(self, 'x3d'): self._set_pt3d_rotation(x, y, z, rotation_order) def chiral_morphology(self, axis='x'): """ Mirror the morphology around given axis, (default x-axis), useful to introduce more heterogeneouties in morphology shapes Parameters ---------- axis: str 'x' or 'y' or 'z' """ # morphology relative to soma-position rel_start, rel_end = self._rel_positions() if axis == 'x': rel_start[:, 0] = -rel_start[:, 0] rel_end[:, 0] = -rel_end[:, 0] elif axis == 'y': rel_start[:, 1] = -rel_start[:, 1] rel_end[:, 1] = -rel_end[:, 1] elif axis == 'z': rel_start[:, 2] = -rel_start[:, 2] rel_end[:, 2] = -rel_end[:, 2] else: raise Exception("axis must be either 'x', 'y' or 'z'") if self.verbose: print('morphology mirrored across %s-axis' % axis) # set the proper 3D positions self._real_positions(rel_start, rel_end) def _rel_positions(self): """ Morphology relative to soma position """ rel_start = np.array([self.x[:, 0] - self.somapos[0], self.y[:, 0] - self.somapos[1], self.z[:, 0] - self.somapos[2]]).T rel_end = np.array([self.x[:, -1] - self.somapos[0], self.y[:, -1] - self.somapos[1], self.z[:, -1] - self.somapos[2]]).T return rel_start, rel_end def _real_positions(self, rel_start, rel_end): """ Morphology coordinates relative to Origo """ self.x[:, 0] = rel_start[:, 0] + self.somapos[0] self.y[:, 0] = rel_start[:, 1] + self.somapos[1] self.z[:, 0] = rel_start[:, 2] + self.somapos[2] self.x[:, -1] = rel_end[:, 0] + self.somapos[0] self.y[:, -1] = rel_end[:, 1] + self.somapos[1] self.z[:, -1] = rel_end[:, 2] + self.somapos[2] self.__update_synapse_positions() def get_rand_prob_area_norm(self, section='allsec', z_min=-10000, z_max=10000): """ Return the probability (0-1) for synaptic coupling on segments in section sum(prob)=1 over all segments in section. Probability normalized by area. Parameters ---------- section: str string matching a section-name. Defaults to 'allsec' z_min: float depth filter z_max: float depth filter Returns ------- ndarray, dtype=float """ idx = self.get_idx(section=section, z_min=z_min, z_max=z_max) prob = self.area[idx] / sum(self.area[idx]) return prob def get_rand_prob_area_norm_from_idx(self, idx=np.array([0])): """ Return the normalized probability (0-1) for synaptic coupling on segments in idx-array. Normalised probability determined by area of segments. Parameters ---------- idx: ndarray, dtype=int. array of segment indices Returns ------- ndarray, dtype=float """ prob = self.area[idx] / sum(self.area[idx]) return prob def get_intersegment_vector(self, idx0=0, idx1=0): """Return the distance between midpoints of two segments with index idx0 and idx1. The argument returned is a list [x, y, z], where x = self.x[idx1].mean(axis=-1) - self.x[idx0].mean(axis=-1) etc. Parameters ---------- idx0: int idx1: int Returns ------- list of floats distance between midpoints along x,y,z axis in µm """ vector = [] try: if idx1 < 0 or idx0 < 0: raise Exception('idx0 < 0 or idx1 < 0') vector.append( self.x[idx1].mean(axis=-1) - self.x[idx0].mean(axis=-1)) vector.append( self.y[idx1].mean(axis=-1) - self.y[idx0].mean(axis=-1)) vector.append( self.z[idx1].mean(axis=-1) - self.z[idx0].mean(axis=-1)) return vector except BaseException: ERRMSG = 'idx0 and idx1 must be ints on [0, %i]' % self.totnsegs raise ValueError(ERRMSG) def get_intersegment_distance(self, idx0=0, idx1=0): """ Return the Euclidean distance between midpoints of two segments. Parameters ---------- idx0: int idx1: int Returns ------- float distance (µm). """ try: vector = np.array(self.get_intersegment_vector(idx0, idx1)) return np.sqrt((vector**2).sum()) except BaseException: ERRMSG = 'idx0 and idx1 must be ints on [0, %i]' % self.totnsegs raise ValueError(ERRMSG) def get_idx_children(self, parent="soma[0]"): """Get the idx of parent's children sections, i.e. compartments ids of sections connected to parent-argument Parameters ---------- parent: str name-pattern matching a sectionname. Defaults to "soma[0]" Returns ------- ndarray, dtype=int """ idxvec = np.zeros(self.totnsegs) secnamelist = [] childseclist = [] # filling list of sectionnames for all sections, one entry per segment for sec in self.allseclist: for seg in sec: secnamelist.append(sec.name()) if parent in secnamelist: # filling list of children section-names for sec in self.allseclist: if sec.name() == parent: sref = neuron.h.SectionRef(sec=sec) break assert sec.name() == parent == sref.sec.name() for sec in sref.child: childseclist.append(sec.name()) # idxvec=1 where both coincide i = 0 for sec in secnamelist: for childsec in childseclist: if sec == childsec: idxvec[i] += 1 i += 1 [idx] = np.where(idxvec) return idx else: return np.array([]) def get_idx_parent_children(self, parent="soma[0]"): """ Get all idx of segments of parent and children sections, i.e. segment idx of sections connected to parent-argument, and also of the parent segments Parameters ---------- parent: str name-pattern matching a sectionname. Defaults to "soma[0]" Returns ------- ndarray, dtype=int """ seclist = [parent] for sec in self.allseclist: if sec.name() == parent: sref = neuron.h.SectionRef(sec=sec) break assert sref.sec.name() == parent for sec in sref.child: seclist.append(sec.name()) return self.get_idx(section=seclist) def get_idx_name(self, idx=np.array([0], dtype=int)): ''' Return NEURON convention name of segments with index idx. The returned argument is an array of tuples with corresponding segment idx, section name, and position along the section, like; [(0, 'neuron.h.soma[0]', 0.5),] Parameters ---------- idx: ndarray, dtype int segment indices, must be between 0 and cell.totnsegs Returns ------- ndarray, dtype=object tuples with section names of segments ''' # ensure idx is array-like, or convert if isinstance(idx, int) or np.int64: idx = np.array([idx]) elif len(idx) == 0: return else: idx = np.array(idx).astype(int) # ensure all idx are valid if np.any(idx >= self.totnsegs): wrongidx = idx[np.where(idx >= self.totnsegs)] raise Exception('idx %s >= number of compartments' % str(wrongidx)) # create list of seg names: allsegnames = [] segidx = 0 for sec in self.allseclist: for seg in sec: allsegnames.append((segidx, '%s' % sec.name(), seg.x)) segidx += 1 return np.array(allsegnames, dtype=object)[idx][0] def _collect_pt3d(self): """collect the pt3d info, for each section""" x = [] y = [] z = [] d = [] for sec in self.allseclist: n3d = int(neuron.h.n3d(sec=sec)) x_i, y_i, z_i = np.zeros(n3d), np.zeros(n3d), np.zeros(n3d), d_i = np.zeros(n3d) for i in range(n3d): x_i[i] = neuron.h.x3d(i, sec=sec) y_i[i] = neuron.h.y3d(i, sec=sec) z_i[i] = neuron.h.z3d(i, sec=sec) d_i[i] = neuron.h.diam3d(i, sec=sec) x.append(x_i) y.append(y_i) z.append(z_i) d.append(d_i) # remove offsets which may be present if soma is centred in Origo if len(x) > 1: xoff = x[0].mean() yoff = y[0].mean() zoff = z[0].mean() for i in range(len(x)): x[i] -= xoff y[i] -= yoff z[i] -= zoff return x, y, z, d def _update_pt3d(self): """ update the locations in neuron.hoc.space using neuron.h.pt3dchange() """ for i, sec in enumerate(self.allseclist): n3d = int(neuron.h.n3d(sec=sec)) for n in range(n3d): neuron.h.pt3dchange(n, self.x3d[i][n], self.y3d[i][n], self.z3d[i][n], self.diam3d[i][n], sec=sec) # let NEURON know about the changes we just did: neuron.h.define_shape() # must recollect the geometry, otherwise we get roundoff errors! self._collect_geometry() def _set_pt3d_pos(self, diffx=0, diffy=0, diffz=0): """ Offset pt3d geometry with differential displacement indicated in Cell.set_pos() """ for i in range(len(self.x3d)): self.x3d[i] += diffx self.y3d[i] += diffy self.z3d[i] += diffz self._update_pt3d() def _set_pt3d_rotation(self, x=None, y=None, z=None, rotation_order='xyz'): """ Rotate pt3d geometry of cell object around the x-, y-, z-axis in the order described by rotation_order parameter. rotation_order should be a string with 3 elements containing x, y and z e.g. 'xyz', 'zyx' Input should be angles in radians. using rotation matrices, takes dict with rot. angles, where x, y, z are the rotation angles around respective axes. All rotation angles are optional. Parameters ---------- x: float rotation angle in radians y: float rotation angle in radians z: float rotation angle in radians rotation_order: str rotation order, default: 'xyz' Examples -------- >>> cell = LFPy.Cell(**kwargs) >>> rotation = {'x': 1.233, 'y': 0.236, 'z': np.pi} >>> cell.set_pt3d_rotation(**rotation) """ for ax in rotation_order: if ax == 'x' and x is not None: theta = -x rotation_x = np.array([[1, 0, 0], [0, np.cos(theta), -np.sin(theta)], [0, np.sin(theta), np.cos(theta)]]) for i in range(len(self.x3d)): rel_pos = self._rel_pt3d_positions( self.x3d[i], self.y3d[i], self.z3d[i]) rel_pos = np.dot(rel_pos, rotation_x) self.x3d[i], self.y3d[i], self.z3d[i] = \ self._real_pt3d_positions(rel_pos) if self.verbose: print(('Rotated geometry %g radians around x-axis' % (-theta))) else: if self.verbose: print('Geometry not rotated around x-axis') if ax == 'y' and y is not None: phi = -y rotation_y = np.array([[np.cos(phi), 0, np.sin(phi)], [0, 1, 0], [-np.sin(phi), 0, np.cos(phi)]]) for i in range(len(self.x3d)): rel_pos = self._rel_pt3d_positions( self.x3d[i], self.y3d[i], self.z3d[i]) rel_pos = np.dot(rel_pos, rotation_y) self.x3d[i], self.y3d[i], self.z3d[i] = \ self._real_pt3d_positions(rel_pos) if self.verbose: print('Rotated geometry %g radians around y-axis' % (-phi)) else: if self.verbose: print('Geometry not rotated around y-axis') if ax == 'z' and z is not None: gamma = -z rotation_z = np.array([[np.cos(gamma), -np.sin(gamma), 0], [np.sin(gamma), np.cos(gamma), 0], [0, 0, 1]]) for i in range(len(self.x3d)): rel_pos = self._rel_pt3d_positions( self.x3d[i], self.y3d[i], self.z3d[i]) rel_pos = np.dot(rel_pos, rotation_z) self.x3d[i], self.y3d[i], self.z3d[i] = \ self._real_pt3d_positions(rel_pos) if self.verbose: print( 'Rotated geometry %g radians around z-axis' % (-gamma)) else: if self.verbose: print('Geometry not rotated around z-axis') self._update_pt3d() def _rel_pt3d_positions(self, x, y, z): """Morphology relative to soma position """ rel_pos = np.transpose(np.array([x - self.somapos[0], y - self.somapos[1], z - self.somapos[2]])) return rel_pos def _real_pt3d_positions(self, rel_pos): """Morphology coordinates relative to Origo """ x = rel_pos[:, 0] + self.somapos[0] y = rel_pos[:, 1] + self.somapos[1] z = rel_pos[:, 2] + self.somapos[2] x = np.array(x).flatten() y = np.array(y).flatten() z = np.array(z).flatten() return x, y, z def _create_polygon(self, i, projection=('x', 'z')): """create a polygon to fill for each section""" x = getattr(self, projection[0] + '3d')[i] y = getattr(self, projection[1] + '3d')[i] # x = self.x3d[i] # z = self.z3d[i] d = self.diam3d[i] # calculate angles dx = np.diff(x) dy = np.diff(y) theta = np.arctan2(dy, dx) x = np.r_[x, x[::-1]] y = np.r_[y, y[::-1]] theta = np.r_[theta, theta[::-1]] d = np.r_[d, d[::-1]] # 1st corner: x[0] -= 0.5 * d[0] * np.sin(theta[0]) y[0] += 0.5 * d[0] * np.cos(theta[0]) # pt3d points between start and end of section, first side x[1:dx.size] -= 0.25 * d[1:dx.size] * ( np.sin(theta[:dx.size - 1]) + np.sin(theta[1:dx.size])) y[1:dy.size] += 0.25 * d[1:dy.size] * ( np.cos(theta[:dy.size - 1]) + np.cos(theta[1:dx.size])) # end of section, first side x[dx.size] -= 0.5 * d[dx.size] * np.sin(theta[dx.size]) y[dy.size] += 0.5 * d[dy.size] * np.cos(theta[dy.size]) # other side # end of section, second side x[dx.size + 1] += 0.5 * d[dx.size + 1] * np.sin(theta[dx.size]) y[dy.size + 1] -= 0.5 * d[dy.size + 1] * np.cos(theta[dy.size]) # pt3d points between start and end of section, second side x[::-1][1:dx.size] += 0.25 * d[::-1][1:dx.size] * ( np.sin(theta[::-1][:dx.size - 1]) + np.sin(theta[::-1][1:dx.size])) y[::-1][1:dy.size] -= 0.25 * d[::-1][1:dy.size] * ( np.cos(theta[::-1][:dy.size - 1]) + np.cos(theta[::-1][1:dx.size])) # last corner: x[-1] += 0.5 * d[-1] * np.sin(theta[-1]) y[-1] -= 0.5 * d[-1] * np.cos(theta[-1]) return x, y def get_pt3d_polygons(self, projection=('x', 'z')): """For each section create a polygon in the plane determined by keyword argument projection=('x', 'z'), that can be visualized using e.g., plt.fill() Parameters ---------- projection: tuple of strings Determining projection. Defaults to ('x', 'z') Returns ------- list list of (x, z) tuples giving the trajectory of each section that can be plotted using PolyCollection Examples -------- >>> from matplotlib.collections import PolyCollection >>> import matplotlib.pyplot as plt >>> cell = LFPy.Cell(morphology='PATH/TO/MORPHOLOGY') >>> zips = [] >>> for x, z in cell.get_pt3d_polygons(projection=('x', 'z')): >>> zips.append(list(zip(x, z))) >>> polycol = PolyCollection(zips, >>> edgecolors='none', >>> facecolors='gray') >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> ax.add_collection(polycol) >>> ax.axis(ax.axis('equal')) >>> plt.show() """ if len(projection) != 2: raise ValueError("projection arg be a tuple like ('x', 'y')") if 'x' in projection and 'y' in projection: pass elif 'x' in projection and 'z' in projection: pass elif 'y' in projection and 'z' in projection: pass else: mssg = "projection must be a length 2 tuple of 'x', 'y' or 'z'!" raise ValueError(mssg) assert self.pt3d is True, 'Cell keyword argument pt3d != True' polygons = [] for i in range(len(self.x3d)): polygons.append(self._create_polygon(i, projection)) return polygons def _create_segment_polygon(self, i, projection=('x', 'z')): """Create a polygon to fill for segment i, in the plane determined by kwarg projection""" x = getattr(self, projection[0])[i] z = getattr(self, projection[1])[i] d = self.d[i] # calculate angles dx = np.diff(x) dz = np.diff(z) theta = np.arctan2(dz, dx) x = np.r_[x, x[::-1]] z = np.r_[z, z[::-1]] # 1st corner: x[0] -= 0.5 * d * np.sin(theta) z[0] += 0.5 * d * np.cos(theta) # end of section, first side x[1] -= 0.5 * d * np.sin(theta) z[1] += 0.5 * d * np.cos(theta) # other side # end of section, second side x[2] += 0.5 * d * np.sin(theta) z[2] -= 0.5 * d * np.cos(theta) # last corner: x[3] += 0.5 * d * np.sin(theta) z[3] -= 0.5 * d * np.cos(theta) return x, z def get_idx_polygons(self, projection=('x', 'z')): """For each segment idx in cell create a polygon in the plane determined by the projection kwarg (default ('x', 'z')), that can be visualized using plt.fill() or mpl.collections.PolyCollection Parameters ---------- projection: tuple of strings Determining projection. Defaults to ('x', 'z') Returns ------- polygons: list list of (ndarray, ndarray) tuples giving the trajectory of each section Examples -------- >>> from matplotlib.collections import PolyCollection >>> import matplotlib.pyplot as plt >>> cell = LFPy.Cell(morphology='PATH/TO/MORPHOLOGY') >>> zips = [] >>> for x, z in cell.get_idx_polygons(projection=('x', 'z')): >>> zips.append(list(zip(x, z))) >>> polycol = PolyCollection(zips, >>> edgecolors='none', >>> facecolors='gray') >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> ax.add_collection(polycol) >>> ax.axis(ax.axis('equal')) >>> plt.show() """ if len(projection) != 2: raise ValueError("projection arg be a tuple like ('x', 'y')") if 'x' in projection and 'y' in projection: pass elif 'x' in projection and 'z' in projection: pass elif 'y' in projection and 'z' in projection: pass else: mssg = "projection must be a length 2 tuple of 'x', 'y' or 'z'!" raise ValueError(mssg) polygons = [] for i in np.arange(self.totnsegs): polygons.append(self._create_segment_polygon(i, projection)) return polygons def insert_v_ext(self, v_ext, t_ext): """Set external extracellular potential around cell. Playback of some extracellular potential v_ext on each cell.totnseg compartments. Assumes that the "extracellular"-mechanism is inserted on each compartment. Can be used to study ephaptic effects and similar The inputs will be copied and attached to the cell object as cell.v_ext, cell.t_ext, and converted to (list of) neuron.h.Vector types, to allow playback into each compartment e_extracellular reference. Can not be deleted prior to running cell.simulate() Parameters ---------- v_ext: ndarray Numpy array of size cell.totnsegs x t_ext.size, unit mV t_ext: ndarray Time vector of v_ext in ms Examples -------- >>> import LFPy >>> import numpy as np >>> import matplotlib.pyplot as plt >>> #create cell >>> cell = LFPy.Cell(morphology='morphologies/example_morphology.hoc', >>> passive=True) >>> #time vector and extracellular field for every segment: >>> t_ext = np.arange(cell.tstop / cell.dt+ 1) * cell.dt >>> v_ext = np.random.rand(cell.totnsegs, t_ext.size)-0.5 >>> #insert potentials and record response: >>> cell.insert_v_ext(v_ext, t_ext) >>> cell.simulate(rec_imem=True, rec_vmem=True) >>> fig = plt.figure() >>> ax1 = fig.add_subplot(311) >>> ax2 = fig.add_subplot(312) >>> ax3 = fig.add_subplot(313) >>> eim = ax1.matshow(np.array(cell.v_ext), cmap='spectral') >>> cb1 = fig.colorbar(eim, ax=ax1) >>> cb1.set_label('v_ext') >>> ax1.axis(ax1.axis('tight')) >>> iim = ax2.matshow(cell.imem, cmap='spectral') >>> cb2 = fig.colorbar(iim, ax=ax2) >>> cb2.set_label('imem') >>> ax2.axis(ax2.axis('tight')) >>> vim = ax3.matshow(cell.vmem, cmap='spectral') >>> ax3.axis(ax3.axis('tight')) >>> cb3 = fig.colorbar(vim, ax=ax3) >>> cb3.set_label('vmem') >>> ax3.set_xlabel('tstep') >>> plt.show() """ # test dimensions of input try: if v_ext.shape[0] != self.totnsegs: raise ValueError("v_ext.shape[0] != cell.totnsegs") if v_ext.shape[1] != t_ext.size: raise ValueError('v_ext.shape[1] != t_ext.size') except BaseException: raise ValueError('v_ext, t_ext must both be np.array types') if not self.extracellular: raise Exception('LFPy.Cell arg extracellular != True') # create list of extracellular potentials on each segment, time vector self.t_ext = neuron.h.Vector(t_ext) self.v_ext = [] for v in v_ext: self.v_ext.append(neuron.h.Vector(v)) # play v_ext into e_extracellular reference i = 0 for sec in self.allseclist: for seg in sec: self.v_ext[i].play(seg._ref_e_extracellular, self.t_ext) i += 1 return def get_axial_currents_from_vmem(self, timepoints=None): """Compute axial currents from cell sim: get current magnitude, distance vectors and position vectors. Parameters ---------- timepoints: ndarray, dtype=int array of timepoints in simulation at which you want to compute the axial currents. Defaults to False. If not given, all simulation timesteps will be included. Returns ------- i_axial: ndarray, dtype=float Shape ((cell.totnsegs-1)*2, len(timepoints)) array of axial current magnitudes I in units of (nA) in cell at all timesteps in timepoints, or at all timesteps of the simulation if timepoints=None. Contains two current magnitudes per segment, (except for the root segment): 1) the current from the mid point of the segment to the segment start point, and 2) the current from the segment start point to the mid point of the parent segment. d_vectors: ndarray, dtype=float Shape (3, (cell.totnsegs-1)*2) array of distance vectors traveled by each axial current in i_axial in units of (µm). The indices of the first axis, correspond to the first axis of i_axial and pos_vectors. pos_vectors: ndarray, dtype=float Shape ((cell.totnsegs-1)*2, 3) array of position vectors pointing to the mid point of each axial current in i_axial in units of (µm). The indices of the first axis, correspond to the first axis of i_axial and d_vectors. Raises ------ AttributeError Raises an exeption if the cell.vmem attribute cannot be found """ if not hasattr(self, 'vmem'): raise AttributeError('no vmem, run cell.simulate(rec_vmem=True)') self._ri_list = self.get_axial_resistance() i_axial = [] d_vectors = [] pos_vectors = [] dseg = np.c_[self.x.mean(axis=-1) - self.x[:, 0], self.y.mean(axis=-1) - self.y[:, 0], self.z.mean(axis=-1) - self.z[:, 0]] dpar = np.c_[self.x[:, -1] - self.x.mean(axis=-1), self.y[:, -1] - self.y.mean(axis=-1), self.z[:, -1] - self.z.mean(axis=-1)] # children_dict = self.get_dict_of_children_idx() for sec in self.allseclist: if not neuron.h.SectionRef(sec=sec).has_parent(): if sec.nseg == 1: # skip soma, since soma is an orphan continue else: # the first segment has more than one segment, # need to compute axial currents within this section. seg_idx = 1 parent_idx = 0 bottom_seg = False first_sec = True branch = False parentsec = None children_dict = None connection_dict = None conn_point = 1 else: # section has parent section first_sec = False bottom_seg = True secref = neuron.h.SectionRef(sec=sec) parentseg = secref.parent() parentsec = parentseg.sec children_dict = self.get_dict_of_children_idx() branch = len(children_dict[parentsec.name()]) > 1 connection_dict = self.get_dict_parent_connections() conn_point = connection_dict[sec.name()] # find parent index if conn_point == 1 or parentsec.nseg == 1: internal_parent_idx = -1 # last seg in sec elif conn_point == 0: internal_parent_idx = 0 # first seg in sec else: # if parentseg is not first or last seg in parentsec segment_xlist = np.array( [segment.x for segment in parentsec]) internal_parent_idx = np.abs( segment_xlist - conn_point).argmin() parent_idx = self.get_idx(section=parentsec.name())[ internal_parent_idx] # find segment index seg_idx = self.get_idx(section=sec.name())[0] for _ in sec: if first_sec: first_sec = False continue iseg, ipar = self._parent_and_segment_current(seg_idx, parent_idx, bottom_seg, branch, parentsec, children_dict, connection_dict, conn_point, timepoints, sec ) if bottom_seg: # if a seg is connected to soma, it is # connected to the middle of soma, # and dpar needs to be altered. par_dist = np.array([(self.x[seg_idx, 0] - self.x[parent_idx].mean(axis=-1)), (self.y[seg_idx, 0] - self.y[parent_idx].mean(axis=-1)), (self.z[seg_idx, 0] - self.z[parent_idx].mean(axis=-1))]) else: par_dist = dpar[parent_idx] d_vectors.append(par_dist) d_vectors.append(dseg[seg_idx]) i_axial.append(ipar) i_axial.append(iseg) pos_par = np.array([self.x[seg_idx, 0], self.y[seg_idx, 0], self.z[seg_idx, 0]]) - 0.5 * par_dist pos_seg = np.array([self.x[seg_idx].mean(axis=-1), self.y[seg_idx].mean(axis=-1), self.z[seg_idx].mean(axis=-1)]) pos_seg -= 0.5 * dseg[seg_idx] pos_vectors.append(pos_par) pos_vectors.append(pos_seg) parent_idx = seg_idx seg_idx += 1 branch = False bottom_seg = False return np.array(i_axial), np.array(d_vectors).T, np.array(pos_vectors) def get_axial_resistance(self): """ Return NEURON axial resistance for all cell compartments. Returns ------- ri_list: ndarray, dtype=float Shape (cell.totnsegs, ) array containing neuron.h.ri(seg.x) in units of (MOhm) for all segments in cell calculated using the neuron.h.ri(seg.x) method. neuron.h.ri(seg.x) returns the axial resistance from the middle of the segment to the middle of the parent segment. Note: If seg is the first segment in a section, i.e. the parent segment belongs to a different section or there is no parent section, then neuron.h.ri(seg.x) returns the axial resistance from the middle of the segment to the node connecting the segment to the parent section (or a ghost node if there is no parent) """ ri_list = np.zeros(self.totnsegs) comp = 0 for sec in self.allseclist: for seg in sec: ri_list[comp] = neuron.h.ri(seg.x, sec=sec) comp += 1 return ri_list def get_dict_of_children_idx(self): """ Return dictionary with children segment indices for all sections. Returns ------- children_dict: dictionary Dictionary containing a list for each section, with the segment index of all the section's children. The dictionary is needed to find the sibling of a segment. """ children_dict = {} for sec in self.allseclist: children_dict[sec.name()] = [] for child in neuron.h.SectionRef(sec=sec).child: # add index of first segment of each child children_dict[sec.name()].append(int(self.get_idx( section=child.name())[0])) return children_dict def get_dict_parent_connections(self): """ Return dictionary with parent connection point for all sections. Returns ------- connection_dict: dictionary Dictionary containing a float in range [0, 1] for each section in cell. The float gives the location on the parent segment to which the section is connected. The dictionary is needed for computing axial currents. """ connection_dict = {} for i, sec in enumerate(self.allseclist): connection_dict[sec.name()] = neuron.h.parent_connection(sec=sec) return connection_dict def _parent_and_segment_current(self, seg_idx, parent_idx, bottom_seg, branch=False, parentsec=None, children_dict=None, connection_dict=None, conn_point=1, timepoints=None, sec=None): """ Return axial current from segment (seg_idx) mid to segment start, and current from parent segment (parent_idx) end to parent segment mid. Parameters ---------- seg_idx: int Segment index parent_idx: int Parent index bottom_seg: boolean branch: boolean parentsec: neuron.Section object parent section children_dict: dict or None Default None connection_dict: dict or None Default None conn_point: float relative connection point on section in the interval [0, 1]. Defaults to 1 timepoints: ndarray, dtype=int array of timepoints in simulation at which you want to compute the axial currents. Defaults to None. If not given, the axial currents. Defaults to None. If not given, all simulation timesteps will be included. sec: neuron.Section object current section needed in new NEURON version Returns ------- iseg: dtype=float Axial current in units of (nA) from segment mid point to segment start point. ipar: dtype=float Axial current in units of (nA) from parent segment end point to parent segment mid point. """ # axial resistance between segment mid and parent node seg_ri = self._ri_list[seg_idx] vmem = self.vmem if timepoints is not None: vmem = self.vmem[:, timepoints] vpar = vmem[parent_idx] vseg = vmem[seg_idx] # if segment is the first in its section and it is connected to # top or bottom of parent section, we need to find parent_ri explicitly if bottom_seg and (conn_point == 0 or conn_point == 1): if conn_point == 0: parent_ri = self._ri_list[parent_idx] else: parent_ri = neuron.h.ri(0, sec=sec) if not branch: ri = parent_ri + seg_ri iseg = (vpar - vseg) / ri ipar = iseg else: # if branch, need to compute iseg and ipar separately [sib_idcs] = np.take(children_dict[parentsec.name()], np.where(children_dict[parentsec.name()] != seg_idx)) sibs = [self.get_idx_name(sib_idcs)[i][1] for i in range(len(sib_idcs))] # compute potential in branch point between parent and siblings v_branch_num = vpar / parent_ri + vseg / seg_ri v_branch_denom = 1. / parent_ri + 1. / seg_ri for sib_idx, sib in zip(sib_idcs, sibs): sib_conn_point = connection_dict[sib] if sib_conn_point == conn_point: v_branch_num += vmem[sib_idx] / self._ri_list[sib_idx] v_branch_denom += 1. / self._ri_list[sib_idx] v_branch = v_branch_num / v_branch_denom iseg = (v_branch - vseg) / seg_ri # set ipar=iseg # only fraction of total current into parent is added per # sibling ipar = iseg else: iseg = (vpar - vseg) / seg_ri ipar = iseg return iseg, ipar def distort_geometry(self, factor=0., axis='z', nu=0.0): """ Distorts cellular morphology with a relative factor along a chosen axis preserving Poisson's ratio. A ratio nu=0.5 assumes uncompressible and isotropic media that embeds the cell. A ratio nu=0 will only affect geometry along the chosen axis. A ratio nu=-1 will isometrically scale the neuron geometry along each axis. This method does not affect the underlying cable properties of the cell, only predictions of extracellular measurements (by affecting the relative locations of sources representing the compartments). Parameters ---------- factor: float relative compression/stretching factor of morphology. Default is 0 (no compression/stretching). Positive values implies a compression along the chosen axis. axis: str which axis to apply compression/stretching. Default is "z". nu: float Poisson's ratio. Ratio between axial and transversal compression/stretching. Default is 0. """ assert abs(factor) < 1., 'abs(factor) >= 1, factor must be in <-1, 1>' assert axis in ['x', 'y', 'z'], \ 'axis={} not "x", "y" or "z"'.format(axis) for pos, dir_ in zip(self.somapos, 'xyz'): geometry = np.c_[getattr(self, dir_)[:, 0], getattr(self, dir_)[:, -1]] if dir_ == axis: geometry -= pos geometry *= (1. - factor) geometry += pos else: geometry -= pos geometry *= (1. + factor * nu) geometry += pos setattr(self, dir_, geometry) # recompute length of each segment self._set_length() def _set_length(self): '''callable method to (re)set length attribute''' self.length = np.sqrt(np.diff(self.x, axis=-1)**2 + np.diff(self.y, axis=-1)**2 + np.diff(self.z, axis=-1)**2).flatten() def _set_area(self): '''callable method to (re)set area attribute''' if self.d.ndim == 1: self.area = self.length * np.pi * self.d else: # Surface area of conical frusta # A = pi*(r1+r2)*sqrt((r1-r2)^2 + h^2) self.area = np.pi * self.d.sum(axis=-1) * \ np.sqrt(np.diff(self.d, axis=-1)**2 + self.length**2) def get_multi_current_dipole_moments(self, timepoints=None): ''' Return 3D current dipole moment vector and middle position vector from each axial current in space. Parameters ---------- timepoints: ndarray, dtype=int or None array of timepoints at which you want to compute the current dipole moments. Defaults to None. If not given, all simulation timesteps will be included. Returns ------- multi_dipoles: ndarray, dtype = float Shape (n_axial_currents, 3, n_timepoints) array containing the x-,y-,z-components of the current dipole moment from each axial current in cell, at all timepoints. The number of axial currents, n_axial_currents = (cell.totnsegs-1) * 2 and the number of timepoints, n_timepoints = cell.tvec.size. The current dipole moments are given in units of (nA µm). pos_axial: ndarray, dtype = float Shape (n_axial_currents, 3) array containing the x-, y-, and z-components giving the mid position in space of each multi_dipole in units of (µm). Examples -------- Get all current dipole moments and positions from all axial currents in a single neuron simulation: >>> import LFPy >>> import numpy as np >>> cell = LFPy.Cell('PATH/TO/MORPHOLOGY', extracellular=False) >>> syn = LFPy.Synapse(cell, idx=cell.get_closest_idx(0,0,1000), >>> syntype='ExpSyn', e=0., tau=1., weight=0.001) >>> syn.set_spike_times(np.mgrid[20:100:20]) >>> cell.simulate(rec_vmem=True, rec_imem=False) >>> timepoints = np.array([1,2,3,4]) >>> multi_dipoles, dipole_locs = cell.get_multi_current_dipole_moments( >>> timepoints=timepoints) ''' i_axial, d_axial, pos_axial = self.get_axial_currents_from_vmem( timepoints=timepoints) Ni, Nt = i_axial.shape multi_dipoles = np.zeros((Ni, 3, Nt)) for i in range(Ni): multi_dipoles[i, ] = (i_axial[i][:, np.newaxis] * d_axial[:, i]).T return multi_dipoles, pos_axial
gpl-3.0
citrix-openstack-build/nova
nova/tests/virt/hyperv/test_vmutils.py
8
2546
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock from nova import test from nova.virt.hyperv import vmutils class VMUtilsTestCase(test.NoDBTestCase): """Unit tests for the Hyper-V VMUtils class.""" _FAKE_VM_NAME = 'fake_vm' _FAKE_MEMORY_MB = 2 _FAKE_VM_PATH = "fake_vm_path" def setUp(self): self._vmutils = vmutils.VMUtils() self._vmutils._conn = mock.MagicMock() super(VMUtilsTestCase, self).setUp() def test_enable_vm_metrics_collection(self): self.assertRaises(NotImplementedError, self._vmutils.enable_vm_metrics_collection, self._FAKE_VM_NAME) def _lookup_vm(self): mock_vm = mock.MagicMock() self._vmutils._lookup_vm_check = mock.MagicMock( return_value=mock_vm) mock_vm.path_.return_value = self._FAKE_VM_PATH return mock_vm def test_set_vm_memory_static(self): self._test_set_vm_memory_dynamic(1.0) def test_set_vm_memory_dynamic(self): self._test_set_vm_memory_dynamic(2.0) def _test_set_vm_memory_dynamic(self, dynamic_memory_ratio): mock_vm = self._lookup_vm() mock_s = self._vmutils._conn.Msvm_VirtualSystemSettingData()[0] mock_s.SystemType = 3 mock_vmsetting = mock.MagicMock() mock_vmsetting.associators.return_value = [mock_s] self._vmutils._modify_virt_resource = mock.MagicMock() self._vmutils._set_vm_memory(mock_vm, mock_vmsetting, self._FAKE_MEMORY_MB, dynamic_memory_ratio) self._vmutils._modify_virt_resource.assert_called_with( mock_s, self._FAKE_VM_PATH) if dynamic_memory_ratio > 1: self.assertTrue(mock_s.DynamicMemoryEnabled) else: self.assertFalse(mock_s.DynamicMemoryEnabled)
apache-2.0
diogobaeder/merendeira
tests/supplies/test_models.py
1
1026
from django.test import TestCase from nose.tools import istest from merendeira.supplies.models import Category, Product class CategoryTest(TestCase): @istest def creates_a_basic_instance(self): Category.objects.create(title='Comidas') category = Category.objects.get(pk=1) self.assertEqual(category.title, 'Comidas') self.assertEqual(category.slug, 'comidas') @istest def is_printable_by_title(self): category = Category.objects.create(title='Comidas') self.assertEqual(str(category), 'Comidas') class ProductTest(TestCase): def create_category(self): return Category.objects.create(title='Comidas') @istest def creates_a_basic_instance(self): category = self.create_category() Product.objects.create( title='Tomate', category=category, ) product = Product.objects.get(pk=1) self.assertEqual(product.title, 'Tomate') self.assertEqual(product.slug, 'tomate')
bsd-2-clause
kalahbrown/HueBigSQL
desktop/core/ext-py/Django-1.6.10/django/contrib/gis/tests/test_geoforms.py
97
13891
from django.forms import ValidationError from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.tests.utils import HAS_SPATIALREFSYS from django.test import SimpleTestCase from django.utils import six from django.utils.html import escape from django.utils.unittest import skipUnless if HAS_SPATIALREFSYS: from django.contrib.gis import forms from django.contrib.gis.geos import GEOSGeometry @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "GeometryFieldTest needs gdal support and a spatial database") class GeometryFieldTest(SimpleTestCase): def test_init(self): "Testing GeometryField initialization with defaults." fld = forms.GeometryField() for bad_default in ('blah', 3, 'FoO', None, 0): self.assertRaises(ValidationError, fld.clean, bad_default) def test_srid(self): "Testing GeometryField with a SRID set." # Input that doesn't specify the SRID is assumed to be in the SRID # of the input field. fld = forms.GeometryField(srid=4326) geom = fld.clean('POINT(5 23)') self.assertEqual(4326, geom.srid) # Making the field in a different SRID from that of the geometry, and # asserting it transforms. fld = forms.GeometryField(srid=32140) tol = 0.0000001 xform_geom = GEOSGeometry('POINT (951640.547328465 4219369.26171664)', srid=32140) # The cleaned geometry should be transformed to 32140. cleaned_geom = fld.clean('SRID=4326;POINT (-95.363151 29.763374)') self.assertTrue(xform_geom.equals_exact(cleaned_geom, tol)) def test_null(self): "Testing GeometryField's handling of null (None) geometries." # Form fields, by default, are required (`required=True`) fld = forms.GeometryField() with six.assertRaisesRegex(self, forms.ValidationError, "No geometry value provided."): fld.clean(None) # This will clean None as a geometry (See #10660). fld = forms.GeometryField(required=False) self.assertIsNone(fld.clean(None)) def test_geom_type(self): "Testing GeometryField's handling of different geometry types." # By default, all geometry types are allowed. fld = forms.GeometryField() for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.clean(wkt)) pnt_fld = forms.GeometryField(geom_type='POINT') self.assertEqual(GEOSGeometry('POINT(5 23)'), pnt_fld.clean('POINT(5 23)')) # a WKT for any other geom_type will be properly transformed by `to_python` self.assertEqual(GEOSGeometry('LINESTRING(0 0, 1 1)'), pnt_fld.to_python('LINESTRING(0 0, 1 1)')) # but rejected by `clean` self.assertRaises(forms.ValidationError, pnt_fld.clean, 'LINESTRING(0 0, 1 1)') def test_to_python(self): """ Testing to_python returns a correct GEOSGeometry object or a ValidationError """ fld = forms.GeometryField() # to_python returns the same GEOSGeometry for a WKT for wkt in ('POINT(5 23)', 'MULTIPOLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'LINESTRING(0 0, 1 1)'): self.assertEqual(GEOSGeometry(wkt), fld.to_python(wkt)) # but raises a ValidationError for any other string for wkt in ('POINT(5)', 'MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))', 'BLAH(0 0, 1 1)'): self.assertRaises(forms.ValidationError, fld.to_python, wkt) def test_field_with_text_widget(self): class PointForm(forms.Form): pt = forms.PointField(srid=4326, widget=forms.TextInput) form = PointForm() cleaned_pt = form.fields['pt'].clean('POINT(5 23)') self.assertEqual(cleaned_pt, GEOSGeometry('POINT(5 23)')) self.assertEqual(4326, cleaned_pt.srid) point = GEOSGeometry('SRID=4326;POINT(5 23)') form = PointForm(data={'pt': 'POINT(5 23)'}, initial={'pt': point}) self.assertFalse(form.has_changed()) @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "SpecializedFieldTest needs gdal support and a spatial database") class SpecializedFieldTest(SimpleTestCase): def setUp(self): self.geometries = { 'point': GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)"), 'multipoint': GEOSGeometry("SRID=4326;MULTIPOINT(" "(13.18634033203125 14.504356384277344)," "(13.207969665527 14.490966796875)," "(13.177070617675 14.454917907714))"), 'linestring': GEOSGeometry("SRID=4326;LINESTRING(" "-8.26171875 -0.52734375," "-7.734375 4.21875," "6.85546875 3.779296875," "5.44921875 -3.515625)"), 'multilinestring': GEOSGeometry("SRID=4326;MULTILINESTRING(" "(-16.435546875 -2.98828125," "-17.2265625 2.98828125," "-0.703125 3.515625," "-1.494140625 -3.33984375)," "(-8.0859375 -5.9765625," "8.525390625 -8.7890625," "12.392578125 -0.87890625," "10.01953125 7.646484375))"), 'polygon': GEOSGeometry("SRID=4326;POLYGON(" "(-1.669921875 6.240234375," "-3.8671875 -0.615234375," "5.9765625 -3.955078125," "18.193359375 3.955078125," "9.84375 9.4921875," "-1.669921875 6.240234375))"), 'multipolygon': GEOSGeometry("SRID=4326;MULTIPOLYGON(" "((-17.578125 13.095703125," "-17.2265625 10.8984375," "-13.974609375 10.1953125," "-13.359375 12.744140625," "-15.732421875 13.7109375," "-17.578125 13.095703125))," "((-8.525390625 5.537109375," "-8.876953125 2.548828125," "-5.888671875 1.93359375," "-5.09765625 4.21875," "-6.064453125 6.240234375," "-8.525390625 5.537109375)))"), 'geometrycollection': GEOSGeometry("SRID=4326;GEOMETRYCOLLECTION(" "POINT(5.625 -0.263671875)," "POINT(6.767578125 -3.603515625)," "POINT(8.525390625 0.087890625)," "POINT(8.0859375 -2.13134765625)," "LINESTRING(" "6.273193359375 -1.175537109375," "5.77880859375 -1.812744140625," "7.27294921875 -2.230224609375," "7.657470703125 -1.25244140625))"), } def assertMapWidget(self, form_instance): """ Make sure the MapWidget js is passed in the form media and a MapWidget is actually created """ self.assertTrue(form_instance.is_valid()) rendered = form_instance.as_p() self.assertIn('new MapWidget(options);', rendered) self.assertIn('gis/js/OLMapWidget.js', str(form_instance.media)) def assertTextarea(self, geom, rendered): """Makes sure the wkt and a textarea are in the content""" self.assertIn('<textarea ', rendered) self.assertIn('required', rendered) self.assertIn(geom.wkt, rendered) def test_pointfield(self): class PointForm(forms.Form): p = forms.PointField() geom = self.geometries['point'] form = PointForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PointForm().is_valid()) invalid = PointForm(data={'p': 'some invalid geom'}) self.assertFalse(invalid.is_valid()) self.assertTrue('Invalid geometry value' in str(invalid.errors)) for invalid in [geom for key, geom in self.geometries.items() if key!='point']: self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid()) def test_multipointfield(self): class PointForm(forms.Form): p = forms.MultiPointField() geom = self.geometries['multipoint'] form = PointForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PointForm().is_valid()) for invalid in [geom for key, geom in self.geometries.items() if key!='multipoint']: self.assertFalse(PointForm(data={'p': invalid.wkt}).is_valid()) def test_linestringfield(self): class LineStringForm(forms.Form): l = forms.LineStringField() geom = self.geometries['linestring'] form = LineStringForm(data={'l': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(LineStringForm().is_valid()) for invalid in [geom for key, geom in self.geometries.items() if key!='linestring']: self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid()) def test_multilinestringfield(self): class LineStringForm(forms.Form): l = forms.MultiLineStringField() geom = self.geometries['multilinestring'] form = LineStringForm(data={'l': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(LineStringForm().is_valid()) for invalid in [geom for key, geom in self.geometries.items() if key!='multilinestring']: self.assertFalse(LineStringForm(data={'p': invalid.wkt}).is_valid()) def test_polygonfield(self): class PolygonForm(forms.Form): p = forms.PolygonField() geom = self.geometries['polygon'] form = PolygonForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PolygonForm().is_valid()) for invalid in [geom for key, geom in self.geometries.items() if key!='polygon']: self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid()) def test_multipolygonfield(self): class PolygonForm(forms.Form): p = forms.MultiPolygonField() geom = self.geometries['multipolygon'] form = PolygonForm(data={'p': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(PolygonForm().is_valid()) for invalid in [geom for key, geom in self.geometries.items() if key!='multipolygon']: self.assertFalse(PolygonForm(data={'p': invalid.wkt}).is_valid()) def test_geometrycollectionfield(self): class GeometryForm(forms.Form): g = forms.GeometryCollectionField() geom = self.geometries['geometrycollection'] form = GeometryForm(data={'g': geom}) self.assertTextarea(geom, form.as_p()) self.assertMapWidget(form) self.assertFalse(GeometryForm().is_valid()) for invalid in [geom for key, geom in self.geometries.items() if key!='geometrycollection']: self.assertFalse(GeometryForm(data={'g': invalid.wkt}).is_valid()) def test_osm_widget(self): class PointForm(forms.Form): p = forms.PointField(widget=forms.OSMWidget) geom = self.geometries['point'] form = PointForm(data={'p': geom}) rendered = form.as_p() self.assertIn("OpenStreetMap (Mapnik)", rendered) self.assertIn("id: 'id_p',", rendered) @skipUnless(HAS_GDAL and HAS_SPATIALREFSYS, "CustomGeometryWidgetTest needs gdal support and a spatial database") class CustomGeometryWidgetTest(SimpleTestCase): def test_custom_serialization_widget(self): class CustomGeometryWidget(forms.BaseGeometryWidget): template_name = 'gis/openlayers.html' deserialize_called = 0 def serialize(self, value): return value.json if value else '' def deserialize(self, value): self.deserialize_called += 1 return GEOSGeometry(value) class PointForm(forms.Form): p = forms.PointField(widget=CustomGeometryWidget) point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)") form = PointForm(data={'p': point}) self.assertIn(escape(point.json), form.as_p()) CustomGeometryWidget.called = 0 widget = form.fields['p'].widget # Force deserialize use due to a string value self.assertIn(escape(point.json), widget.render('p', point.json)) self.assertEqual(widget.deserialize_called, 1) form = PointForm(data={'p': point.json}) self.assertTrue(form.is_valid()) # Ensure that resulting geometry has srid set self.assertEqual(form.cleaned_data['p'].srid, 4326)
apache-2.0
jspan/Open-Knesset
auxiliary/migrations/0013_auto__add_tagkeyphrase.py
14
7851
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'TagKeyphrase' db.create_table(u'auxiliary_tagkeyphrase', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('tag', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['tagging.Tag'])), ('phrase', self.gf('django.db.models.fields.CharField')(max_length=100)), )) db.send_create_signal(u'auxiliary', ['TagKeyphrase']) def backwards(self, orm): # Deleting model 'TagKeyphrase' db.delete_table(u'auxiliary_tagkeyphrase') models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'auxiliary.feedback': { 'Meta': {'object_name': 'Feedback'}, 'content': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip_address': ('django.db.models.fields.IPAddressField', [], {'max_length': '15', 'null': 'True', 'blank': 'True'}), 'suggested_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}), 'suggested_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'feedback'", 'null': 'True', 'to': u"orm['auth.User']"}), 'url': ('django.db.models.fields.TextField', [], {}), 'user_agent': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) }, u'auxiliary.tagkeyphrase': { 'Meta': {'object_name': 'TagKeyphrase'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'phrase': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['tagging.Tag']"}) }, u'auxiliary.tagsuggestion': { 'Meta': {'object_name': 'TagSuggestion'}, 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.TextField', [], {'unique': 'True'}), 'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'suggested_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'tagsuggestion'", 'null': 'True', 'to': u"orm['auth.User']"}) }, u'auxiliary.tagsynonym': { 'Meta': {'object_name': 'TagSynonym'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'synonym_tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'synonym_synonym_tag'", 'unique': 'True', 'to': u"orm['tagging.Tag']"}), 'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'synonym_proper_tag'", 'to': u"orm['tagging.Tag']"}) }, u'auxiliary.tidbit': { 'Meta': {'object_name': 'Tidbit'}, 'button_link': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'button_text': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content': ('tinymce.models.HTMLField', [], {}), 'icon': ('django.db.models.fields.CharField', [], {'max_length': '15'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'ordering': ('django.db.models.fields.IntegerField', [], {'default': '20', 'db_index': 'True'}), 'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'suggested_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'tidbits'", 'null': 'True', 'to': u"orm['auth.User']"}), 'title': ('django.db.models.fields.CharField', [], {'default': "u'Did you know ?'", 'max_length': '40'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'tagging.tag': { 'Meta': {'ordering': "('name',)", 'object_name': 'Tag'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}) } } complete_apps = ['auxiliary']
bsd-3-clause
moonboots/tensorflow
tensorflow/python/kernel_tests/unpack_op_test.py
15
2525
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for Unpack Op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf class UnpackOpTest(tf.test.TestCase): def testSimple(self): np.random.seed(7) for use_gpu in False, True: with self.test_session(use_gpu=use_gpu): for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2): data = np.random.randn(*shape) # Convert data to a single tensorflow tensor x = tf.constant(data) # Unpack into a list of tensors cs = tf.unpack(x, num=shape[0]) self.assertEqual(type(cs), list) self.assertEqual(len(cs), shape[0]) cs = [c.eval() for c in cs] self.assertAllEqual(cs, data) def testGradients(self): for use_gpu in False, True: for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2): data = np.random.randn(*shape) shapes = [shape[1:]] * shape[0] for i in xrange(shape[0]): with self.test_session(use_gpu=use_gpu): x = tf.constant(data) cs = tf.unpack(x, num=shape[0]) err = tf.test.compute_gradient_error(x, shape, cs[i], shapes[i]) self.assertLess(err, 1e-6) def testInferNum(self): with self.test_session(): for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2): x = tf.placeholder(np.float32, shape=shape) cs = tf.unpack(x) self.assertEqual(type(cs), list) self.assertEqual(len(cs), shape[0]) def testCannotInferNum(self): x = tf.placeholder(np.float32) with self.assertRaisesRegexp( ValueError, r'Cannot infer num from shape <unknown>'): tf.unpack(x) if __name__ == '__main__': tf.test.main()
apache-2.0
chinmaygarde/mojo
sky/tools/webkitpy/common/system/systemhost.py
13
2475
# Copyright (c) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os import platform import sys from webkitpy.common.system import environment, executive, filesystem, platforminfo, user, workspace class SystemHost(object): def __init__(self): self.executable = sys.executable self.executive = executive.Executive() self.filesystem = filesystem.FileSystem() self.user = user.User() self.platform = platforminfo.PlatformInfo(sys, platform, self.executive) self.workspace = workspace.Workspace(self.filesystem, self.executive) def copy_current_environment(self): return environment.Environment(os.environ.copy()) def print_(self, *args, **kwargs): sep = kwargs.get('sep', ' ') end = kwargs.get('end', '\n') file = kwargs.get('file', None) stderr = kwargs.get('stderr', False) file = file or (sys.stderr if stderr else sys.stdout) file.write(sep.join([str(arg) for arg in args]) + end)
bsd-3-clause
75651/kbengine_cloud
kbe/src/lib/python/Lib/unittest/test/testmock/testwith.py
80
8873
import unittest from warnings import catch_warnings from unittest.test.testmock.support import is_instance from unittest.mock import MagicMock, Mock, patch, sentinel, mock_open, call something = sentinel.Something something_else = sentinel.SomethingElse class WithTest(unittest.TestCase): def test_with_statement(self): with patch('%s.something' % __name__, sentinel.Something2): self.assertEqual(something, sentinel.Something2, "unpatched") self.assertEqual(something, sentinel.Something) def test_with_statement_exception(self): try: with patch('%s.something' % __name__, sentinel.Something2): self.assertEqual(something, sentinel.Something2, "unpatched") raise Exception('pow') except Exception: pass else: self.fail("patch swallowed exception") self.assertEqual(something, sentinel.Something) def test_with_statement_as(self): with patch('%s.something' % __name__) as mock_something: self.assertEqual(something, mock_something, "unpatched") self.assertTrue(is_instance(mock_something, MagicMock), "patching wrong type") self.assertEqual(something, sentinel.Something) def test_patch_object_with_statement(self): class Foo(object): something = 'foo' original = Foo.something with patch.object(Foo, 'something'): self.assertNotEqual(Foo.something, original, "unpatched") self.assertEqual(Foo.something, original) def test_with_statement_nested(self): with catch_warnings(record=True): with patch('%s.something' % __name__) as mock_something, patch('%s.something_else' % __name__) as mock_something_else: self.assertEqual(something, mock_something, "unpatched") self.assertEqual(something_else, mock_something_else, "unpatched") self.assertEqual(something, sentinel.Something) self.assertEqual(something_else, sentinel.SomethingElse) def test_with_statement_specified(self): with patch('%s.something' % __name__, sentinel.Patched) as mock_something: self.assertEqual(something, mock_something, "unpatched") self.assertEqual(mock_something, sentinel.Patched, "wrong patch") self.assertEqual(something, sentinel.Something) def testContextManagerMocking(self): mock = Mock() mock.__enter__ = Mock() mock.__exit__ = Mock() mock.__exit__.return_value = False with mock as m: self.assertEqual(m, mock.__enter__.return_value) mock.__enter__.assert_called_with() mock.__exit__.assert_called_with(None, None, None) def test_context_manager_with_magic_mock(self): mock = MagicMock() with self.assertRaises(TypeError): with mock: 'foo' + 3 mock.__enter__.assert_called_with() self.assertTrue(mock.__exit__.called) def test_with_statement_same_attribute(self): with patch('%s.something' % __name__, sentinel.Patched) as mock_something: self.assertEqual(something, mock_something, "unpatched") with patch('%s.something' % __name__) as mock_again: self.assertEqual(something, mock_again, "unpatched") self.assertEqual(something, mock_something, "restored with wrong instance") self.assertEqual(something, sentinel.Something, "not restored") def test_with_statement_imbricated(self): with patch('%s.something' % __name__) as mock_something: self.assertEqual(something, mock_something, "unpatched") with patch('%s.something_else' % __name__) as mock_something_else: self.assertEqual(something_else, mock_something_else, "unpatched") self.assertEqual(something, sentinel.Something) self.assertEqual(something_else, sentinel.SomethingElse) def test_dict_context_manager(self): foo = {} with patch.dict(foo, {'a': 'b'}): self.assertEqual(foo, {'a': 'b'}) self.assertEqual(foo, {}) with self.assertRaises(NameError): with patch.dict(foo, {'a': 'b'}): self.assertEqual(foo, {'a': 'b'}) raise NameError('Konrad') self.assertEqual(foo, {}) class TestMockOpen(unittest.TestCase): def test_mock_open(self): mock = mock_open() with patch('%s.open' % __name__, mock, create=True) as patched: self.assertIs(patched, mock) open('foo') mock.assert_called_once_with('foo') def test_mock_open_context_manager(self): mock = mock_open() handle = mock.return_value with patch('%s.open' % __name__, mock, create=True): with open('foo') as f: f.read() expected_calls = [call('foo'), call().__enter__(), call().read(), call().__exit__(None, None, None)] self.assertEqual(mock.mock_calls, expected_calls) self.assertIs(f, handle) def test_explicit_mock(self): mock = MagicMock() mock_open(mock) with patch('%s.open' % __name__, mock, create=True) as patched: self.assertIs(patched, mock) open('foo') mock.assert_called_once_with('foo') def test_read_data(self): mock = mock_open(read_data='foo') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.read() self.assertEqual(result, 'foo') def test_readline_data(self): # Check that readline will return all the lines from the fake file mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') line1 = h.readline() line2 = h.readline() line3 = h.readline() self.assertEqual(line1, 'foo\n') self.assertEqual(line2, 'bar\n') self.assertEqual(line3, 'baz\n') # Check that we properly emulate a file that doesn't end in a newline mock = mock_open(read_data='foo') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.readline() self.assertEqual(result, 'foo') def test_readlines_data(self): # Test that emulating a file that ends in a newline character works mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.readlines() self.assertEqual(result, ['foo\n', 'bar\n', 'baz\n']) # Test that files without a final newline will also be correctly # emulated mock = mock_open(read_data='foo\nbar\nbaz') with patch('%s.open' % __name__, mock, create=True): h = open('bar') result = h.readlines() self.assertEqual(result, ['foo\n', 'bar\n', 'baz']) def test_mock_open_read_with_argument(self): # At one point calling read with an argument was broken # for mocks returned by mock_open some_data = 'foo\nbar\nbaz' mock = mock_open(read_data=some_data) self.assertEqual(mock().read(10), some_data) def test_interleaved_reads(self): # Test that calling read, readline, and readlines pulls data # sequentially from the data we preload with mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') line1 = h.readline() rest = h.readlines() self.assertEqual(line1, 'foo\n') self.assertEqual(rest, ['bar\n', 'baz\n']) mock = mock_open(read_data='foo\nbar\nbaz\n') with patch('%s.open' % __name__, mock, create=True): h = open('bar') line1 = h.readline() rest = h.read() self.assertEqual(line1, 'foo\n') self.assertEqual(rest, 'bar\nbaz\n') def test_overriding_return_values(self): mock = mock_open(read_data='foo') handle = mock() handle.read.return_value = 'bar' handle.readline.return_value = 'bar' handle.readlines.return_value = ['bar'] self.assertEqual(handle.read(), 'bar') self.assertEqual(handle.readline(), 'bar') self.assertEqual(handle.readlines(), ['bar']) # call repeatedly to check that a StopIteration is not propagated self.assertEqual(handle.readline(), 'bar') self.assertEqual(handle.readline(), 'bar') if __name__ == '__main__': unittest.main()
lgpl-3.0
ikmaak/Printrun
printrun/utils.py
19
8549
# This file is part of the Printrun suite. # # Printrun is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Printrun is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Printrun. If not, see <http://www.gnu.org/licenses/>. import os import sys import re import gettext import datetime import subprocess import shlex import logging # Set up Internationalization using gettext # searching for installed locales on /usr/share; uses relative folder if not # found (windows) def install_locale(domain): if os.path.exists('/usr/share/pronterface/locale'): gettext.install(domain, '/usr/share/pronterface/locale', unicode = 1) elif os.path.exists('/usr/local/share/pronterface/locale'): gettext.install(domain, '/usr/local/share/pronterface/locale', unicode = 1) else: gettext.install(domain, './locale', unicode = 1) class LogFormatter(logging.Formatter): def __init__(self, format_default, format_info): super(LogFormatter, self).__init__(format_info) self.format_default = format_default self.format_info = format_info def format(self, record): if record.levelno == logging.INFO: self._fmt = self.format_info else: self._fmt = self.format_default return super(LogFormatter, self).format(record) def setup_logging(out, filepath = None, reset_handlers = False): logger = logging.getLogger() logger.setLevel(logging.INFO) if reset_handlers: logger.handlers = [] formatter = LogFormatter("[%(levelname)s] %(message)s", "%(message)s") logging_handler = logging.StreamHandler(out) logging_handler.setFormatter(formatter) logger.addHandler(logging_handler) if filepath: if os.path.isdir(filepath): filepath = os.path.join(filepath, "printrun.log") formatter = LogFormatter("%(asctime)s - [%(levelname)s] %(message)s", "%(asctime)s - %(message)s") logging_handler = logging.FileHandler(filepath) logging_handler.setFormatter(formatter) logger.addHandler(logging_handler) def iconfile(filename): if hasattr(sys, "frozen") and sys.frozen == "windows_exe": return sys.executable else: return pixmapfile(filename) def imagefile(filename): for prefix in ['/usr/local/share/pronterface/images', '/usr/share/pronterface/images']: candidate = os.path.join(prefix, filename) if os.path.exists(candidate): return candidate local_candidate = os.path.join(os.path.dirname(sys.argv[0]), "images", filename) if os.path.exists(local_candidate): return local_candidate else: return os.path.join("images", filename) def lookup_file(filename, prefixes): local_candidate = os.path.join(os.path.dirname(sys.argv[0]), filename) if os.path.exists(local_candidate): return local_candidate for prefix in prefixes: candidate = os.path.join(prefix, filename) if os.path.exists(candidate): return candidate return filename def pixmapfile(filename): return lookup_file(filename, ['/usr/local/share/pixmaps', '/usr/share/pixmaps']) def sharedfile(filename): return lookup_file(filename, ['/usr/local/share/pronterface', '/usr/share/pronterface']) def configfile(filename): return lookup_file(filename, [os.path.expanduser("~/.printrun/"), ]) def decode_utf8(s): try: s = s.decode("utf-8") except: pass return s def format_time(timestamp): return datetime.datetime.fromtimestamp(timestamp).strftime("%H:%M:%S") def format_duration(delta): return str(datetime.timedelta(seconds = int(delta))) def prepare_command(command, replaces = None): command = shlex.split(command.replace("\\", "\\\\").encode()) if replaces: replaces["$python"] = sys.executable for pattern, rep in replaces.items(): command = [bit.replace(pattern, rep) for bit in command] command = [bit.encode() for bit in command] return command def run_command(command, replaces = None, stdout = subprocess.STDOUT, stderr = subprocess.STDOUT, blocking = False): command = prepare_command(command, replaces) if blocking: return subprocess.call(command) else: return subprocess.Popen(command, stderr = stderr, stdout = stdout) def get_command_output(command, replaces): p = run_command(command, replaces, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, blocking = False) return p.stdout.read() def dosify(name): return os.path.split(name)[1].split(".")[0][:8] + ".g" class RemainingTimeEstimator(object): drift = None gcode = None def __init__(self, gcode): self.drift = 1 self.previous_layers_estimate = 0 self.current_layer_estimate = 0 self.current_layer_lines = 0 self.gcode = gcode self.remaining_layers_estimate = sum(layer.duration for layer in gcode.all_layers) if len(gcode) > 0: self.update_layer(0, 0) def update_layer(self, layer, printtime): self.previous_layers_estimate += self.current_layer_estimate if self.previous_layers_estimate > 1. and printtime > 1.: self.drift = printtime / self.previous_layers_estimate self.current_layer_estimate = self.gcode.all_layers[layer].duration self.current_layer_lines = len(self.gcode.all_layers[layer]) self.remaining_layers_estimate -= self.current_layer_estimate self.last_idx = -1 self.last_estimate = None def __call__(self, idx, printtime): if not self.current_layer_lines: return (0, 0) if idx == self.last_idx: return self.last_estimate layer, line = self.gcode.idxs(idx) layer_progress = (1 - (float(line + 1) / self.current_layer_lines)) remaining = layer_progress * self.current_layer_estimate + self.remaining_layers_estimate estimate = self.drift * remaining total = estimate + printtime self.last_idx = idx self.last_estimate = (estimate, total) return self.last_estimate def parse_build_dimensions(bdim): # a string containing up to six numbers delimited by almost anything # first 0-3 numbers specify the build volume, no sign, always positive # remaining 0-3 numbers specify the coordinates of the "southwest" corner of the build platform # "XXX,YYY" # "XXXxYYY+xxx-yyy" # "XXX,YYY,ZZZ+xxx+yyy-zzz" # etc bdl = re.findall("([-+]?[0-9]*\.?[0-9]*)", bdim) defaults = [200, 200, 100, 0, 0, 0, 0, 0, 0] bdl = filter(None, bdl) bdl_float = [float(value) if value else defaults[i] for i, value in enumerate(bdl)] if len(bdl_float) < len(defaults): bdl_float += [defaults[i] for i in range(len(bdl_float), len(defaults))] for i in range(3): # Check for nonpositive dimensions for build volume if bdl_float[i] <= 0: bdl_float[i] = 1 return bdl_float def get_home_pos(build_dimensions): return build_dimensions[6:9] if len(build_dimensions) >= 9 else None def hexcolor_to_float(color, components): color = color[1:] numel = len(color) ndigits = numel / components div = 16 ** ndigits - 1 return tuple(round(float(int(color[i:i + ndigits], 16)) / div, 2) for i in range(0, numel, ndigits)) def check_rgb_color(color): if len(color[1:]) % 3 != 0: ex = ValueError(_("Color must be specified as #RGB")) ex.from_validator = True raise ex def check_rgba_color(color): if len(color[1:]) % 4 != 0: ex = ValueError(_("Color must be specified as #RGBA")) ex.from_validator = True raise ex tempreport_exp = re.compile("([TB]\d*):([-+]?\d*\.?\d*)(?: ?\/)?([-+]?\d*\.?\d*)") def parse_temperature_report(report): matches = tempreport_exp.findall(report) return dict((m[0], (m[1], m[2])) for m in matches)
gpl-3.0
evernym/plenum
common/serializers/json_serializer.py
2
2130
# Consider using bson or ubjson for serializing json import base64 from typing import Dict from common.serializers.mapping_serializer import MappingSerializer try: import ujson as json from ujson import encode as uencode # Older versions of ujson's encode do not support `sort_keys`, if that # is the case default to using json uencode({'xx': '123', 'aa': 90}, sort_keys=True) class UJsonEncoder: @staticmethod def encode(o): if isinstance(o, (bytes, bytearray)): return '"{}"'.format(base64.b64encode(o).decode("utf-8")) else: return uencode(o, sort_keys=True) JsonEncoder = UJsonEncoder() except (ImportError, TypeError): import json class OrderedJsonEncoder(json.JSONEncoder): def __init__(self, *args, **kwargs): kwargs['ensure_ascii'] = False kwargs['sort_keys'] = True kwargs['separators'] = (',', ':') super().__init__(*args, **kwargs) def encode(self, o): if isinstance(o, (bytes, bytearray)): return '"{}"'.format(base64.b64encode(o).decode("utf-8")) else: return super().encode(o) JsonEncoder = OrderedJsonEncoder() class JsonSerializer(MappingSerializer): """ Class to convert a mapping to json with keys ordered in lexicographical order """ @staticmethod def dumps(data, toBytes=True): encoded = JsonEncoder.encode(data) if toBytes: encoded = encoded.encode() return encoded @staticmethod def loads(data): if isinstance(data, (bytes, bytearray)): data = data.decode() return json.loads(data) # The `fields` argument is kept to conform to the interface, its not # need in this method def serialize(self, data: Dict, fields=None, toBytes=True): return self.dumps(data, toBytes) # The `fields` argument is kept to conform to the interface, its not # need in this method def deserialize(self, data, fields=None): return self.loads(data)
apache-2.0
marksherman/appinventor-sources
appinventor/misc/i18n/i18n.py
8
10775
#!/usr/bin/env python # -*- mode: python; coding: utf-8; -*- # Copyright © 2019 MIT, All rights reserved. # Released under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 """ Internationalization helper tool for MIT App Inventor. This utility provides two commands, combine and split, to work with the Java properties and JavaScript files needed to internationalize the App Inventor web editor. The combine command takes the OdeMessages_default.properties file generated by GWT and the English messages file for blocklyeditor and combines them into a single .properties file that can be imported into translation services, such as Google Translate Toolkit. """ from __future__ import print_function import argparse import os import os.path import re __author__ = 'Evan W. Patton (ewpatton@mit.edu)' file_path = os.path.realpath(__file__) js_to_prop = os.path.join(os.path.dirname(file_path), 'js_to_prop.js') appinventor_dir = os.path.normpath(os.path.join(os.path.dirname(file_path), '../../')) class CombineAction(argparse.Action): def __init__(self, option_strings, dest, nargs=None, **kwargs): if nargs is not None: raise ValueError('nargs not allowed') super(CombineAction, self).__init__(option_strings, dest, **kwargs) def __call__(self, parser, namespace, values, option_strings=None): pass blockly_header = """// -*- mode: javascript; js-indent-level: 2; -*- // Copyright 2018-2019 Massachusetts Institute of Technology. All rights reserved. // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 'use strict'; goog.provide('AI.Blockly.Msg.%(lang)s'); goog.require('Blockly.Msg.%(lang)s'); Blockly.Msg.%(lang)s.switch_language_to_%(lang_name)s = { // Switch language to %(lang_name)s. category: '', helpUrl: '', init: function() { Blockly.Msg.%(lang)s.switch_blockly_language_to_%(lang)s.init(); """ blockly_footer = """ } }; """ paletteItems = { 'userInterfaceComponentPallette', 'layoutComponentPallette', 'mediaComponentPallette', 'drawingAndAnimationComponentPallette', 'mapsComponentPallette', 'sensorComponentPallette', 'socialComponentPallette', 'storageComponentPallette', 'connectivityComponentPallette', 'legoMindstormsComponentPallette', 'experimentalComponentPallette', 'extensionComponentPallette' } def js_stringify(text): return "'" + text.replace("''", "'").replace("'", "\\'").replace("\n", "\\n").replace("\r", "\\r").replace("\\:", ":").replace("\\=", "=") + "'" def split(args): if args.lang is None: raise ValueError('No --lang specified for splitting file') if args.lang_name is None: raise ValueError('No --lang_name specified for splitting file') appengine_file = os.path.join(appinventor_dir, 'appengine', 'src', 'com', 'google', 'appinventor', 'client', 'OdeMessages_%s.properties' % args.lang[0]) blockly_dir = os.path.join(appinventor_dir, 'blocklyeditor', 'src', 'msg', args.lang[0].lower()) if not os.path.isdir(blockly_dir): os.mkdir(blockly_dir) blockly_file = os.path.join(blockly_dir, '_messages.js') with open(args.source) as source: with open(appengine_file, 'w+') as ode_output: with open(blockly_file, 'w+') as blockly_output: blockly_output.write(blockly_header % {'lang': args.lang[0], 'lang_name': args.lang_name[0]}) description = None for line in source: if len(line) <= 2: pass elif line[0] == '#': if description is not None: description += line else: description = line elif line.startswith('appengine.switchTo') or line.startswith('appengine.SwitchTo'): pass elif line.startswith('appengine.'): if description is not None: ode_output.write(description) description = None line = line[len('appengine.'):] parts = [part.strip() for part in line.split(' = ', 1)] ode_output.write(parts[0]) ode_output.write(' = ') if parts[0].endswith('Params') or parts[0].endswith('Properties') or \ parts[0].endswith('Methods') or parts[0].endswith('Events') or \ (parts[0].endswith('ComponentPallette') and not parts[0].endswith('HelpStringComponentPallette') and not parts[0] in paletteItems): parts[1] = ''.join(parts[1].split()) ode_output.write(parts[1].replace("'", "''")) ode_output.write('\n\n') else: parts = [part.strip() for part in line[len('blockseditor.'):].split('=', 1)] blockly_output.write(' Blockly.Msg.') blockly_output.write(parts[0]) blockly_output.write(' = ') blockly_output.write(js_stringify(parts[1])) blockly_output.write(';\n') blockly_output.write(blockly_footer) def propescape(s): return s.replace('\\\\', '\\').replace('\\\'', '\'').replace('\\\"', '\"').replace('\'', '\'\'').replace(':', '\\:').replace('=', '\\=') def read_block_translations(lang_code): linere = re.compile(r"(Blockly\.Msg\.[A-Z_]+)\s*=\s*?[\"\'\[](.*)[\"\'\]];") continuation = re.compile(r'\s*\+?\s*(?:\"|\')?(.*)?(?:\"|\')\s*\+?') with open(os.path.join(appinventor_dir, 'blocklyeditor', 'src', 'msg', lang_code, '_messages.js')) as js: comment = None items = [] full_line = '' is_block_comment = False is_line_continuation = False for line in js: line = line.strip() if line == '': continue if line.startswith(r'//'): comment = line[3:] continue if is_block_comment: full_line += line if line.endswith(r'*/'): comment = full_line is_block_comment = False full_line = '' continue if line.startswith(r'/*'): full_line = line is_block_comment = True continue if line.endswith('{'): full_line = '' continue if line.startswith('+') or line.endswith('+'): line = continuation.match(line).group(1) is_line_continuation = True elif is_line_continuation: line = line[1:] is_line_continuation = False full_line += line if full_line.endswith(';'): match = linere.match(full_line) if match is not None: items.append('blockseditor.%s = %s' % (match.group(1), propescape(match.group(2)))) if comment: items.append('# Description: %s' % comment) comment = None full_line = '' return '\n'.join(items) + '\n' def combine(args): if args.lang is None: javaprops = os.path.join(appinventor_dir, 'appengine', 'build', 'extra', 'ode', 'com.google.appinventor.client.OdeMessages_default.properties') lang_code = 'en' else: lang_code = args.lang[0] javaprops = os.path.join(appinventor_dir, 'appengine', 'build', 'extra', 'ode', 'com.google.appinventor.client.OdeMessages_%s.properties' % lang_code) blockprops = read_block_translations(lang_code.lower()) # subprocess.check_output(['node', js_to_prop], text=True, encoding='utf8') with open(os.path.join(appinventor_dir, 'misc', 'i18n', 'translation_template_%s.properties' % lang_code), 'w+', encoding='utf8') as out: out.write('# Frontend definitions\n') with open(javaprops, 'rt', encoding='utf8') as props: lastline = '' for line in props: if lastline.endswith(r'\n') or line.startswith('#') or line.strip() == '': out.write(line) else: out.write('appengine.') out.write(line) out.write('\n# Blocks editor definitions\n') out.write(blockprops) out.close() from xml.etree import ElementTree as et def tmx_merge(args): if args.dest is None: raise ValueError('No --dest specified for splitting file') tmx_tree = None for sfile in args.source_files: data = et.parse(sfile).getroot() if tmx_tree is None: tmx_tree = data else: for tu in data.iter('tu'): insertion_point = tmx_tree.find("./body/tu/[@tuid='%s']" % tu.attrib["tuid"]) if insertion_point is not None: for child in tu: insertion_point.append(child) if tmx_tree is not None: with open(args.dest[0], 'w+') as ofile: ofile.write(et.tostring(tmx_tree, encoding='utf8').decode('utf8')) else: raise ValueError('No output') def parse_args(): parser = argparse.ArgumentParser(description='App Inventor internationalization toolkit') subparsers = parser.add_subparsers() parser_combine = subparsers.add_parser('combine') parser_combine.add_argument('--lang', nargs=1, type=str, action='store') parser_combine.set_defaults(func=combine) parser_split = subparsers.add_parser('split') parser_split.add_argument('--lang', nargs=1, type=str, action='store') parser_split.add_argument('--lang_name', nargs=1, type=str, action='store') parser_split.add_argument('source') parser_split.set_defaults(func=split) parser_tmxmerge = subparsers.add_parser('tmx_merge') parser_tmxmerge.add_argument('--dest', nargs=1, type=str, action='store') parser_tmxmerge.add_argument('source_files', nargs=argparse.REMAINDER) parser_tmxmerge.set_defaults(func=tmx_merge) args = parser.parse_args() if not hasattr(args, 'func'): parser.error('One of either combine or split must be specified') return args def main(): args = parse_args() args.func(args) if __name__ == '__main__': main()
apache-2.0
lnielsen/invenio
invenio/legacy/websubmit/engine.py
2
82544
## This file is part of Invenio. ## Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """WebSubmit: the mechanism for the submission of new records into Invenio via a Web interface. """ __revision__ = "$Id$" ## import interesting modules: import traceback import string import os import sys import time import types import re import pprint from urllib import quote_plus from cgi import escape from invenio.config import \ CFG_SITE_LANG, \ CFG_SITE_NAME, \ CFG_SITE_URL, \ CFG_WEBSUBMIT_STORAGEDIR, \ CFG_DEVEL_SITE, \ CFG_SITE_SECURE_URL, \ CFG_WEBSUBMIT_USE_MATHJAX from invenio.legacy.dbquery import Error from invenio.modules.access.engine import acc_authorize_action from invenio.legacy.webpage import page, error_page, warning_page from invenio.legacy.webuser import getUid, get_email, collect_user_info, isGuestUser, \ page_not_authorized from invenio.legacy.websubmit.config import CFG_RESERVED_SUBMISSION_FILENAMES, \ InvenioWebSubmitFunctionError, InvenioWebSubmitFunctionStop, \ InvenioWebSubmitFunctionWarning from invenio.base.i18n import gettext_set_language, wash_language from invenio.legacy.webstat.api import register_customevent from invenio.ext.logging import register_exception from invenio.utils.url import make_canonical_urlargd, redirect_to_url from invenio.legacy.websubmit.admin_engine import string_is_alphanumeric_including_underscore from invenio.utils.html import get_mathjax_header from invenio.legacy.websubmit.db_layer import \ get_storage_directory_of_action, \ get_longname_of_doctype, \ get_longname_of_action, \ get_num_pages_of_submission, \ get_parameter_value_for_doctype, \ submission_exists_in_log, \ log_new_pending_submission, \ log_new_completed_submission, \ update_submission_modified_date_in_log, \ update_submission_reference_in_log, \ update_submission_reference_and_status_in_log, \ get_form_fields_on_submission_page, \ get_element_description, \ get_element_check_description, \ get_form_fields_not_on_submission_page, \ function_step_is_last, \ get_collection_children_of_submission_collection, \ get_submission_collection_name, \ get_doctype_children_of_submission_collection, \ get_categories_of_doctype, \ get_doctype_details, \ get_actions_on_submission_page_for_doctype, \ get_action_details, \ get_parameters_of_function, \ get_details_of_submission, \ get_functions_for_submission_step, \ get_submissions_at_level_X_with_score_above_N, \ submission_is_finished import invenio.legacy.template websubmit_templates = invenio.legacy.template.load('websubmit') def interface(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG, doctype="", act="", startPg=1, access="", mainmenu="", fromdir="", nextPg="", nbPg="", curpage=1): """This function is called after a user has visited a document type's "homepage" and selected the type of "action" to perform. Having clicked an action-button (e.g. "Submit a New Record"), this function will be called . It performs the task of initialising a new submission session (retrieving information about the submission, creating a working submission-directory, etc), and "drawing" a submission page containing the WebSubmit form that the user uses to input the metadata to be submitted. When a user moves between pages in the submission interface, this function is recalled so that it can save the metadata entered into the previous page by the user, and draw the current submission-page. Note: During a submission, for each page refresh, this function will be called while the variable "step" (a form variable, seen by websubmit_webinterface, which calls this function) is 0 (ZERO). In other words, this function handles the FRONT-END phase of a submission, BEFORE the WebSubmit functions are called. @param req: (apache request object) *** NOTE: Added into this object, is a variable called "form" (req.form). This is added into the object in the index function of websubmit_webinterface. It contains a "mod_python.util.FieldStorage" instance, that contains the form-fields found on the previous submission page. @param c: (string), defaulted to CFG_SITE_NAME. The name of the Invenio installation. @param ln: (string), defaulted to CFG_SITE_LANG. The language in which to display the pages. @param doctype: (string) - the doctype ID of the doctype for which the submission is being made. @param act: (string) - The ID of the action being performed (e.g. submission of bibliographic information; modification of bibliographic information, etc). @param startPg: (integer) - Starting page for the submission? Defaults to 1. @param indir: (string) - the directory used to store all submissions of the given "type" of this submission. For example, if the submission is of the type "modify bibliographic information", this variable would contain "modify". @param access: (string) - the "access" number for the submission (e.g. 1174062451_7010). This number is also used as the name for the current working submission directory. @param mainmenu: (string) - contains the URL (minus the Invenio home stem) for the submission's home-page. (E.g. If this submission is "PICT", the "mainmenu" file would contain "/submit?doctype=PICT". @param fromdir: (integer) @param nextPg: (string) @param nbPg: (string) @param curpage: (integer) - the current submission page number. Defaults to 1. """ ln = wash_language(ln) # load the right message language _ = gettext_set_language(ln) sys.stdout = req # get user ID: user_info = collect_user_info(req) uid = user_info['uid'] uid_email = user_info['email'] # variable initialisation t = "" field = [] fieldhtml = [] level = [] fullDesc = [] text = '' check = [] select = [] radio = [] upload = [] txt = [] noPage = [] # Preliminary tasks if not access: # In some cases we want to take the users directly to the submit-form. # This fix makes this possible - as it generates the required access # parameter if it is not present. pid = os.getpid() now = time.time() access = "%i_%s" % (now, pid) # check we have minimum fields if not doctype or not act or not access: ## We don't have all the necessary information to go ahead ## with this submission: return warning_page(_("Not enough information to go ahead with the submission."), req, ln) try: assert(not access or re.match('\d+_\d+', access)) except AssertionError: register_exception(req=req, prefix='doctype="%s", access="%s"' % (doctype, access)) return warning_page(_("Invalid parameters"), req, ln) if doctype and act: ## Let's clean the input details = get_details_of_submission(doctype, act) if not details: return warning_page(_("Invalid doctype and act parameters"), req, ln) doctype = details[0] act = details[1] ## Before continuing to display the submission form interface, ## verify that this submission has not already been completed: if submission_is_finished(doctype, act, access, uid_email): ## This submission has already been completed. ## This situation can arise when, having completed a submission, ## the user uses the browser's back-button to go back to the form ## stage of the submission and then tries to submit once more. ## This is unsafe and should not be allowed. Instead of re-displaying ## the submission forms, display an error message to the user: wrnmsg = """<b>This submission has been completed. Please go to the""" \ """ <a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s">""" \ """main menu</a> to start a new submission.</b>""" \ % { 'doctype' : quote_plus(doctype), 'ln' : ln } return warning_page(wrnmsg, req, ln) ## retrieve the action and doctype data: ## Concatenate action ID and doctype ID to make the submission ID: subname = "%s%s" % (act, doctype) ## Get the submission storage directory from the DB: submission_dir = get_storage_directory_of_action(act) if submission_dir: indir = submission_dir else: ## Unable to determine the submission-directory: return warning_page(_("Unable to find the submission directory for the action: %(x_dir)s", x_dir=escape(str(act))), req, ln) ## get the document type's long-name: doctype_lname = get_longname_of_doctype(doctype) if doctype_lname is not None: ## Got the doctype long-name: replace spaces with HTML chars: docname = doctype_lname.replace(" ", "&nbsp;") else: ## Unknown document type: return warning_page(_("Unknown document type"), req, ln) ## get the action's long-name: actname = get_longname_of_action(act) if actname is None: ## Unknown action: return warning_page(_("Unknown action"), req, ln) ## Get the number of pages for this submission: num_submission_pages = get_num_pages_of_submission(subname) if num_submission_pages is not None: nbpages = num_submission_pages else: ## Unable to determine the number of pages for this submission: return warning_page(_("Unable to determine the number of submission pages."), req, ln) ## If unknown, get the current page of submission: if startPg != "" and curpage in ("", 0): curpage = startPg ## retrieve the name of the file in which the reference of ## the submitted document will be stored rn_filename = get_parameter_value_for_doctype(doctype, "edsrn") if rn_filename is not None: edsrn = rn_filename else: ## Unknown value for edsrn - set it to an empty string: edsrn = "" ## This defines the path to the directory containing the action data curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, indir, doctype, access) try: assert(curdir == os.path.abspath(curdir)) except AssertionError: register_exception(req=req, prefix='indir="%s", doctype="%s", access="%s"' % (indir, doctype, access)) return warning_page(_("Invalid parameters"), req, ln) ## if this submission comes from another one (fromdir is then set) ## We retrieve the previous submission directory and put it in the proper one if fromdir != "": olddir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, fromdir, doctype, access) try: assert(olddir == os.path.abspath(olddir)) except AssertionError: register_exception(req=req, prefix='fromdir="%s", doctype="%s", access="%s"' % (fromdir, doctype, access)) return warning_page(_("Invalid parameters"), req, ln) if os.path.exists(olddir): os.rename(olddir, curdir) ## If the submission directory still does not exist, we create it if not os.path.exists(curdir): try: os.makedirs(curdir) except Exception as e: register_exception(req=req, alert_admin=True) return warning_page(_("Unable to create a directory for this submission. The administrator has been alerted."), req, ln) ## Retrieve the previous page, as submitted to curdir (before we ## overwrite it with our curpage as declared from the incoming ## form) try: fp = open(os.path.join(curdir, "curpage")) previous_page_from_disk = fp.read() fp.close() except: previous_page_from_disk = "1" # retrieve the original main menu url and save it in the "mainmenu" file if mainmenu != "": fp = open(os.path.join(curdir, "mainmenu"), "w") fp.write(mainmenu) fp.close() # and if the file containing the URL to the main menu exists # we retrieve it and store it in the $mainmenu variable if os.path.exists(os.path.join(curdir, "mainmenu")): fp = open(os.path.join(curdir, "mainmenu"), "r"); mainmenu = fp.read() fp.close() else: mainmenu = "%s/submit" % (CFG_SITE_URL,) # various authentication related tasks... if uid_email != "guest" and uid_email != "": #First save the username (email address) in the SuE file. This way bibconvert will be able to use it if needed fp = open(os.path.join(curdir, "SuE"), "w") fp.write(uid_email) fp.close() if os.path.exists(os.path.join(curdir, "combo%s" % doctype)): fp = open(os.path.join(curdir, "combo%s" % doctype), "r"); categ = fp.read() fp.close() else: categ = req.form.get('combo%s' % doctype, '*') # is user authorized to perform this action? (auth_code, auth_message) = acc_authorize_action(req, 'submit', \ authorized_if_no_roles=not isGuestUser(uid), \ verbose=0, \ doctype=doctype, \ act=act, \ categ=categ) if not auth_code == 0: return warning_page("""<center><font color="red">%s</font></center>""" % auth_message, req, ln) ## update the "journal of submission": ## Does the submission already exist in the log? submission_exists = \ submission_exists_in_log(doctype, act, access, uid_email) if submission_exists == 1: ## update the modification-date of this submission in the log: update_submission_modified_date_in_log(doctype, act, access, uid_email) else: ## Submission doesn't exist in log - create it: log_new_pending_submission(doctype, act, access, uid_email) ## Let's write in curdir file under curdir the curdir value ## in case e.g. it is needed in FFT. fp = open(os.path.join(curdir, "curdir"), "w") fp.write(curdir) fp.close() ## Let's write in ln file the current language fp = open(os.path.join(curdir, "ln"), "w") fp.write(ln) fp.close() # Save the form fields entered in the previous submission page # If the form was sent with the GET method form = dict(req.form) value = "" # we parse all the form variables for key, formfields in form.items(): filename = key.replace("[]", "") file_to_open = os.path.join(curdir, filename) try: assert(file_to_open == os.path.abspath(file_to_open)) except AssertionError: register_exception(req=req, prefix='curdir="%s", filename="%s"' % (curdir, filename)) return warning_page(_("Invalid parameters"), req, ln) # Do not write reserved filenames to disk if filename in CFG_RESERVED_SUBMISSION_FILENAMES: # Unless there is really an element with that name on this # page or previous one (either visited, or declared to be # visited), which means that admin authorized it. if not ((str(curpage).isdigit() and \ filename in [submission_field[3] for submission_field in \ get_form_fields_on_submission_page(subname, curpage)]) or \ (str(curpage).isdigit() and int(curpage) > 1 and \ filename in [submission_field[3] for submission_field in \ get_form_fields_on_submission_page(subname, int(curpage) - 1)]) or \ (previous_page_from_disk.isdigit() and \ filename in [submission_field[3] for submission_field in \ get_form_fields_on_submission_page(subname, int(previous_page_from_disk))])): # Still this will filter out reserved field names that # might have been called by functions such as # Create_Modify_Interface function in MBI step, or # dynamic fields in response elements, but that is # unlikely to be a problem. continue # Skip variables containing characters that are not allowed in # WebSubmit elements if not string_is_alphanumeric_including_underscore(filename): continue # the field is an array if isinstance(formfields, types.ListType): fp = open(file_to_open, "w") for formfield in formfields: #stripslashes(value) value = specialchars(formfield) fp.write(value+"\n") fp.close() # the field is a normal string elif isinstance(formfields, types.StringTypes) and formfields != "": value = formfields fp = open(file_to_open, "w") fp.write(specialchars(value)) fp.close() # the field is a file elif hasattr(formfields,"filename") and formfields.filename: dir_to_open = os.path.join(curdir, 'files', key) try: assert(dir_to_open == os.path.abspath(dir_to_open)) assert(dir_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR)) except AssertionError: register_exception(req=req, prefix='curdir="%s", key="%s"' % (curdir, key)) return warning_page(_("Invalid parameters"), req, ln) if not os.path.exists(dir_to_open): try: os.makedirs(dir_to_open) except: register_exception(req=req, alert_admin=True) return warning_page(_("Cannot create submission directory. The administrator has been alerted."), req, ln) filename = formfields.filename ## Before saving the file to disc, wash the filename (in particular ## washing away UNIX and Windows (e.g. DFS) paths): filename = os.path.basename(filename.split('\\')[-1]) filename = filename.strip() if filename != "": fp = open(os.path.join(dir_to_open, filename), "w") while True: buf = formfields.read(10240) if buf: fp.write(buf) else: break fp.close() fp = open(os.path.join(curdir, "lastuploadedfile"), "w") fp.write(filename) fp.close() fp = open(file_to_open, "w") fp.write(filename) fp.close() else: return warning_page(_("No file uploaded?"), req, ln) ## if the found field is the reference of the document, ## save this value in the "journal of submissions": if uid_email != "" and uid_email != "guest": if key == edsrn: update_submission_reference_in_log(doctype, access, uid_email, value) ## create the interface: subname = "%s%s" % (act, doctype) ## Get all of the form fields that appear on this page, ordered by fieldnum: form_fields = get_form_fields_on_submission_page(subname, curpage) full_fields = [] values = [] the_globals = { 'doctype' : doctype, 'action' : action, 'access' : access, 'ln' : ln, 'curdir' : curdir, 'uid' : uid, 'uid_email' : uid_email, 'form' : form, 'act' : act, 'action' : act, ## for backward compatibility 'req' : req, 'user_info' : user_info, 'InvenioWebSubmitFunctionError' : InvenioWebSubmitFunctionError, '__websubmit_in_jail__' : True, '__builtins__' : globals()['__builtins__'] } for field_instance in form_fields: full_field = {} ## Retrieve the field's description: element_descr = get_element_description(field_instance[3]) try: assert(element_descr is not None) except AssertionError: msg = _("Unknown form field found on submission page.") register_exception(req=req, alert_admin=True, prefix=msg) ## The form field doesn't seem to exist - return with error message: return warning_page(_("Unknown form field found on submission page."), req, ln) if element_descr[8] is None: val = "" else: val = element_descr[8] ## we also retrieve and add the javascript code of the checking function, if needed ## Set it to empty string to begin with: full_field['javascript'] = '' if field_instance[7] != '': check_descr = get_element_check_description(field_instance[7]) if check_descr is not None: ## Retrieved the check description: full_field['javascript'] = check_descr full_field['type'] = element_descr[3] full_field['name'] = field_instance[3] full_field['rows'] = element_descr[5] full_field['cols'] = element_descr[6] full_field['val'] = val full_field['size'] = element_descr[4] full_field['maxlength'] = element_descr[7] full_field['htmlcode'] = element_descr[9] full_field['typename'] = field_instance[1] ## TODO: Investigate this, Not used? ## It also seems to refer to pagenum. # The 'R' fields must be executed in the engine's environment, # as the runtime functions access some global and local # variables. if full_field ['type'] == 'R': try: co = compile (full_field ['htmlcode'].replace("\r\n","\n"), "<string>", "exec") the_globals['text'] = '' the_globals['custom_level'] = None exec co in the_globals text = the_globals['text'] # Also get the custom_level if it's define in the element description custom_level = the_globals.get('custom_level') # Make sure custom_level has an appropriate value or default to 'O' if custom_level not in ('M', 'O', None): custom_level = 'O' except: register_exception(req=req, alert_admin=True, prefix="Error in evaluating response element %s with globals %s" % (pprint.pformat(full_field), pprint.pformat(the_globals))) raise else: text = websubmit_templates.tmpl_submit_field (ln = ln, field = full_field) # Provide a default value for the custom_level custom_level = None # we now determine the exact type of the created field if full_field['type'] not in [ 'D','R']: field.append(full_field['name']) level.append(custom_level is None and field_instance[5] or custom_level) fullDesc.append(field_instance[4]) txt.append(field_instance[6]) check.append(field_instance[7]) # If the field is not user-defined, we try to determine its type # (select, radio, file upload...) # check whether it is a select field or not if re.search("SELECT", text, re.IGNORECASE) is not None: select.append(1) else: select.append(0) # checks whether it is a radio field or not if re.search(r"TYPE=[\"']?radio", text, re.IGNORECASE) is not None: radio.append(1) else: radio.append(0) # checks whether it is a file upload or not if re.search(r"TYPE=[\"']?file", text, re.IGNORECASE) is not None: upload.append(1) else: upload.append(0) # if the field description contains the "<COMBO>" string, replace # it by the category selected on the document page submission page combofile = "combo%s" % doctype if os.path.exists("%s/%s" % (curdir, combofile)): f = open("%s/%s" % (curdir, combofile), "r") combo = f.read() f.close() else: combo = "" text = text.replace("<COMBO>", combo) # if there is a <YYYY> tag in it, replace it by the current year year = time.strftime("%Y"); text = text.replace("<YYYY>", year) # if there is a <TODAY> tag in it, replace it by the current year today = time.strftime("%d/%m/%Y"); text = text.replace("<TODAY>", today) fieldhtml.append(text) else: select.append(0) radio.append(0) upload.append(0) # field.append(value) - initial version, not working with JS, taking a submitted value field.append(field_instance[3]) level.append(custom_level is None and field_instance[5] or custom_level) txt.append(field_instance[6]) fullDesc.append(field_instance[4]) check.append(field_instance[7]) fieldhtml.append(text) full_field['fullDesc'] = field_instance[4] full_field['text'] = text # If a file exists with the name of the field we extract the saved value text = '' if os.path.exists(os.path.join(curdir, full_field['name'])): file = open(os.path.join(curdir, full_field['name']), "r"); text = file.read() file.close() values.append(text) full_fields.append(full_field) returnto = {} if int(curpage) == int(nbpages): subname = "%s%s" % (act, doctype) other_form_fields = \ get_form_fields_not_on_submission_page(subname, curpage) nbFields = 0 message = "" fullcheck_select = [] fullcheck_radio = [] fullcheck_upload = [] fullcheck_field = [] fullcheck_level = [] fullcheck_txt = [] fullcheck_noPage = [] fullcheck_check = [] for field_instance in other_form_fields: if field_instance[5] == "M": ## If this field is mandatory, get its description: element_descr = get_element_description(field_instance[3]) try: assert(element_descr is not None) except AssertionError: msg = _("Unknown form field found on submission page.") register_exception(req=req, alert_admin=True, prefix=msg) ## The form field doesn't seem to exist - return with error message: return warning_page(_("Unknown form field found on submission page."), req, ln) if element_descr[3] in ['D', 'R']: if element_descr[3] == "D": text = element_descr[9] else: text = eval(element_descr[9]) formfields = text.split(">") for formfield in formfields: match = re.match("name=([^ <>]+)", formfield, re.IGNORECASE) if match is not None: names = match.groups for value in names: if value != "": value = re.compile("[\"']+").sub("", value) fullcheck_field.append(value) fullcheck_level.append(field_instance[5]) fullcheck_txt.append(field_instance[6]) fullcheck_noPage.append(field_instance[1]) fullcheck_check.append(field_instance[7]) nbFields = nbFields + 1 else: fullcheck_noPage.append(field_instance[1]) fullcheck_field.append(field_instance[3]) fullcheck_level.append(field_instance[5]) fullcheck_txt.append(field_instance[6]) fullcheck_check.append(field_instance[7]) nbFields = nbFields+1 # tests each mandatory field fld = 0 res = 1 for i in xrange(nbFields): res = 1 if not os.path.exists(os.path.join(curdir, fullcheck_field[i])): res = 0 else: file = open(os.path.join(curdir, fullcheck_field[i]), "r") text = file.read() if text == '': res = 0 else: if text == "Select:": res = 0 if res == 0: fld = i break if not res: returnto = { 'field' : fullcheck_txt[fld], 'page' : fullcheck_noPage[fld], } t += websubmit_templates.tmpl_page_interface( ln = ln, docname = docname, actname = actname, curpage = curpage, nbpages = nbpages, nextPg = nextPg, access = access, nbPg = nbPg, doctype = doctype, act = act, fields = full_fields, javascript = websubmit_templates.tmpl_page_interface_js( ln = ln, upload = upload, field = field, fieldhtml = fieldhtml, txt = txt, check = check, level = level, curdir = curdir, values = values, select = select, radio = radio, curpage = curpage, nbpages = nbpages, returnto = returnto, ), mainmenu = mainmenu, ) t += websubmit_templates.tmpl_page_do_not_leave_submission_js(ln) # start display: req.content_type = "text/html" req.send_http_header() p_navtrail = """<a href="/submit?ln=%(ln)s" class="navtrail">%(submit)s</a>&nbsp;>&nbsp;<a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s" class="navtrail">%(docname)s</a>&nbsp;""" % { 'submit' : _("Submit"), 'doctype' : quote_plus(doctype), 'docname' : docname, 'ln' : ln } ## add MathJax if wanted if CFG_WEBSUBMIT_USE_MATHJAX: metaheaderadd = get_mathjax_header(req.is_https()) metaheaderadd += websubmit_templates.tmpl_mathpreview_header(ln, req.is_https()) else: metaheaderadd = '' return page(title= actname, body = t, navtrail = p_navtrail, description = "submit documents", keywords = "submit", uid = uid, language = ln, req = req, navmenuid='submit', metaheaderadd=metaheaderadd) def endaction(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG, doctype="", act="", startPg=1, access="", mainmenu="", fromdir="", nextPg="", nbPg="", curpage=1, step=1, mode="U"): """Having filled-in the WebSubmit form created for metadata by the interface function, the user clicks a button to either "finish the submission" or to "proceed" to the next stage of the submission. At this point, a variable called "step" will be given a value of 1 or above, which means that this function is called by websubmit_webinterface. So, during all non-zero steps of the submission, this function is called. In other words, this function is called during the BACK-END phase of a submission, in which WebSubmit *functions* are being called. The function first ensures that all of the WebSubmit form field values have been saved in the current working submission directory, in text- files with the same name as the field elements have. It then determines the functions to be called for the given step of the submission, and executes them. Following this, if this is the last step of the submission, it logs the submission as "finished" in the journal of submissions. @param req: (apache request object) *** NOTE: Added into this object, is a variable called "form" (req.form). This is added into the object in the index function of websubmit_webinterface. It contains a "mod_python.util.FieldStorage" instance, that contains the form-fields found on the previous submission page. @param c: (string), defaulted to CFG_SITE_NAME. The name of the Invenio installation. @param ln: (string), defaulted to CFG_SITE_LANG. The language in which to display the pages. @param doctype: (string) - the doctype ID of the doctype for which the submission is being made. @param act: (string) - The ID of the action being performed (e.g. submission of bibliographic information; modification of bibliographic information, etc). @param startPg: (integer) - Starting page for the submission? Defaults to 1. @param indir: (string) - the directory used to store all submissions of the given "type" of this submission. For example, if the submission is of the type "modify bibliographic information", this variable would contain "modify". @param access: (string) - the "access" number for the submission (e.g. 1174062451_7010). This number is also used as the name for the current working submission directory. @param mainmenu: (string) - contains the URL (minus the Invenio home stem) for the submission's home-page. (E.g. If this submission is "PICT", the "mainmenu" file would contain "/submit?doctype=PICT". @param fromdir: @param nextPg: @param nbPg: @param curpage: (integer) - the current submission page number. Defaults to 1. @param step: (integer) - the current step of the submission. Defaults to 1. @param mode: """ # load the right message language _ = gettext_set_language(ln) dismode = mode ln = wash_language(ln) sys.stdout = req rn = "" t = "" # get user ID: uid = getUid(req) uid_email = get_email(uid) ## Get the submission storage directory from the DB: submission_dir = get_storage_directory_of_action(act) if submission_dir: indir = submission_dir else: ## Unable to determine the submission-directory: return warning_page(_("Unable to find the submission directory for the action: %(x_dir)s", x_dir=escape(str(act))), req, ln) curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, indir, doctype, access) if os.path.exists(os.path.join(curdir, "combo%s" % doctype)): fp = open(os.path.join(curdir, "combo%s" % doctype), "r"); categ = fp.read() fp.close() else: categ = req.form.get('combo%s' % doctype, '*') # is user authorized to perform this action? (auth_code, auth_message) = acc_authorize_action(req, 'submit', \ authorized_if_no_roles=not isGuestUser(uid), \ verbose=0, \ doctype=doctype, \ act=act, \ categ=categ) if not auth_code == 0: return warning_page("""<center><font color="red">%s</font></center>""" % auth_message, req, ln) # Preliminary tasks ## check we have minimum fields if not doctype or not act or not access: ## We don't have all the necessary information to go ahead ## with this submission: return warning_page(_("Not enough information to go ahead with the submission."), req, ln) if doctype and act: ## Let's clean the input details = get_details_of_submission(doctype, act) if not details: return warning_page(_("Invalid doctype and act parameters"), req, ln) doctype = details[0] act = details[1] try: assert(not access or re.match('\d+_\d+', access)) except AssertionError: register_exception(req=req, prefix='doctype="%s", access="%s"' % (doctype, access)) return warning_page(_("Invalid parameters"), req, ln) ## Before continuing to process the submitted data, verify that ## this submission has not already been completed: if submission_is_finished(doctype, act, access, uid_email): ## This submission has already been completed. ## This situation can arise when, having completed a submission, ## the user uses the browser's back-button to go back to the form ## stage of the submission and then tries to submit once more. ## This is unsafe and should not be allowed. Instead of re-processing ## the submitted data, display an error message to the user: wrnmsg = """<b>This submission has been completed. Please go to the""" \ """ <a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s">""" \ """main menu</a> to start a new submission.</b>""" \ % { 'doctype' : quote_plus(doctype), 'ln' : ln } return warning_page(wrnmsg, req, ln) ## Get the number of pages for this submission: subname = "%s%s" % (act, doctype) ## retrieve the action and doctype data ## Get the submission storage directory from the DB: submission_dir = get_storage_directory_of_action(act) if submission_dir: indir = submission_dir else: ## Unable to determine the submission-directory: return warning_page(_("Unable to find the submission directory for the action: %(x_dir)s", x_dir=escape(str(act))), req, ln) # The following words are reserved and should not be used as field names reserved_words = ["stop", "file", "nextPg", "startPg", "access", "curpage", "nbPg", "act", \ "indir", "doctype", "mode", "step", "deleted", "file_path", "userfile_name"] # This defines the path to the directory containing the action data curdir = os.path.join(CFG_WEBSUBMIT_STORAGEDIR, indir, doctype, access) try: assert(curdir == os.path.abspath(curdir)) except AssertionError: register_exception(req=req, prefix='indir="%s", doctype=%s, access=%s' % (indir, doctype, access)) return warning_page(_("Invalid parameters"), req, ln) ## If the submission directory still does not exist, we create it if not os.path.exists(curdir): try: os.makedirs(curdir) except Exception as e: register_exception(req=req, alert_admin=True) return warning_page(_("Unable to create a directory for this submission. The administrator has been alerted."), req, ln) # retrieve the original main menu url ans save it in the "mainmenu" file if mainmenu != "": fp = open(os.path.join(curdir, "mainmenu"), "w") fp.write(mainmenu) fp.close() # and if the file containing the URL to the main menu exists # we retrieve it and store it in the $mainmenu variable if os.path.exists(os.path.join(curdir, "mainmenu")): fp = open(os.path.join(curdir, "mainmenu"), "r"); mainmenu = fp.read() fp.close() else: mainmenu = "%s/submit" % (CFG_SITE_URL,) num_submission_pages = get_num_pages_of_submission(subname) if num_submission_pages is not None: nbpages = num_submission_pages else: ## Unable to determine the number of pages for this submission: return warning_page(_("Unable to determine the number of submission pages."), \ req, ln) ## Retrieve the previous page, as submitted to curdir (before we ## overwrite it with our curpage as declared from the incoming ## form) try: fp = open(os.path.join(curdir, "curpage")) previous_page_from_disk = fp.read() fp.close() except: previous_page_from_disk = str(num_submission_pages) ## retrieve the name of the file in which the reference of ## the submitted document will be stored rn_filename = get_parameter_value_for_doctype(doctype, "edsrn") if rn_filename is not None: edsrn = rn_filename else: ## Unknown value for edsrn - set it to an empty string: edsrn = "" ## Determine whether the action is finished ## (ie there are no other steps after the current one): finished = function_step_is_last(doctype, act, step) ## Let's write in curdir file under curdir the curdir value ## in case e.g. it is needed in FFT. fp = open(os.path.join(curdir, "curdir"), "w") fp.write(curdir) fp.close() ## Let's write in ln file the current language fp = open(os.path.join(curdir, "ln"), "w") fp.write(ln) fp.close() # Save the form fields entered in the previous submission page # If the form was sent with the GET method form = req.form value = "" # we parse all the form variables for key in form.keys(): formfields = form[key] filename = key.replace("[]", "") file_to_open = os.path.join(curdir, filename) try: assert(file_to_open == os.path.abspath(file_to_open)) assert(file_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR)) except AssertionError: register_exception(req=req, prefix='curdir="%s", filename="%s"' % (curdir, filename)) return warning_page(_("Invalid parameters"), req, ln) # Do not write reserved filenames to disk if filename in CFG_RESERVED_SUBMISSION_FILENAMES: # Unless there is really an element with that name on this # page, or on the previously visited one, which means that # admin authorized it. Note that in endaction() curpage is # equivalent to the "previous" page value if not ((previous_page_from_disk.isdigit() and \ filename in [submission_field[3] for submission_field in \ get_form_fields_on_submission_page(subname, int(previous_page_from_disk))]) or \ (str(curpage).isdigit() and int(curpage) > 1 and \ filename in [submission_field[3] for submission_field in \ get_form_fields_on_submission_page(subname, int(curpage) - 1)])): # might have been called by functions such as # Create_Modify_Interface function in MBI step, or # dynamic fields in response elements, but that is # unlikely to be a problem. continue # Skip variables containing characters that are not allowed in # WebSubmit elements if not string_is_alphanumeric_including_underscore(filename): continue # the field is an array if isinstance(formfields, types.ListType): fp = open(file_to_open, "w") for formfield in formfields: #stripslashes(value) value = specialchars(formfield) fp.write(value+"\n") fp.close() # the field is a normal string elif isinstance(formfields, types.StringTypes) and formfields != "": value = formfields fp = open(file_to_open, "w") fp.write(specialchars(value)) fp.close() # the field is a file elif hasattr(formfields, "filename") and formfields.filename: dir_to_open = os.path.join(curdir, 'files', key) try: assert(dir_to_open == os.path.abspath(dir_to_open)) assert(dir_to_open.startswith(CFG_WEBSUBMIT_STORAGEDIR)) except AssertionError: register_exception(req=req, prefix='curdir="%s", key="%s"' % (curdir, key)) return warning_page(_("Invalid parameters"), req, ln) if not os.path.exists(dir_to_open): try: os.makedirs(dir_to_open) except: register_exception(req=req, alert_admin=True) return warning_page(_("Cannot create submission directory. The administrator has been alerted."), req, ln) filename = formfields.filename ## Before saving the file to disc, wash the filename (in particular ## washing away UNIX and Windows (e.g. DFS) paths): filename = os.path.basename(filename.split('\\')[-1]) filename = filename.strip() if filename != "": fp = open(os.path.join(dir_to_open, filename), "w") while True: buf = formfields.file.read(10240) if buf: fp.write(buf) else: break fp.close() fp = open(os.path.join(curdir, "lastuploadedfile"), "w") fp.write(filename) fp.close() fp = open(file_to_open, "w") fp.write(filename) fp.close() else: return warning_page(_("No file uploaded?"), req, ln) ## if the found field is the reference of the document ## we save this value in the "journal of submissions" if uid_email != "" and uid_email != "guest": if key == edsrn: update_submission_reference_in_log(doctype, access, uid_email, value) ## get the document type's long-name: doctype_lname = get_longname_of_doctype(doctype) if doctype_lname is not None: ## Got the doctype long-name: replace spaces with HTML chars: docname = doctype_lname.replace(" ", "&nbsp;") else: ## Unknown document type: return warning_page(_("Unknown document type"), req, ln) ## get the action's long-name: actname = get_longname_of_action(act) if actname is None: ## Unknown action: return warning_page(_("Unknown action"), req, ln) ## Determine whether the action is finished ## (ie there are no other steps after the current one): last_step = function_step_is_last(doctype, act, step) next_action = '' ## The next action to be proposed to the user # Prints the action details, returning the mandatory score action_score = action_details(doctype, act) current_level = get_level(doctype, act) # Calls all the function's actions function_content = '' try: ## Handle the execution of the functions for this ## submission/step: start_time = time.time() (function_content, last_step, action_score, rn) = \ print_function_calls(req=req, doctype=doctype, action=act, step=step, form=form, start_time=start_time, access=access, curdir=curdir, dismode=mode, rn=rn, last_step=last_step, action_score=action_score, ln=ln) except InvenioWebSubmitFunctionError as e: register_exception(req=req, alert_admin=True, prefix='doctype="%s", action="%s", step="%s", form="%s", start_time="%s"' % (doctype, act, step, form, start_time)) ## There was a serious function-error. Execution ends. if CFG_DEVEL_SITE: raise else: return warning_page(_("A serious function-error has been encountered. Adminstrators have been alerted. <br /><em>Please not that this might be due to wrong characters inserted into the form</em> (e.g. by copy and pasting some text from a PDF file)."), req, ln) except InvenioWebSubmitFunctionStop as e: ## For one reason or another, one of the functions has determined that ## the data-processing phase (i.e. the functions execution) should be ## halted and the user should be returned to the form interface once ## more. (NOTE: Redirecting the user to the Web-form interface is ## currently done using JavaScript. The "InvenioWebSubmitFunctionStop" ## exception contains a "value" string, which is effectively JavaScript ## - probably an alert box and a form that is submitted). **THIS WILL ## CHANGE IN THE FUTURE WHEN JavaScript IS REMOVED!** if e.value is not None: function_content = e.value else: function_content = e else: ## No function exceptions (InvenioWebSubmitFunctionStop, ## InvenioWebSubmitFunctionError) were raised by the functions. Propose ## the next action (if applicable), and log the submission as finished: ## If the action was mandatory we propose the next ## mandatory action (if any) if action_score != -1 and last_step == 1: next_action = Propose_Next_Action(doctype, \ action_score, \ access, \ current_level, \ indir) ## If we are in the last step of an action, we can update ## the "journal of submissions" if last_step == 1: if uid_email != "" and uid_email != "guest": ## update the "journal of submission": ## Does the submission already exist in the log? submission_exists = \ submission_exists_in_log(doctype, act, access, uid_email) if submission_exists == 1: ## update the rn and status to finished for this submission ## in the log: update_submission_reference_and_status_in_log(doctype, \ act, \ access, \ uid_email, \ rn, \ "finished") else: ## Submission doesn't exist in log - create it: log_new_completed_submission(doctype, \ act, \ access, \ uid_email, \ rn) ## Having executed the functions, create the page that will be displayed ## to the user: t = websubmit_templates.tmpl_page_endaction( ln = ln, # these fields are necessary for the navigation nextPg = nextPg, startPg = startPg, access = access, curpage = curpage, nbPg = nbPg, nbpages = nbpages, doctype = doctype, act = act, docname = docname, actname = actname, mainmenu = mainmenu, finished = finished, function_content = function_content, next_action = next_action, ) if finished: # register event in webstat try: register_customevent("websubmissions", [get_longname_of_doctype(doctype)]) except: register_exception(suffix="Do the webstat tables exists? Try with 'webstatadmin --load-config'") else: t += websubmit_templates.tmpl_page_do_not_leave_submission_js(ln) # start display: req.content_type = "text/html" req.send_http_header() p_navtrail = '<a href="/submit?ln='+ln+'" class="navtrail">' + _("Submit") +\ """</a>&nbsp;>&nbsp;<a href="/submit?doctype=%(doctype)s&amp;ln=%(ln)s" class="navtrail">%(docname)s</a>""" % { 'doctype' : quote_plus(doctype), 'docname' : docname, 'ln' : ln, } ## add MathJax if wanted if CFG_WEBSUBMIT_USE_MATHJAX: metaheaderadd = get_mathjax_header(req.is_https()) metaheaderadd += websubmit_templates.tmpl_mathpreview_header(ln, req.is_https()) else: metaheaderadd = '' return page(title= actname, body = t, navtrail = p_navtrail, description="submit documents", keywords="submit", uid = uid, language = ln, req = req, navmenuid='submit', metaheaderadd=metaheaderadd) def home(req, catalogues_text, c=CFG_SITE_NAME, ln=CFG_SITE_LANG): """This function generates the WebSubmit "home page". Basically, this page contains a list of submission-collections in WebSubmit, and gives links to the various document-type submissions. Document-types only appear on this page when they have been connected to a submission-collection in WebSubmit. @param req: (apache request object) @param catalogues_text (string): the computed catalogues tree @param c: (string) - defaults to CFG_SITE_NAME @param ln: (string) - The Invenio interface language of choice. Defaults to CFG_SITE_LANG (the default language of the installation). @return: (string) - the Web page to be displayed. """ ln = wash_language(ln) # get user ID: try: uid = getUid(req) user_info = collect_user_info(req) except Error as e: return error_page(e, req, ln) # load the right message language _ = gettext_set_language(ln) finaltext = websubmit_templates.tmpl_submit_home_page( ln = ln, catalogues = catalogues_text, user_info = user_info, ) return page(title=_("Submit"), body=finaltext, navtrail=[], description="submit documents", keywords="submit", uid=uid, language=ln, req=req, navmenuid='submit' ) def makeCataloguesTable(req, ln=CFG_SITE_LANG): """Build the 'catalogues' (submission-collections) tree for the WebSubmit home-page. This tree contains the links to the various document types in WebSubmit. @param req: (dict) - the user request object in order to decide whether to display a submission. @param ln: (string) - the language of the interface. (defaults to 'CFG_SITE_LANG'). @return: (string, bool, bool) - the submission-collections tree. True if there is at least one submission authorized for the user True if there is at least one submission """ def is_at_least_one_submission_authorized(cats): for cat in cats: if cat['docs']: return True if is_at_least_one_submission_authorized(cat['sons']): return True return False text = "" catalogues = [] ## Get the submission-collections attached at the top level ## of the submission-collection tree: top_level_collctns = get_collection_children_of_submission_collection(0) if len(top_level_collctns) != 0: ## There are submission-collections attatched to the top level. ## retrieve their details for displaying: for child_collctn in top_level_collctns: catalogues.append(getCatalogueBranch(child_collctn[0], 1, req)) text = websubmit_templates.tmpl_submit_home_catalogs( ln=ln, catalogs=catalogues) submissions_exist = True at_least_one_submission_authorized = is_at_least_one_submission_authorized(catalogues) else: text = websubmit_templates.tmpl_submit_home_catalog_no_content(ln=ln) submissions_exist = False at_least_one_submission_authorized = False return text, at_least_one_submission_authorized, submissions_exist def getCatalogueBranch(id_father, level, req): """Build up a given branch of the submission-collection tree. I.e. given a parent submission-collection ID, build up the tree below it. This tree will include doctype-children, as well as other submission- collections and their children. Finally, return the branch as a dictionary. @param id_father: (integer) - the ID of the submission-collection from which to begin building the branch. @param level: (integer) - the level of the current submission- collection branch. @param req: (dict) - the user request object in order to decide whether to display a submission. @return: (dictionary) - the branch and its sub-branches. """ elem = {} ## The dictionary to contain this branch of the tree. ## First, get the submission-collection-details: collctn_name = get_submission_collection_name(id_father) if collctn_name is not None: ## Got the submission-collection's name: elem['name'] = collctn_name else: ## The submission-collection is unknown to the DB ## set its name as empty: elem['name'] = "" elem['id'] = id_father elem['level'] = level ## Now get details of the doctype-children of this ## submission-collection: elem['docs'] = [] ## List to hold the doctype-children ## of the submission-collection doctype_children = \ get_doctype_children_of_submission_collection(id_father) user_info = collect_user_info(req) for child_doctype in doctype_children: ## To get access to a submission pipeline for a logged in user, ## it is decided by any authorization. If none are defined for the action ## then a logged in user will get access. ## If user is not logged in, a specific rule to allow the action is needed if acc_authorize_action(req, 'submit', \ authorized_if_no_roles=not isGuestUser(user_info['uid']), \ doctype=child_doctype[0])[0] == 0: elem['docs'].append(getDoctypeBranch(child_doctype[0])) ## Now, get the collection-children of this submission-collection: elem['sons'] = [] collctn_children = \ get_collection_children_of_submission_collection(id_father) for child_collctn in collctn_children: elem['sons'].append(getCatalogueBranch(child_collctn[0], level + 1, req)) ## Now return this branch of the built-up 'collection-tree': return elem def getDoctypeBranch(doctype): """Create a document-type 'leaf-node' for the submission-collections tree. Basically, this leaf is a dictionary containing the name and ID of the document-type submission to which it links. @param doctype: (string) - the ID of the document type. @return: (dictionary) - the document-type 'leaf node'. Contains the following values: + id: (string) - the document-type ID. + name: (string) - the (long) name of the document-type. """ ldocname = get_longname_of_doctype(doctype) if ldocname is None: ldocname = "Unknown Document Type" return { 'id' : doctype, 'name' : ldocname, } def displayCatalogueBranch(id_father, level, catalogues): text = "" collctn_name = get_submission_collection_name(id_father) if collctn_name is None: ## If this submission-collection wasn't known in the DB, ## give it the name "Unknown Submission-Collection" to ## avoid errors: collctn_name = "Unknown Submission-Collection" ## Now, create the display for this submission-collection: if level == 1: text = "<LI><font size=\"+1\"><strong>%s</strong></font>\n" \ % collctn_name else: ## TODO: These are the same (and the if is ugly.) Why? if level == 2: text = "<LI>%s\n" % collctn_name else: if level > 2: text = "<LI>%s\n" % collctn_name ## Now display the children document-types that are attached ## to this submission-collection: ## First, get the children: doctype_children = get_doctype_children_of_submission_collection(id_father) collctn_children = get_collection_children_of_submission_collection(id_father) if len(doctype_children) > 0 or len(collctn_children) > 0: ## There is something to display, so open a list: text = text + "<UL>\n" ## First, add the doctype leaves of this branch: for child_doctype in doctype_children: ## Add the doctype 'leaf-node': text = text + displayDoctypeBranch(child_doctype[0], catalogues) ## Now add the submission-collection sub-branches: for child_collctn in collctn_children: catalogues.append(child_collctn[0]) text = text + displayCatalogueBranch(child_collctn[0], level+1, catalogues) ## Finally, close up the list if there were nodes to display ## at this branch: if len(doctype_children) > 0 or len(collctn_children) > 0: text = text + "</UL>\n" return text def displayDoctypeBranch(doctype, catalogues): text = "" ldocname = get_longname_of_doctype(doctype) if ldocname is None: ldocname = "Unknown Document Type" text = "<LI><a href=\"\" onmouseover=\"javascript:" \ "popUpTextWindow('%s',true,event);\" onmouseout" \ "=\"javascript:popUpTextWindow('%s',false,event);\" " \ "onClick=\"document.forms[0].doctype.value='%s';" \ "document.forms[0].submit();return false;\">%s</a>\n" \ % (doctype, doctype, doctype, ldocname) return text def action(req, c=CFG_SITE_NAME, ln=CFG_SITE_LANG, doctype=""): # load the right message language _ = gettext_set_language(ln) nbCateg = 0 snameCateg = [] lnameCateg = [] actionShortDesc = [] indir = [] actionbutton = [] statustext = [] t = "" ln = wash_language(ln) # get user ID: try: uid = getUid(req) except Error as e: return error_page(e, req, ln) #parses database to get all data ## first, get the list of categories doctype_categs = get_categories_of_doctype(doctype) for doctype_categ in doctype_categs: if not acc_authorize_action(req, 'submit', \ authorized_if_no_roles=not isGuestUser(uid), \ verbose=0, \ doctype=doctype, \ categ=doctype_categ[0])[0] == 0: # This category is restricted for this user, move on to the next categories. continue nbCateg = nbCateg+1 snameCateg.append(doctype_categ[0]) lnameCateg.append(doctype_categ[1]) ## Now get the details of the document type: doctype_details = get_doctype_details(doctype) if doctype_details is None: ## Doctype doesn't exist - raise error: return warning_page(_("Unable to find document type: %(doctype)s", doctype=escape(str(doctype))), req, ln) else: docFullDesc = doctype_details[0] # Also update the doctype as returned by the database, since # it might have a differnent case (eg. DemOJrN->demoJRN) doctype = docShortDesc = doctype_details[1] description = doctype_details[4] ## Get the details of the actions supported by this document-type: doctype_actions = get_actions_on_submission_page_for_doctype(doctype) for doctype_action in doctype_actions: if not acc_authorize_action(req, 'submit', \ authorized_if_no_roles=not isGuestUser(uid), \ doctype=doctype, \ act=doctype_action[0])[0] == 0: # This action is not authorized for this user, move on to the next actions. continue ## Get the details of this action: action_details = get_action_details(doctype_action[0]) if action_details is not None: actionShortDesc.append(doctype_action[0]) indir.append(action_details[1]) actionbutton.append(action_details[4]) statustext.append(action_details[5]) if not snameCateg and not actionShortDesc: if isGuestUser(uid): # If user is guest and does not have access to any of the # categories, offer to login. return redirect_to_url(req, "%s/youraccount/login%s" % ( CFG_SITE_SECURE_URL, make_canonical_urlargd({'referer' : CFG_SITE_SECURE_URL + req.unparsed_uri, 'ln' : ln}, {})), norobot=True) else: return page_not_authorized(req, "../submit", uid=uid, text=_("You are not authorized to access this submission interface."), navmenuid='submit') ## Send the gathered information to the template so that the doctype's ## home-page can be displayed: t = websubmit_templates.tmpl_action_page( ln=ln, uid=uid, pid = os.getpid(), now = time.time(), doctype = doctype, description = description, docfulldesc = docFullDesc, snameCateg = snameCateg, lnameCateg = lnameCateg, actionShortDesc = actionShortDesc, indir = indir, # actionbutton = actionbutton, statustext = statustext, ) p_navtrail = """<a href="/submit?ln=%(ln)s" class="navtrail">%(submit)s</a>""" % {'submit' : _("Submit"), 'ln' : ln} return page(title = docFullDesc, body=t, navtrail=p_navtrail, description="submit documents", keywords="submit", uid=uid, language=ln, req=req, navmenuid='submit' ) def Request_Print(m, txt): """The argumemts to this function are the display mode (m) and the text to be displayed (txt). """ return txt def Evaluate_Parameter (field, doctype): # Returns the literal value of the parameter. Assumes that the value is # uniquely determined by the doctype, i.e. doctype is the primary key in # the table # If the table name is not null, evaluate the parameter ## TODO: The above comment looks like nonesense? This ## function only seems to get the values of parameters ## from the db... ## Get the value for the parameter: param_val = get_parameter_value_for_doctype(doctype, field) if param_val is None: ## Couldn't find a value for this parameter for this doctype. ## Instead, try with the default doctype (DEF): param_val = get_parameter_value_for_doctype("DEF", field) if param_val is None: ## There was no value for the parameter for the default doctype. ## Nothing can be done about it - return an empty string: return "" else: ## There was some kind of value for the parameter; return it: return param_val def Get_Parameters (function, doctype): """For a given function of a given document type, a dictionary of the parameter names and values are returned. @param function: (string) - the name of the function for which the parameters are to be retrieved. @param doctype: (string) - the ID of the document type. @return: (dictionary) - of the parameters of the function. Keyed by the parameter name, values are of course the parameter values. """ parray = {} ## Get the names of the parameters expected by this function: func_params = get_parameters_of_function(function) for func_param in func_params: ## For each of the parameters, get its value for this document- ## type and add it into the dictionary of parameters: parameter = func_param[0] parray[parameter] = Evaluate_Parameter (parameter, doctype) return parray def get_level(doctype, action): """Get the level of a given submission. If unknown, return 0 as the level. @param doctype: (string) - the ID of the document type. @param action: (string) - the ID of the action. @return: (integer) - the level of the submission; 0 otherwise. """ subm_details = get_details_of_submission(doctype, action) if subm_details is not None: ## Return the level of this action subm_level = subm_details[9] try: int(subm_level) except ValueError: return 0 else: return subm_level else: return 0 def action_details (doctype, action): # Prints whether the action is mandatory or optional. The score of the # action is returned (-1 if the action was optional) subm_details = get_details_of_submission(doctype, action) if subm_details is not None: if subm_details[9] != "0": ## This action is mandatory; return the score: return subm_details[10] else: return -1 else: return -1 def print_function_calls(req, doctype, action, step, form, start_time, access, curdir, dismode, rn, last_step, action_score, ln=CFG_SITE_LANG): """ Calls the functions required by an 'action' action on a 'doctype' document In supervisor mode, a table of the function calls is produced @return: (function_output_string, last_step, action_score, rn) """ user_info = collect_user_info(req) # load the right message language _ = gettext_set_language(ln) t = "" ## Here follows the global protect environment. the_globals = { 'doctype' : doctype, 'action' : action, 'act' : action, ## for backward compatibility 'step' : step, 'access' : access, 'ln' : ln, 'curdir' : curdir, 'uid' : user_info['uid'], 'uid_email' : user_info['email'], 'rn' : rn, 'last_step' : last_step, 'action_score' : action_score, '__websubmit_in_jail__' : True, 'form' : form, 'user_info' : user_info, '__builtins__' : globals()['__builtins__'], 'Request_Print': Request_Print } ## Get the list of functions to be called funcs_to_call = get_functions_for_submission_step(doctype, action, step) ## If no functions are found at this step for this doctype, ## get the functions for the DEF(ault) doctype: if len(funcs_to_call) == 0: funcs_to_call = get_functions_for_submission_step("DEF", action, step) if len(funcs_to_call) > 0: # while there are functions left... functions = [] for function in funcs_to_call: try: function_name = function[0] function_score = function[1] currfunction = { 'name' : function_name, 'score' : function_score, 'error' : 0, 'text' : '', } #FIXME: deprecated from invenio.legacy.websubmit import functions as legacy_functions function_path = os.path.join(legacy_functions.__path__[0], function_name + '.py') if os.path.exists(function_path): # import the function itself #function = getattr(invenio.legacy.websubmit.functions, function_name) execfile(function_path, the_globals) if function_name not in the_globals: currfunction['error'] = 1 else: the_globals['function'] = the_globals[function_name] # Evaluate the parameters, and place them in an array the_globals['parameters'] = Get_Parameters(function_name, doctype) # Call function: log_function(curdir, "Start %s" % function_name, start_time) try: try: ## Attempt to call the function with 4 arguments: ## ("parameters", "curdir" and "form" as usual), ## and "user_info" - the dictionary of user ## information: ## ## Note: The function should always be called with ## these keyword arguments because the "TypeError" ## except clause checks for a specific mention of ## the 'user_info' keyword argument when a legacy ## function (one that accepts only 'parameters', ## 'curdir' and 'form') has been called and if ## the error string doesn't contain this, ## the TypeError will be considered as a something ## that was incorrectly handled in the function and ## will be propagated as an ## InvenioWebSubmitFunctionError instead of the ## function being called again with the legacy 3 ## arguments. func_returnval = eval("function(parameters=parameters, curdir=curdir, form=form, user_info=user_info)", the_globals) except TypeError as err: ## If the error contains the string "got an ## unexpected keyword argument", it means that the ## function doesn't accept the "user_info" ## argument. Test for this: if "got an unexpected keyword argument 'user_info'" in \ str(err).lower(): ## As expected, the function doesn't accept ## the user_info keyword argument. Call it ## again with the legacy 3 arguments ## (parameters, curdir, form): func_returnval = eval("function(parameters=parameters, curdir=curdir, form=form)", the_globals) else: ## An unexpected "TypeError" was caught. ## It looks as though the function itself didn't ## handle something correctly. ## Convert this error into an ## InvenioWebSubmitFunctionError and raise it: msg = "Unhandled TypeError caught when " \ "calling [%s] WebSubmit function: " \ "[%s]: \n%s" % (function_name, str(err), traceback.format_exc()) raise InvenioWebSubmitFunctionError(msg) except InvenioWebSubmitFunctionWarning as err: ## There was an unexpected behaviour during the ## execution. Log the message into function's log ## and go to next function log_function(curdir, "***Warning*** from %s: %s" \ % (function_name, str(err)), start_time) ## Reset "func_returnval" to None: func_returnval = None register_exception(req=req, alert_admin=True, prefix="Warning in executing function %s with globals %s" % (pprint.pformat(currfunction), pprint.pformat(the_globals))) log_function(curdir, "End %s" % function_name, start_time) if func_returnval is not None: ## Append the returned value as a string: currfunction['text'] = str(func_returnval) else: ## The function the NoneType. Don't keep that value as ## the currfunction->text. Replace it with the empty ## string. currfunction['text'] = "" else: currfunction['error'] = 1 functions.append(currfunction) except InvenioWebSubmitFunctionStop as err: ## The submission asked to stop execution. This is ## ok. Do not alert admin, and raise exception further log_function(curdir, "***Stop*** from %s: %s" \ % (function_name, str(err)), start_time) raise except: register_exception(req=req, alert_admin=True, prefix="Error in executing function %s with globals %s" % (pprint.pformat(currfunction), pprint.pformat(the_globals))) raise t = websubmit_templates.tmpl_function_output( ln = ln, display_on = (dismode == 'S'), action = action, doctype = doctype, step = step, functions = functions, ) else : if dismode == 'S': t = "<br /><br /><b>" + _("The chosen action is not supported by the document type.") + "</b>" return (t, the_globals['last_step'], the_globals['action_score'], the_globals['rn']) def Propose_Next_Action (doctype, action_score, access, currentlevel, indir, ln=CFG_SITE_LANG): t = "" next_submissions = \ get_submissions_at_level_X_with_score_above_N(doctype, currentlevel, action_score) if len(next_submissions) > 0: actions = [] first_score = next_submissions[0][10] for action in next_submissions: if action[10] == first_score: ## Get the submission directory of this action: nextdir = get_storage_directory_of_action(action[1]) if nextdir is None: nextdir = "" curraction = { 'page' : action[11], 'action' : action[1], 'doctype' : doctype, 'nextdir' : nextdir, 'access' : access, 'indir' : indir, 'name' : action[12], } actions.append(curraction) t = websubmit_templates.tmpl_next_action( ln = ln, actions = actions, ) return t def specialchars(text): text = string.replace(text, "&#147;", "\042"); text = string.replace(text, "&#148;", "\042"); text = string.replace(text, "&#146;", "\047"); text = string.replace(text, "&#151;", "\055"); text = string.replace(text, "&#133;", "\056\056\056"); return text def log_function(curdir, message, start_time, filename="function_log"): """Write into file the message and the difference of time between starttime and current time @param curdir:(string) path to the destination dir @param message: (string) message to write into the file @param starttime: (float) time to compute from @param filname: (string) name of log file """ time_lap = "%.3f" % (time.time() - start_time) if os.access(curdir, os.F_OK|os.W_OK): fd = open("%s/%s" % (curdir, filename), "a+") fd.write("""%s --- %s\n""" % (message, time_lap)) fd.close()
gpl-2.0
mblondel/scikit-learn
sklearn/setup.py
24
2991
import os from os.path import join import warnings def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration from numpy.distutils.system_info import get_info, BlasNotFoundError import numpy libraries = [] if os.name == 'posix': libraries.append('m') config = Configuration('sklearn', parent_package, top_path) config.add_subpackage('__check_build') config.add_subpackage('svm') config.add_subpackage('datasets') config.add_subpackage('datasets/tests') config.add_subpackage('feature_extraction') config.add_subpackage('feature_extraction/tests') config.add_subpackage('cluster') config.add_subpackage('cluster/tests') config.add_subpackage('covariance') config.add_subpackage('covariance/tests') config.add_subpackage('cross_decomposition') config.add_subpackage('decomposition') config.add_subpackage('decomposition/tests') config.add_subpackage("ensemble") config.add_subpackage("ensemble/tests") config.add_subpackage('feature_selection') config.add_subpackage('feature_selection/tests') config.add_subpackage('utils') config.add_subpackage('utils/tests') config.add_subpackage('externals') config.add_subpackage('mixture') config.add_subpackage('mixture/tests') config.add_subpackage('gaussian_process') config.add_subpackage('gaussian_process/tests') config.add_subpackage('neighbors') config.add_subpackage('neural_network') config.add_subpackage('preprocessing') config.add_subpackage('manifold') config.add_subpackage('metrics') config.add_subpackage('semi_supervised') config.add_subpackage("tree") config.add_subpackage("tree/tests") config.add_subpackage('metrics/tests') config.add_subpackage('metrics/cluster') config.add_subpackage('metrics/cluster/tests') # add cython extension module for hmm config.add_extension( '_hmmc', sources=['_hmmc.c'], include_dirs=[numpy.get_include()], libraries=libraries, ) config.add_extension( '_isotonic', sources=['_isotonic.c'], include_dirs=[numpy.get_include()], libraries=libraries, ) # some libs needs cblas, fortran-compiled BLAS will not be sufficient blas_info = get_info('blas_opt', 0) if (not blas_info) or ( ('NO_ATLAS_INFO', 1) in blas_info.get('define_macros', [])): config.add_library('cblas', sources=[join('src', 'cblas', '*.c')]) warnings.warn(BlasNotFoundError.__doc__) # the following packages depend on cblas, so they have to be build # after the above. config.add_subpackage('linear_model') config.add_subpackage('utils') # add the test directory config.add_subpackage('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**configuration(top_path='').todict())
bsd-3-clause
vladikoff/fxa-mochitest
tests/venv/lib/python2.7/site-packages/mozlog/logger.py
46
6610
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from logging import getLogger as getSysLogger from logging import * # Some of the build slave environments don't see the following when doing # 'from logging import *' # see https://bugzilla.mozilla.org/show_bug.cgi?id=700415#c35 from logging import getLoggerClass, addLevelName, setLoggerClass, shutdown, debug, info, basicConfig import json _default_level = INFO _LoggerClass = getLoggerClass() # Define mozlog specific log levels START = _default_level + 1 END = _default_level + 2 PASS = _default_level + 3 KNOWN_FAIL = _default_level + 4 FAIL = _default_level + 5 CRASH = _default_level + 6 # Define associated text of log levels addLevelName(START, 'TEST-START') addLevelName(END, 'TEST-END') addLevelName(PASS, 'TEST-PASS') addLevelName(KNOWN_FAIL, 'TEST-KNOWN-FAIL') addLevelName(FAIL, 'TEST-UNEXPECTED-FAIL') addLevelName(CRASH, 'PROCESS-CRASH') class MozLogger(_LoggerClass): """ MozLogger class which adds some convenience log levels related to automated testing in Mozilla and ability to output structured log messages. """ def testStart(self, message, *args, **kwargs): """Logs a test start message""" self.log(START, message, *args, **kwargs) def testEnd(self, message, *args, **kwargs): """Logs a test end message""" self.log(END, message, *args, **kwargs) def testPass(self, message, *args, **kwargs): """Logs a test pass message""" self.log(PASS, message, *args, **kwargs) def testFail(self, message, *args, **kwargs): """Logs a test fail message""" self.log(FAIL, message, *args, **kwargs) def testKnownFail(self, message, *args, **kwargs): """Logs a test known fail message""" self.log(KNOWN_FAIL, message, *args, **kwargs) def processCrash(self, message, *args, **kwargs): """Logs a process crash message""" self.log(CRASH, message, *args, **kwargs) def log_structured(self, action, params=None): """Logs a structured message object.""" if params is None: params = {} level = params.get('_level', _default_level) if isinstance(level, int): params['_level'] = getLevelName(level) else: params['_level'] = level level = getLevelName(level.upper()) # If the logger is fed a level number unknown to the logging # module, getLevelName will return a string. Unfortunately, # the logging module will raise a type error elsewhere if # the level is not an integer. if not isinstance(level, int): level = _default_level params['action'] = action # The can message be None. This is expected, and shouldn't cause # unstructured formatters to fail. message = params.get('_message') self.log(level, message, extra={'params': params}) class JSONFormatter(Formatter): """Log formatter for emitting structured JSON entries.""" def format(self, record): # Default values determined by logger metadata output = { '_time': int(round(record.created * 1000, 0)), '_namespace': record.name, '_level': getLevelName(record.levelno), } # If this message was created by a call to log_structured, # anything specified by the caller's params should act as # an override. output.update(getattr(record, 'params', {})) if record.msg and output.get('_message') is None: # For compatibility with callers using the printf like # API exposed by python logging, call the default formatter. output['_message'] = Formatter.format(self, record) return json.dumps(output, indent=output.get('indent')) class MozFormatter(Formatter): """ MozFormatter class used to standardize formatting If a different format is desired, this can be explicitly overriden with the log handler's setFormatter() method """ level_length = 0 max_level_length = len('TEST-START') def __init__(self, include_timestamp=False): """ Formatter.__init__ has fmt and datefmt parameters that won't have any affect on a MozFormatter instance. :param include_timestamp: if True, include formatted time at the beginning of the message """ self.include_timestamp = include_timestamp Formatter.__init__(self) def format(self, record): # Handles padding so record levels align nicely if len(record.levelname) > self.level_length: pad = 0 if len(record.levelname) <= self.max_level_length: self.level_length = len(record.levelname) else: pad = self.level_length - len(record.levelname) + 1 sep = '|'.rjust(pad) fmt = '%(name)s %(levelname)s ' + sep + ' %(message)s' if self.include_timestamp: fmt = '%(asctime)s ' + fmt # this protected member is used to define the format # used by the base Formatter's method self._fmt = fmt return Formatter.format(self, record) def getLogger(name, handler=None): """ Returns the logger with the specified name. If the logger doesn't exist, it is created. If handler is specified, adds it to the logger. Otherwise a default handler that logs to standard output will be used. :param name: The name of the logger to retrieve :param handler: A handler to add to the logger. If the logger already exists, and a handler is specified, an exception will be raised. To add a handler to an existing logger, call that logger's addHandler method. """ setLoggerClass(MozLogger) if name in Logger.manager.loggerDict: if handler: raise ValueError('The handler parameter requires ' + \ 'that a logger by this name does ' + \ 'not already exist') return Logger.manager.loggerDict[name] logger = getSysLogger(name) logger.setLevel(_default_level) if handler is None: handler = StreamHandler() handler.setFormatter(MozFormatter()) logger.addHandler(handler) logger.propagate = False return logger
mpl-2.0
gymnasium/edx-platform
openedx/core/djangoapps/user_api/accounts/tests/test_permissions.py
9
2353
""" Tests for User deactivation API permissions """ from django.test import TestCase, RequestFactory from openedx.core.djangoapps.user_api.accounts.permissions import CanDeactivateUser, CanRetireUser from student.tests.factories import ContentTypeFactory, PermissionFactory, SuperuserFactory, UserFactory class CanDeactivateUserTest(TestCase): """ Tests for user deactivation API permissions """ def setUp(self): super(CanDeactivateUserTest, self).setUp() self.request = RequestFactory().get('/test/url') def test_api_permission_superuser(self): self.request.user = SuperuserFactory() result = CanDeactivateUser().has_permission(self.request, None) self.assertTrue(result) def test_api_permission_user_granted_permission(self): user = UserFactory() permission = PermissionFactory( codename='can_deactivate_users', content_type=ContentTypeFactory( app_label='student' ) ) user.user_permissions.add(permission) # pylint: disable=no-member self.request.user = user result = CanDeactivateUser().has_permission(self.request, None) self.assertTrue(result) def test_api_permission_user_without_permission(self): self.request.user = UserFactory() result = CanDeactivateUser().has_permission(self.request, None) self.assertFalse(result) class CanRetireUserTest(TestCase): """ Tests for user retirement API permissions """ def setUp(self): super(CanRetireUserTest, self).setUp() self.request = RequestFactory().get('/test/url') def test_api_permission_superuser(self): self.request.user = SuperuserFactory() result = CanRetireUser().has_permission(self.request, None) self.assertTrue(result) def test_api_permission_user_granted_permission(self): user = UserFactory() self.request.user = user with self.settings(RETIREMENT_SERVICE_WORKER_USERNAME=user.username): result = CanRetireUser().has_permission(self.request, None) self.assertTrue(result) def test_api_permission_user_without_permission(self): self.request.user = UserFactory() result = CanRetireUser().has_permission(self.request, None) self.assertFalse(result)
agpl-3.0
sorgerlab/belpy
indra/sources/trips/client.py
2
4754
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import re import sys import getopt import xml.dom.minidom import logging import requests logger = logging.getLogger(__name__) base_url = 'http://trips.ihmc.us/parser/cgi/' def send_query(text, service_endpoint='drum', query_args=None): """Send a query to the TRIPS web service. Parameters ---------- text : str The text to be processed. service_endpoint : Optional[str] Selects the TRIPS/DRUM web service endpoint to use. Is a choice between "drum" (default), "drum-dev", a nightly build, and "cwms" for use with more general knowledge extraction. query_args : Optional[dict] A dictionary of arguments to be passed with the query. Returns ------- html : str The HTML result returned by the web service. """ if service_endpoint in ['drum', 'drum-dev', 'cwms', 'cwmsreader']: url = base_url + service_endpoint else: logger.error('Invalid service endpoint: %s' % service_endpoint) return '' if query_args is None: query_args = {} query_args.update({'input': text}) res = requests.get(url, query_args, timeout=3600) if not res.status_code == 200: logger.error('Problem with TRIPS query: status code %s' % res.status_code) return '' # Gets unicode content return res.text def get_xml(html, content_tag='ekb', fail_if_empty=False): """Extract the content XML from the HTML output of the TRIPS web service. Parameters ---------- html : str The HTML output from the TRIPS web service. content_tag : str The xml tag used to label the content. Default is 'ekb'. fail_if_empty : bool If True, and if the xml content found is an empty string, raise an exception. Default is False. Returns ------- The extraction knowledge base (e.g. EKB) XML that contains the event and term extractions. """ cont = re.findall(r'<%(tag)s(.*?)>(.*?)</%(tag)s>' % {'tag': content_tag}, html, re.MULTILINE | re.DOTALL) if cont: events_terms = ''.join([l.strip() for l in cont[0][1].splitlines()]) if 'xmlns' in cont[0][0]: meta = ' '.join([l.strip() for l in cont[0][0].splitlines()]) else: meta = '' else: events_terms = '' meta = '' if fail_if_empty: assert events_terms != '',\ "Got empty string for events content from html:\n%s" % html header = ('<?xml version="1.0" encoding="utf-8" standalone="yes"?><%s%s>' % (content_tag, meta)) footer = '</%s>' % content_tag return header + events_terms.replace('\n', '') + footer def save_xml(xml_str, file_name, pretty=True): """Save the TRIPS EKB XML in a file. Parameters ---------- xml_str : str The TRIPS EKB XML string to be saved. file_name : str The name of the file to save the result in. pretty : Optional[bool] If True, the XML is pretty printed. """ try: fh = open(file_name, 'wt') except IOError: logger.error('Could not open %s for writing.' % file_name) return if pretty: xmld = xml.dom.minidom.parseString(xml_str) xml_str_pretty = xmld.toprettyxml() fh.write(xml_str_pretty) else: fh.write(xml_str) fh.close() if __name__ == '__main__': filemode = False text = 'Active BRAF phosphorylates MEK1 at Ser222.' outfile_name = 'braf_test.xml' opts, extraparams = getopt.getopt(sys.argv[1:], 's:f:o:h', ['string=', 'file=', 'output=', 'help']) for o, p in opts: if o in ['-h', '--help']: print('String mode: python -m indra.sources.trips.client.py ' '--string "RAS binds GTP" --output text.xml') print('File mode: python -m indra.sources.trips.client.py ' '--file test.txt --output text.xml') sys.exit() elif o in ['-s', '--string']: text = p elif o in ['-f', '--file']: filemode = True infile_name = p elif o in ['-o', '--output']: outfile_name = p if filemode: try: fh = open(infile_name, 'rt') except IOError: print('Could not open %s.' % infile_name) exit() text = fh.read() fh.close() print('Parsing contents of %s...' % infile_name) else: print('Parsing string: %s' % text) html = send_query(text) xml = get_xml(html) save_xml(xml, outfile_name)
mit
nginxxx/ansible
test/integration/setup_gce.py
163
1391
''' Create GCE resources for use in integration tests. Takes a prefix as a command-line argument and creates two persistent disks named ${prefix}-base and ${prefix}-extra and a snapshot of the base disk named ${prefix}-snapshot. prefix will be forced to lowercase, to ensure the names are legal GCE resource names. ''' import sys import optparse import gce_credentials def parse_args(): parser = optparse.OptionParser( usage="%s [options] <prefix>" % (sys.argv[0],), description=__doc__) gce_credentials.add_credentials_options(parser) parser.add_option("--prefix", action="store", dest="prefix", help="String used to prefix GCE resource names (default: %default)") (opts, args) = parser.parse_args() gce_credentials.check_required(opts, parser) if not args: parser.error("Missing required argument: name prefix") return (opts, args) if __name__ == '__main__': (opts, args) = parse_args() gce = gce_credentials.get_gce_driver(opts) prefix = args[0].lower() try: base_volume = gce.create_volume( size=10, name=prefix+'-base', location='us-central1-a') gce.create_volume_snapshot(base_volume, name=prefix+'-snapshot') gce.create_volume( size=10, name=prefix+'-extra', location='us-central1-a') except KeyboardInterrupt as e: print("\nExiting on user command.")
gpl-3.0
crypto101/merlyn
setup.py
1
2478
import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand from setuptools.command import egg_info packageName = "merlyn" dependencies = [ # Public API "clarent==0.1.0", # Base requirements, Twisted, TLS, AMP etc "twisted>=13.2.0", "pyOpenSSL>=0.13.1", "txampext>=0.0.10", "pycrypto", # (for manhole) "pyasn1", # (for manhole) # Storage "epsilon", "axiom>=0.7.0", "maxims>=0.0.2", ] import re versionLine = open("{0}/_version.py".format(packageName), "rt").read() match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", versionLine, re.M) versionString = match.group(1) class Tox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import tox sys.exit(tox.cmdline([])) def _topLevel(name): return name.split('.', 1)[0] def _hacked_write_toplevel_names(cmd, basename, filename): names = map(_topLevel, cmd.distribution.iter_distribution_names()) pkgs = dict.fromkeys(set(names) - set(["twisted"])) cmd.write_file("top-level names", filename, '\n'.join(pkgs) + '\n') egg_info.write_toplevel_names = _hacked_write_toplevel_names setup(name=packageName, version=versionString, description='A server backend for interactive online exercises.', long_description=open("README.rst").read(), url='https://github.com/crypto101/' + packageName, author='Laurens Van Houtven', author_email='_@lvh.io', packages=find_packages() + ['twisted.plugins'], test_suite=packageName + ".test", install_requires=dependencies, cmdclass={'test': Tox}, zip_safe=True, license='ISC', keywords="crypto twisted", classifiers=[ "Development Status :: 3 - Alpha", "Framework :: Twisted", "Intended Audience :: Education", "License :: OSI Approved :: ISC License (ISCL)", "Programming Language :: Python :: 2 :: Only", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Topic :: Education", "Topic :: Games/Entertainment", "Topic :: Security :: Cryptography", ] ) try: from twisted.plugin import IPlugin, getPlugins except ImportError: pass else: list(getPlugins(IPlugin))
isc
ratoaq2/Flexget
tests/test_assume_quality.py
12
5240
from __future__ import unicode_literals, division, absolute_import from tests import FlexGetBase, build_parser_function from nose.tools import assert_raises from flexget.task import TaskAbort import flexget.utils.qualities as qualities class BaseAssumeQuality(FlexGetBase): __yaml__ = """ templates: global: mock: - {title: 'Testfile[h264-720p]'} - {title: 'Testfile.1280x720'} - {title: 'Testfile.HDTV'} - {title: 'Testfile.cam'} - {title: 'Testfile.noquality'} - {title: 'Testfile.xvid.mp3'} accept_all: yes tasks: test_default: assume_quality: 720p: flac h264: 10bit HDTV: truehd any: 720p h264 test_simple: assume_quality: 720p h264 test_priority: assume_quality: 720p: mp3 720p h264: flac h264: mp3 test_matching: assume_quality: hdtv: 720p test_negative_matching: assume_quality: '!xvid !divx !mp3': 1080p test_no_clobber: assume_quality: 720p: xvid test_invalid_target: assume_quality: potato: 720p test_invalid_quality: assume_quality: hdtv: rhubarb test_with_series: template: no_global mock: - title: my show S01E01 hdtv assume_quality: 720p series: - my show: quality: 720p hdtv test_with_series_target: template: no_global mock: - title: my show S01E01 hdtv assume_quality: 720p series: - my show: target: 720p hdtv test_with_series_qualities: template: no_global mock: - title: my show S01E01 hdtv assume_quality: 720p series: - my show: qualities: [720p hdtv] """ def test_matching(self): self.execute_task('test_matching') entry = self.task.find_entry('entries', title='Testfile.HDTV') assert entry.get('quality') == qualities.Quality('720p HDTV') def test_negative_matching(self): self.execute_task('test_negative_matching') entry = self.task.find_entry('entries', title='Testfile.HDTV') assert entry.get('quality') == qualities.Quality('1080p HDTV') entry = self.task.find_entry('entries', title='Testfile.xvid.mp3') assert entry.get('quality') == qualities.Quality('xvid mp3') def test_no_clobber(self): self.execute_task('test_no_clobber') entry = self.task.find_entry('entries', title='Testfile[h264-720p]') assert entry.get('quality') != qualities.Quality('720p xvid') assert entry.get('quality') == qualities.Quality('720p h264') def test_default(self): self.execute_task('test_default') entry = self.task.find_entry('entries', title='Testfile.noquality') assert entry.get('quality') == qualities.Quality('720p h264'), 'Testfile.noquality quality not \'720p h264\'' def test_simple(self): self.execute_task('test_simple') entry = self.task.find_entry('entries', title='Testfile.noquality') assert entry.get('quality') == qualities.Quality('720p h264'), 'Testfile.noquality quality not \'720p h264\'' def test_priority(self): self.execute_task('test_priority') entry = self.task.find_entry('entries', title='Testfile[h264-720p]') assert entry.get('quality') != qualities.Quality('720p h264 mp3') assert entry.get('quality') == qualities.Quality('720p h264 flac') def test_invalid_target(self): #with assert_raises(TaskAbort): self.execute_task('test_invalid_target') #Requires Python 2.7 assert_raises(TaskAbort, self.execute_task, 'test_invalid_target') def test_invalid_quality(self): #with assert_raises(TaskAbort): self.execute_task('test_invalid_quality') #Requires Python 2.7 assert_raises(TaskAbort, self.execute_task, 'test_invalid_quality') def test_with_series(self): self.execute_task('test_with_series') assert self.task.accepted, 'series plugin should have used assumed quality' def test_with_series_target(self): self.execute_task('test_with_series_target') assert self.task.accepted, 'series plugin should have used assumed quality' def test_with_series_qualities(self): self.execute_task('test_with_series_qualities') assert self.task.accepted, 'series plugin should have used assumed quality' class TestGuessitAssumeQuality(BaseAssumeQuality): def __init__(self): super(TestGuessitAssumeQuality, self).__init__() self.add_tasks_function(build_parser_function('guessit')) class TestInternalAssumeQuality(BaseAssumeQuality): def __init__(self): super(TestInternalAssumeQuality, self).__init__() self.add_tasks_function(build_parser_function('internal'))
mit
okffi/booktype
lib/booktype/utils/config.py
1
4906
# This file is part of Booktype. # Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> # # Booktype is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Booktype is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Booktype. If not, see <http://www.gnu.org/licenses/>. import json import threading import tempfile import os import os.path from django.conf import settings from booki import constants writeLock = threading.RLock() class ConfigurationError(Exception): def __init__(self, description=''): self.description = description def __str__(self): return self.description def read_configuration(): """ Reads configuration file and returns content as a dictionary. @rtype: C{dict} @return: Returns dictionary with all the values """ configPath = '%s/configuration.json' % settings.BOOKI_ROOT try: f = open(configPath, 'r') data = f.read() f.close() except IOError: raise ConfigurationError("Can't read file %s." % configPath) except: raise ConfigurationError("Unknown error.") try: confData = json.loads(data) except: return None return confData def load_configuration(): """ Loads configuration. This function is supposed to be called from the settings.py file. try: BOOKTYPE_CONFIG = config.load_configuration() except config.ConfigurationError: BOOKTYPE_CONFIG = None @rtype: C{dict} @return: Returns dictionary with all the values """ data = read_configuration() return data def save_configuration(): """ Saves the configuration to file. Configuration data is taken from settings.BOOKTYPE_CONFIG variable. """ if not hasattr(settings, 'BOOKTYPE_CONFIG'): return False writeLock.acquire() data = settings.BOOKTYPE_CONFIG configPath = '%s/configuration.json' % settings.BOOKI_ROOT # check for errors jsonData = json.dumps(data) try: fh, fname = tempfile.mkstemp(suffix='', prefix='configuration', dir=settings.BOOKI_ROOT) f = open(fname, 'w+') f.write(jsonData.encode('utf8')) f.close() if os.path.exists(configPath): os.unlink(configPath) os.rename(fname, configPath) except IOError: raise ConfigurationError("Can't write to file %s." % configPath) except: raise ConfigurationError("Unknown error.") finally: writeLock.release() def get_configuration(name, value=None): """ Returns content of a configuration variable. It will first search in user defined configuration. If it can't find it it will go into settings file and finaly constant variables provided with Booktype source. @type name: C{string} @param: Name of the variable @type value: C{object} @param: Default value if it can't find defined variable. @type: C{object} @return: Returns the content of the variable """ # Check if we have it in the configuration file if hasattr(settings, 'BOOKTYPE_CONFIG'): try: settings.BOOKTYPE_CONFIG = load_configuration() except ConfigurationError: pass if settings.BOOKTYPE_CONFIG is not None and name in settings.BOOKTYPE_CONFIG: return settings.BOOKTYPE_CONFIG[name] # Check if we have it in the settings file if hasattr(settings, name): return getattr(settings, name) if hasattr(constants, name): return getattr(constants, name) return value def set_configuration(name, value): """ Sets value for configuration variable. @type name: C{string} @param: Name of the variable @type value: C{object} @param: Value for the variable """ writeLock.acquire() try: if hasattr(settings, 'BOOKTYPE_CONFIG'): if not settings.BOOKTYPE_CONFIG: settings.BOOKTYPE_CONFIG = {} settings.BOOKTYPE_CONFIG[name] = value setattr(settings, name, value) finally: writeLock.release() def del_configuration(name): """ Deletes configuration variable. @type name: C{string} @param: Name of the variable """ if hasattr(settings, 'BOOKTYPE_CONFIG'): writeLock.acquire() try: del settings.BOOKTYPE_CONFIG[name] finally: writeLock.release()
agpl-3.0
huangenyan/Lattish
project/validate_hand.py
1
9670
# -*- coding: utf-8 -*- """ Load tenhou replay and validate tenhou hand score with our own system score Input attribute is file name with tenhou.net log content. Validation working correctly only for phoenix replays, for kyu, first dan and second dan lobbys you need to set ids for hirosima, no red fives and no open tanyao games. """ import logging import sys import os from bs4 import BeautifulSoup from functools import reduce from mahjong.constants import EAST, SOUTH, WEST, NORTH from mahjong.hand import FinishedHand from mahjong.tile import TilesConverter from tenhou.decoder import TenhouDecoder from utils.settings_handler import settings logger = logging.getLogger('validate_hand') def load_content(file_name): with open(file_name, 'r') as f: content = f.read() os.remove(file_name) return content def set_up_logging(): """ Main logger for usual bot needs """ logger = logging.getLogger('validate_hand') logger.setLevel(logging.DEBUG) logs_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logs') if not os.path.exists(logs_directory): os.mkdir(logs_directory) file_name = 'validate_hand.log' fh = logging.FileHandler(os.path.join(logs_directory, file_name)) fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(message)s') fh.setFormatter(formatter) logger.addHandler(fh) def main(): if len(sys.argv) < 2: return False set_up_logging() file_name = sys.argv[1] content = load_content(file_name) TenhouLogParser().parse_log(content, file_name.split('.')[0].replace('temp/', '')) class TenhouLogParser(object): def parse_log(self, log_data, log_id): decoder = TenhouDecoder() finished_hand = FinishedHand() soup = BeautifulSoup(log_data, 'html.parser') elements = soup.find_all() settings.FIVE_REDS = True settings.OPEN_TANYAO = True total_hand = 0 successful_hand = 0 played_rounds = 0 dealer = 0 round_wind = EAST for tag in elements: if tag.name == 'go': game_rule_temp = int(tag.attrs['type']) # let's skip hirosima games hirosima = [177, 185, 241, 249] if game_rule_temp in hirosima: print('0,0') return # one round games skip_games = [2113] if game_rule_temp in skip_games: print('0,0') return no_red_five = [163, 167, 171, 175] if game_rule_temp in no_red_five: settings.FIVE_REDS = False no_open_tanyao = [167, 175] if game_rule_temp in no_open_tanyao: settings.OPEN_TANYAO = False if tag.name == 'taikyoku': dealer = int(tag.attrs['oya']) if tag.name == 'init': dealer = int(tag.attrs['oya']) seed = [int(i) for i in tag.attrs['seed'].split(',')] round_number = seed[0] if round_number < 4: round_wind = EAST elif 4 <= round_number < 8: round_wind = SOUTH elif 8 <= round_number < 12: round_wind = WEST else: round_wind = NORTH played_rounds += 1 if tag.name == 'agari': success = True winner = int(tag.attrs['who']) from_who = int(tag.attrs['fromwho']) closed_hand = [int(i) for i in tag.attrs['hai'].split(',')] ten = [int(i) for i in tag.attrs['ten'].split(',')] dora_indicators = [int(i) for i in tag.attrs['dorahai'].split(',')] if 'dorahaiura' in tag.attrs: dora_indicators += [int(i) for i in tag.attrs['dorahaiura'].split(',')] yaku_list = [] yakuman_list = [] if 'yaku' in tag.attrs: yaku_temp = [int(i) for i in tag.attrs['yaku'].split(',')] yaku_list = yaku_temp[::2] han = sum(yaku_temp[1::2]) else: yakuman_list = [int(i) for i in tag.attrs['yakuman'].split(',')] han = len(yakuman_list) * 13 fu = ten[0] cost = ten[1] melds = [] called_kan_indices = [] if 'm' in tag.attrs: for x in tag.attrs['m'].split(','): message = '<N who={} m={}>'.format(tag.attrs['who'], x) meld = decoder.parse_meld(message) tiles = meld.tiles if len(tiles) == 4: called_kan_indices.append(tiles[0]) tiles = tiles[1:4] # closed kan if meld.from_who == 0: closed_hand.extend(tiles) else: melds.append(tiles) hand = closed_hand if melds: hand += reduce(lambda z, y: z + y, melds) win_tile = int(tag.attrs['machi']) is_tsumo = winner == from_who is_riichi = 1 in yaku_list is_ippatsu = 2 in yaku_list is_chankan = 3 in yaku_list is_rinshan = 4 in yaku_list is_haitei = 5 in yaku_list is_houtei = 6 in yaku_list is_daburu_riichi = 21 in yaku_list is_dealer = winner == dealer is_renhou = 36 in yakuman_list is_tenhou = 37 in yakuman_list is_chiihou = 38 in yakuman_list dif = winner - dealer winds = [EAST, SOUTH, WEST, NORTH] player_wind = winds[dif] result = finished_hand.estimate_hand_value(hand, win_tile, is_tsumo=is_tsumo, is_riichi=is_riichi, is_dealer=is_dealer, is_ippatsu=is_ippatsu, is_rinshan=is_rinshan, is_chankan=is_chankan, is_haitei=is_haitei, is_houtei=is_houtei, is_daburu_riichi=is_daburu_riichi, is_tenhou=is_tenhou, is_renhou=is_renhou, is_chiihou=is_chiihou, round_wind=round_wind, player_wind=player_wind, called_kan_indices=called_kan_indices, open_sets=melds, dora_indicators=dora_indicators) if result['error']: logger.error('Error with hand calculation: {}'.format(result['error'])) calculated_cost = 0 success = False else: calculated_cost = result['cost']['main'] + result['cost']['additional'] * 2 if success: if result['fu'] != fu: logger.error('Wrong fu: {} != {}'.format(result['fu'], fu)) success = False if result['han'] != han: logger.error('Wrong han: {} != {}'.format(result['han'], han)) success = False if cost != calculated_cost: logger.error('Wrong cost: {} != {}'.format(cost, calculated_cost)) success = False if not success: logger.error('http://e.mjv.jp/0/log/?{}'.format(log_id)) logger.error('http://tenhou.net/0/?log={}&tw={}&ts={}'.format(log_id, winner, played_rounds - 1)) logger.error('Winner: {}, Dealer: {}'.format(winner, dealer)) logger.error('Hand: {}'.format(TilesConverter.to_one_line_string(hand))) logger.error('Win tile: {}'.format(TilesConverter.to_one_line_string([win_tile]))) logger.error('Open sets: {}'.format(melds)) logger.error('Called kans: {}'.format(TilesConverter.to_one_line_string(called_kan_indices))) logger.error('Our results: {}'.format(result)) logger.error('Tenhou results: {}'.format(tag.attrs)) logger.error('Dora: {}'.format(TilesConverter.to_one_line_string(dora_indicators))) logger.error('') else: successful_hand += 1 total_hand += 1 print('{},{}'.format(successful_hand, total_hand)) if __name__ == '__main__': main()
mit
vishnu2kmohan/dcos
packages/dcos-integration-test/extra/util/delete_ec2_volume.py
4
2682
#!/usr/bin/env python3 import contextlib import logging import os import sys import boto3 import botocore import requests import retrying from test_util.helpers import retry_boto_rate_limits @contextlib.contextmanager def _remove_env_vars(*env_vars): environ = dict(os.environ) for env_var in env_vars: try: del os.environ[env_var] except KeyError: pass try: yield finally: os.environ.clear() os.environ.update(environ) @retry_boto_rate_limits def delete_ec2_volume(name, timeout=300): """Delete an EC2 EBS volume by its "Name" tag Args: timeout: seconds to wait for volume to become available for deletion """ def _force_detach_volume(volume): for attachment in volume.attachments: volume.detach_from_instance( DryRun=False, InstanceId=attachment['InstanceId'], Device=attachment['Device'], Force=True) @retrying.retry(wait_fixed=30 * 1000, stop_max_delay=timeout * 1000, retry_on_exception=lambda exc: isinstance(exc, botocore.exceptions.ClientError)) def _delete_volume(volume): _force_detach_volume(volume) volume.delete() # Raises ClientError if the volume is still attached. def _get_current_aws_region(): try: return requests.get('http://169.254.169.254/latest/meta-data/placement/availability-zone').text.strip()[:-1] except requests.RequestException as ex: logging.warning("Can't get AWS region from instance metadata: {}".format(ex)) return None # Remove AWS environment variables to force boto to use IAM credentials. with _remove_env_vars('AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY'): volumes = list(boto3.session.Session( # We assume we're running these tests from a cluster node, so we # can assume the region for the instance on which we're running is # the same region in which any volumes were created. region_name=_get_current_aws_region(), ).resource('ec2').volumes.filter(Filters=[{'Name': 'tag:Name', 'Values': [name]}])) if len(volumes) == 0: raise Exception('no volumes found with name {}'.format(name)) elif len(volumes) > 1: raise Exception('multiple volumes found with name {}'.format(name)) volume = volumes[0] try: _delete_volume(volume) except retrying.RetryError as ex: raise Exception('Operation was not completed within {} seconds'.format(timeout)) from ex if __name__ == '__main__': delete_ec2_volume(sys.argv[1])
apache-2.0
doyousketch2/PixelDraw.py
pxl.py
1
6074
##========================================================= ## pxl.py 11 Mar 2017 ## ## turn pixels into polygons, from spritesheets to Blender ## ## Eli Leigh Innis ## Twitter : @ Doyousketch2 ## Email : Doyousketch2 @ yahoo.com ## ## GNU GPLv3 gnu.org/licenses/gpl-3.0.html ##========================================================= ## libs ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from time import time from math import floor ##========================================================= ## script ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ def draw(W, H, pixeldata, metadata, dimensions): looptimer = time() ## initialize timer array = list(pixeldata) ## convert raw pixeldata into an array newline = 1 vert = 1 ## vertex counter vertices = [] faces = ['\n\n'] foundcolors = [] colors = [] blendergrid = 16 ## 8 grid divisions in both directions from origin = 16 blenderunit = 100 ## .obj files apprently use centimeters, 100 = blenderunit maxwidth = blendergrid * blenderunit if W > H: scale = maxwidth / W else: scale = maxwidth / H halfpxl = scale / 2 offx = -scale * W / 2 offy = scale * H / 2 ## the default grid is +8 & -8, along X and Y. ## find the largest of those two (W or H) ## then use a scale-factor for the polygons ## to center pixels within that 16 blender-unit square ## metadata['alpha'] is either True or False if metadata['alpha']: bpp = 4 ## RGBA else: bpp = 3 ## RGB ## bpp = bits per plane # print(str(bpp)) # print(metadata) ## background = top-left corner pixel background = previousColor = [R, G, B] = array[0][0:3] print('\nWidth: %s, Height: %s, Background: r%s g%s b%s' % (W, H, R, G, B)) ##-------------------------------------v ## find number of colors C= 0 Y = 0 while Y < H: yy = array[Y] X = 0 while X < W: xx = X * bpp color = [R, G, B] = yy[xx : xx + 3] if color != background and color not in foundcolors: foundcolors .append(color) if C == 0: print('Found %s color' % C, end = '\r') else: print('Found %s colors' % C, end = '\r') C += 1 X += 1 Y += 1 print('Found %s colors (excluding background)\n' % len(foundcolors)) ##-------------------------------------^ ww = W / 2 hh = H / 2 C= 1 ## init loop counter numcolors = len(foundcolors) ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## main color loop for color in foundcolors: R, G, B = color ##-------------------------------------v ## looptimer to print info looptime = floor((time() - looptimer) * 100) / 100 if C == 1: print('Color: %s of: %s Init took: %s secs r%s g%s b%s' % (C, numcolors, looptime, R, G, B), end = '\r') else: print('Color: %s of: %s last color took: %s secs r%s g%s b%s' % (C, numcolors, looptime, R, G, B), end = '\r') # if looptime > 2: Y = H; continue ## break out of loop, for testing looptimer = time() ## re-init timer for next loop C += 1 ##------------------------------------- ## determine color info for this layer ## divide by 255 to convert colors from (0 - 255) range into (0 - 1) range ## floor(num * 100) / 100 drops digits off of floats to 2 decimal places rr = floor((R / 255) * 100) / 100 gg = floor((G / 255) * 100) / 100 bb = floor((B / 255) * 100) / 100 colorstring = 'r%s g%s b%s' % (R, G, B) colors .append('newmtl %s' % colorstring) colors .append('Kd %s %s %s\n' % (rr, gg, bb)) faces .append('usemtl %s' % colorstring) brightness = (R+R + G+G+G + B) / 6 ## our eyes are sensitive to shades of red and even moreso to green, ## so extra samples of them are taken when averaging luminosity value. ## stackoverflow.com/a/596241 using fast approximation Z = brightness / 50 zz = floor((Z / 10) * 10000) / 20 ##-------------------------------------v ## iterate through pixels Y = 0 while Y < H: yy = array[Y] X = 0 while X < W: ##if metadata['indexed']: ##index = array[Y][X] xx = X * bpp pxlcolor = yy[xx : xx + 3] if pxlcolor != color: previousColor = pxlcolor else: # print(str(X) + ', ' + str(Y) + ', ' + str(color)) offsetX = offx + X * scale offsetY = offy - Y * scale ## floor(num * 10000) / 10000 drops digits off of floats to 4 decimal places if pxlcolor == color and previousColor == pxlcolor and newline == 0: top = floor((offsetY + halfpxl) * 10000) / 10000 right = floor((offsetX + halfpxl) * 10000) / 10000 bottom = floor((offsetY - halfpxl) * 10000) / 10000 ## replace last two vertices in list, so we get RunLengthEncoding effect vertices[-2] = ('v %s %s %s' % (right, bottom, zz)) vertices[-1] = ('v %s %s %s' % (right, top, zz)) elif pxlcolor == color: newline = 0 top = floor((offsetY + halfpxl) * 10000) / 10000 left = floor((offsetX - halfpxl) * 10000) / 10000 right = floor((offsetX + halfpxl) * 10000) / 10000 bottom = floor((offsetY - halfpxl) * 10000) / 10000 vertices .append('v %s %s %s' % (left, top, zz)) vertices .append('v %s %s %s' % (left, bottom, zz)) vertices .append('v %s %s %s' % (right, bottom, zz)) vertices .append('v %s %s %s' % (right, top, zz)) faces .append('f %s %s %s %s' % (vert, vert + 1, vert + 2, vert + 3)) previousColor = pxlcolor vert += 4 X += 1 newline = 1 Y += 1 return vertices, faces, colors ##============================================================= ## eof ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gpl-3.0
NunoEdgarGub1/nupic
external/linux32/lib/python2.6/site-packages/matplotlib/projections/__init__.py
69
2179
from geo import AitoffAxes, HammerAxes, LambertAxes from polar import PolarAxes from matplotlib import axes class ProjectionRegistry(object): """ Manages the set of projections available to the system. """ def __init__(self): self._all_projection_types = {} def register(self, *projections): """ Register a new set of projection(s). """ for projection in projections: name = projection.name self._all_projection_types[name] = projection def get_projection_class(self, name): """ Get a projection class from its *name*. """ return self._all_projection_types[name] def get_projection_names(self): """ Get a list of the names of all projections currently registered. """ names = self._all_projection_types.keys() names.sort() return names projection_registry = ProjectionRegistry() projection_registry.register( axes.Axes, PolarAxes, AitoffAxes, HammerAxes, LambertAxes) def register_projection(cls): projection_registry.register(cls) def get_projection_class(projection=None): """ Get a projection class from its name. If *projection* is None, a standard rectilinear projection is returned. """ if projection is None: projection = 'rectilinear' try: return projection_registry.get_projection_class(projection) except KeyError: raise ValueError("Unknown projection '%s'" % projection) def projection_factory(projection, figure, rect, **kwargs): """ Get a new projection instance. *projection* is a projection name. *figure* is a figure to add the axes to. *rect* is a :class:`~matplotlib.transforms.Bbox` object specifying the location of the axes within the figure. Any other kwargs are passed along to the specific projection constructor being used. """ return get_projection_class(projection)(figure, rect, **kwargs) def get_projection_names(): """ Get a list of acceptable projection names. """ return projection_registry.get_projection_names()
gpl-3.0
xfournet/intellij-community
python/lib/Lib/site-packages/django/contrib/localflavor/au/forms.py
309
1629
""" Australian-specific Form helpers """ from django.core.validators import EMPTY_VALUES from django.forms import ValidationError from django.forms.fields import Field, RegexField, Select from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ import re PHONE_DIGITS_RE = re.compile(r'^(\d{10})$') class AUPostCodeField(RegexField): """Australian post code field.""" default_error_messages = { 'invalid': _('Enter a 4 digit post code.'), } def __init__(self, *args, **kwargs): super(AUPostCodeField, self).__init__(r'^\d{4}$', max_length=None, min_length=None, *args, **kwargs) class AUPhoneNumberField(Field): """Australian phone number field.""" default_error_messages = { 'invalid': u'Phone numbers must contain 10 digits.', } def clean(self, value): """ Validate a phone number. Strips parentheses, whitespace and hyphens. """ super(AUPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return u'' value = re.sub('(\(|\)|\s+|-)', '', smart_unicode(value)) phone_match = PHONE_DIGITS_RE.search(value) if phone_match: return u'%s' % phone_match.group(1) raise ValidationError(self.error_messages['invalid']) class AUStateSelect(Select): """ A Select widget that uses a list of Australian states/territories as its choices. """ def __init__(self, attrs=None): from au_states import STATE_CHOICES super(AUStateSelect, self).__init__(attrs, choices=STATE_CHOICES)
apache-2.0
Julian/home-assistant
homeassistant/components/sensor/sabnzbd.py
12
4178
""" Support for monitoring an SABnzbd NZB client. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.sabnzbd/ """ import logging from datetime import timedelta from homeassistant.helpers.entity import Entity from homeassistant.util import Throttle REQUIREMENTS = ['https://github.com/jamespcole/home-assistant-nzb-clients/' 'archive/616cad59154092599278661af17e2a9f2cf5e2a9.zip' '#python-sabnzbd==0.1'] SENSOR_TYPES = { 'current_status': ['Status', None], 'speed': ['Speed', 'MB/s'], 'queue_size': ['Queue', 'MB'], 'queue_remaining': ['Left', 'MB'], 'disk_size': ['Disk', 'GB'], 'disk_free': ['Disk Free', 'GB'], } _LOGGER = logging.getLogger(__name__) _THROTTLED_REFRESH = None # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the SABnzbd sensors.""" from pysabnzbd import SabnzbdApi, SabnzbdApiException api_key = config.get("api_key") base_url = config.get("base_url") name = config.get("name", "SABnzbd") if not base_url: _LOGGER.error('Missing config variable base_url') return False if not api_key: _LOGGER.error('Missing config variable api_key') return False sab_api = SabnzbdApi(base_url, api_key) try: sab_api.check_available() except SabnzbdApiException: _LOGGER.exception("Connection to SABnzbd API failed.") return False # pylint: disable=global-statement global _THROTTLED_REFRESH _THROTTLED_REFRESH = Throttle(timedelta(seconds=1))(sab_api.refresh_queue) dev = [] for variable in config['monitored_variables']: if variable['type'] not in SENSOR_TYPES: _LOGGER.error('Sensor type: "%s" does not exist', variable['type']) else: dev.append(SabnzbdSensor(variable['type'], sab_api, name)) add_devices(dev) class SabnzbdSensor(Entity): """Representation of an SABnzbd sensor.""" def __init__(self, sensor_type, sabnzb_client, client_name): """Initialize the sensor.""" self._name = SENSOR_TYPES[sensor_type][0] self.sabnzb_client = sabnzb_client self.type = sensor_type self.client_name = client_name self._state = None self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] @property def name(self): """Return the name of the sensor.""" return self.client_name + ' ' + self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return self._unit_of_measurement def refresh_sabnzbd_data(self): """Call the throttled SABnzbd refresh method.""" if _THROTTLED_REFRESH is not None: from pysabnzbd import SabnzbdApiException try: _THROTTLED_REFRESH() except SabnzbdApiException: _LOGGER.exception( self.name + " Connection to SABnzbd API failed." ) def update(self): """Get the latest data and updates the states.""" self.refresh_sabnzbd_data() if self.sabnzb_client.queue: if self.type == 'current_status': self._state = self.sabnzb_client.queue.get('status') elif self.type == 'speed': mb_spd = float(self.sabnzb_client.queue.get('kbpersec')) / 1024 self._state = round(mb_spd, 1) elif self.type == 'queue_size': self._state = self.sabnzb_client.queue.get('mb') elif self.type == 'queue_remaining': self._state = self.sabnzb_client.queue.get('mbleft') elif self.type == 'disk_size': self._state = self.sabnzb_client.queue.get('diskspacetotal1') elif self.type == 'disk_free': self._state = self.sabnzb_client.queue.get('diskspace1') else: self._state = 'Unknown'
mit
tinchoss/Python_Android
python-build/python-libs/xmpppy/xmpp/commands.py
200
16116
## $Id: commands.py,v 1.17 2007/08/28 09:54:15 normanr Exp $ ## Ad-Hoc Command manager ## Mike Albon (c) 5th January 2005 ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2, or (at your option) ## any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. """This module is a ad-hoc command processor for xmpppy. It uses the plug-in mechanism like most of the core library. It depends on a DISCO browser manager. There are 3 classes here, a command processor Commands like the Browser, and a command template plugin Command, and an example command. To use this module: Instansiate the module with the parent transport and disco browser manager as parameters. 'Plug in' commands using the command template. The command feature must be added to existing disco replies where neccessary. What it supplies: Automatic command registration with the disco browser manager. Automatic listing of commands in the public command list. A means of handling requests, by redirection though the command manager. """ from protocol import * from client import PlugIn class Commands(PlugIn): """Commands is an ancestor of PlugIn and can be attached to any session. The commands class provides a lookup and browse mechnism. It follows the same priciple of the Browser class, for Service Discovery to provide the list of commands, it adds the 'list' disco type to your existing disco handler function. How it works: The commands are added into the existing Browser on the correct nodes. When the command list is built the supplied discovery handler function needs to have a 'list' option in type. This then gets enumerated, all results returned as None are ignored. The command executed is then called using it's Execute method. All session management is handled by the command itself. """ def __init__(self, browser): """Initialises class and sets up local variables""" PlugIn.__init__(self) DBG_LINE='commands' self._exported_methods=[] self._handlers={'':{}} self._browser = browser def plugin(self, owner): """Makes handlers within the session""" # Plug into the session and the disco manager # We only need get and set, results are not needed by a service provider, only a service user. owner.RegisterHandler('iq',self._CommandHandler,typ='set',ns=NS_COMMANDS) owner.RegisterHandler('iq',self._CommandHandler,typ='get',ns=NS_COMMANDS) self._browser.setDiscoHandler(self._DiscoHandler,node=NS_COMMANDS,jid='') def plugout(self): """Removes handlers from the session""" # unPlug from the session and the disco manager self._owner.UnregisterHandler('iq',self._CommandHandler,ns=NS_COMMANDS) for jid in self._handlers: self._browser.delDiscoHandler(self._DiscoHandler,node=NS_COMMANDS) def _CommandHandler(self,conn,request): """The internal method to process the routing of command execution requests""" # This is the command handler itself. # We must: # Pass on command execution to command handler # (Do we need to keep session details here, or can that be done in the command?) jid = str(request.getTo()) try: node = request.getTagAttr('command','node') except: conn.send(Error(request,ERR_BAD_REQUEST)) raise NodeProcessed if self._handlers.has_key(jid): if self._handlers[jid].has_key(node): self._handlers[jid][node]['execute'](conn,request) else: conn.send(Error(request,ERR_ITEM_NOT_FOUND)) raise NodeProcessed elif self._handlers[''].has_key(node): self._handlers[''][node]['execute'](conn,request) else: conn.send(Error(request,ERR_ITEM_NOT_FOUND)) raise NodeProcessed def _DiscoHandler(self,conn,request,typ): """The internal method to process service discovery requests""" # This is the disco manager handler. if typ == 'items': # We must: # Generate a list of commands and return the list # * This handler does not handle individual commands disco requests. # Pseudo: # Enumerate the 'item' disco of each command for the specified jid # Build responce and send # To make this code easy to write we add an 'list' disco type, it returns a tuple or 'none' if not advertised list = [] items = [] jid = str(request.getTo()) # Get specific jid based results if self._handlers.has_key(jid): for each in self._handlers[jid].keys(): items.append((jid,each)) else: # Get generic results for each in self._handlers[''].keys(): items.append(('',each)) if items != []: for each in items: i = self._handlers[each[0]][each[1]]['disco'](conn,request,'list') if i != None: list.append(Node(tag='item',attrs={'jid':i[0],'node':i[1],'name':i[2]})) iq = request.buildReply('result') if request.getQuerynode(): iq.setQuerynode(request.getQuerynode()) iq.setQueryPayload(list) conn.send(iq) else: conn.send(Error(request,ERR_ITEM_NOT_FOUND)) raise NodeProcessed elif typ == 'info': return {'ids':[{'category':'automation','type':'command-list'}],'features':[]} def addCommand(self,name,cmddisco,cmdexecute,jid=''): """The method to call if adding a new command to the session, the requred parameters of cmddisco and cmdexecute are the methods to enable that command to be executed""" # This command takes a command object and the name of the command for registration # We must: # Add item into disco # Add item into command list if not self._handlers.has_key(jid): self._handlers[jid]={} self._browser.setDiscoHandler(self._DiscoHandler,node=NS_COMMANDS,jid=jid) if self._handlers[jid].has_key(name): raise NameError,'Command Exists' else: self._handlers[jid][name]={'disco':cmddisco,'execute':cmdexecute} # Need to add disco stuff here self._browser.setDiscoHandler(cmddisco,node=name,jid=jid) def delCommand(self,name,jid=''): """Removed command from the session""" # This command takes a command object and the name used for registration # We must: # Remove item from disco # Remove item from command list if not self._handlers.has_key(jid): raise NameError,'Jid not found' if not self._handlers[jid].has_key(name): raise NameError, 'Command not found' else: #Do disco removal here command = self.getCommand(name,jid)['disco'] del self._handlers[jid][name] self._browser.delDiscoHandler(command,node=name,jid=jid) def getCommand(self,name,jid=''): """Returns the command tuple""" # This gets the command object with name # We must: # Return item that matches this name if not self._handlers.has_key(jid): raise NameError,'Jid not found' elif not self._handlers[jid].has_key(name): raise NameError,'Command not found' else: return self._handlers[jid][name] class Command_Handler_Prototype(PlugIn): """This is a prototype command handler, as each command uses a disco method and execute method you can implement it any way you like, however this is my first attempt at making a generic handler that you can hang process stages on too. There is an example command below. The parameters are as follows: name : the name of the command within the jabber environment description : the natural language description discofeatures : the features supported by the command initial : the initial command in the from of {'execute':commandname} All stages set the 'actions' dictionary for each session to represent the possible options available. """ name = 'examplecommand' count = 0 description = 'an example command' discofeatures = [NS_COMMANDS,NS_DATA] # This is the command template def __init__(self,jid=''): """Set up the class""" PlugIn.__init__(self) DBG_LINE='command' self.sessioncount = 0 self.sessions = {} # Disco information for command list pre-formatted as a tuple self.discoinfo = {'ids':[{'category':'automation','type':'command-node','name':self.description}],'features': self.discofeatures} self._jid = jid def plugin(self,owner): """Plug command into the commands class""" # The owner in this instance is the Command Processor self._commands = owner self._owner = owner._owner self._commands.addCommand(self.name,self._DiscoHandler,self.Execute,jid=self._jid) def plugout(self): """Remove command from the commands class""" self._commands.delCommand(self.name,self._jid) def getSessionID(self): """Returns an id for the command session""" self.count = self.count+1 return 'cmd-%s-%d'%(self.name,self.count) def Execute(self,conn,request): """The method that handles all the commands, and routes them to the correct method for that stage.""" # New request or old? try: session = request.getTagAttr('command','sessionid') except: session = None try: action = request.getTagAttr('command','action') except: action = None if action == None: action = 'execute' # Check session is in session list if self.sessions.has_key(session): if self.sessions[session]['jid']==request.getFrom(): # Check action is vaild if self.sessions[session]['actions'].has_key(action): # Execute next action self.sessions[session]['actions'][action](conn,request) else: # Stage not presented as an option self._owner.send(Error(request,ERR_BAD_REQUEST)) raise NodeProcessed else: # Jid and session don't match. Go away imposter self._owner.send(Error(request,ERR_BAD_REQUEST)) raise NodeProcessed elif session != None: # Not on this sessionid you won't. self._owner.send(Error(request,ERR_BAD_REQUEST)) raise NodeProcessed else: # New session self.initial[action](conn,request) def _DiscoHandler(self,conn,request,type): """The handler for discovery events""" if type == 'list': return (request.getTo(),self.name,self.description) elif type == 'items': return [] elif type == 'info': return self.discoinfo class TestCommand(Command_Handler_Prototype): """ Example class. You should read source if you wish to understate how it works. Generally, it presents a "master" that giudes user through to calculate something. """ name = 'testcommand' description = 'a noddy example command' def __init__(self,jid=''): """ Init internal constants. """ Command_Handler_Prototype.__init__(self,jid) self.initial = {'execute':self.cmdFirstStage} def cmdFirstStage(self,conn,request): """ Determine """ # This is the only place this should be repeated as all other stages should have SessionIDs try: session = request.getTagAttr('command','sessionid') except: session = None if session == None: session = self.getSessionID() self.sessions[session]={'jid':request.getFrom(),'actions':{'cancel':self.cmdCancel,'next':self.cmdSecondStage,'execute':self.cmdSecondStage},'data':{'type':None}} # As this is the first stage we only send a form reply = request.buildReply('result') form = DataForm(title='Select type of operation',data=['Use the combobox to select the type of calculation you would like to do, then click Next',DataField(name='calctype',desc='Calculation Type',value=self.sessions[session]['data']['type'],options=[['circlediameter','Calculate the Diameter of a circle'],['circlearea','Calculate the area of a circle']],typ='list-single',required=1)]) replypayload = [Node('actions',attrs={'execute':'next'},payload=[Node('next')]),form] reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':session,'status':'executing'},payload=replypayload) self._owner.send(reply) raise NodeProcessed def cmdSecondStage(self,conn,request): form = DataForm(node = request.getTag(name='command').getTag(name='x',namespace=NS_DATA)) self.sessions[request.getTagAttr('command','sessionid')]['data']['type']=form.getField('calctype').getValue() self.sessions[request.getTagAttr('command','sessionid')]['actions']={'cancel':self.cmdCancel,None:self.cmdThirdStage,'previous':self.cmdFirstStage,'execute':self.cmdThirdStage,'next':self.cmdThirdStage} # The form generation is split out to another method as it may be called by cmdThirdStage self.cmdSecondStageReply(conn,request) def cmdSecondStageReply(self,conn,request): reply = request.buildReply('result') form = DataForm(title = 'Enter the radius', data=['Enter the radius of the circle (numbers only)',DataField(desc='Radius',name='radius',typ='text-single')]) replypayload = [Node('actions',attrs={'execute':'complete'},payload=[Node('complete'),Node('prev')]),form] reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':request.getTagAttr('command','sessionid'),'status':'executing'},payload=replypayload) self._owner.send(reply) raise NodeProcessed def cmdThirdStage(self,conn,request): form = DataForm(node = request.getTag(name='command').getTag(name='x',namespace=NS_DATA)) try: num = float(form.getField('radius').getValue()) except: self.cmdSecondStageReply(conn,request) from math import pi if self.sessions[request.getTagAttr('command','sessionid')]['data']['type'] == 'circlearea': result = (num**2)*pi else: result = num*2*pi reply = request.buildReply('result') form = DataForm(typ='result',data=[DataField(desc='result',name='result',value=result)]) reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':request.getTagAttr('command','sessionid'),'status':'completed'},payload=[form]) self._owner.send(reply) raise NodeProcessed def cmdCancel(self,conn,request): reply = request.buildReply('result') reply.addChild(name='command',namespace=NS_COMMANDS,attrs={'node':request.getTagAttr('command','node'),'sessionid':request.getTagAttr('command','sessionid'),'status':'cancelled'}) self._owner.send(reply) del self.sessions[request.getTagAttr('command','sessionid')]
apache-2.0
alex/django-old
django/core/files/temp.py
536
1819
""" The temp module provides a NamedTemporaryFile that can be re-opened on any platform. Most platforms use the standard Python tempfile.TemporaryFile class, but MS Windows users are given a custom class. This is needed because in Windows NT, the default implementation of NamedTemporaryFile uses the O_TEMPORARY flag, and thus cannot be reopened [1]. 1: http://mail.python.org/pipermail/python-list/2005-December/359474.html """ import os import tempfile from django.core.files.utils import FileProxyMixin __all__ = ('NamedTemporaryFile', 'gettempdir',) if os.name == 'nt': class TemporaryFile(FileProxyMixin): """ Temporary file object constructor that works in Windows and supports reopening of the temporary file in windows. """ def __init__(self, mode='w+b', bufsize=-1, suffix='', prefix='', dir=None): fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir) self.name = name self.file = os.fdopen(fd, mode, bufsize) self.close_called = False # Because close can be called during shutdown # we need to cache os.unlink and access it # as self.unlink only unlink = os.unlink def close(self): if not self.close_called: self.close_called = True try: self.file.close() except (OSError, IOError): pass try: self.unlink(self.name) except (OSError): pass def __del__(self): self.close() NamedTemporaryFile = TemporaryFile else: NamedTemporaryFile = tempfile.NamedTemporaryFile gettempdir = tempfile.gettempdir
bsd-3-clause
groschovskiy/personfinder
app/unidecode/x057.py
252
4631
data = ( 'Guo ', # 0x00 'Yin ', # 0x01 'Hun ', # 0x02 'Pu ', # 0x03 'Yu ', # 0x04 'Han ', # 0x05 'Yuan ', # 0x06 'Lun ', # 0x07 'Quan ', # 0x08 'Yu ', # 0x09 'Qing ', # 0x0a 'Guo ', # 0x0b 'Chuan ', # 0x0c 'Wei ', # 0x0d 'Yuan ', # 0x0e 'Quan ', # 0x0f 'Ku ', # 0x10 'Fu ', # 0x11 'Yuan ', # 0x12 'Yuan ', # 0x13 'E ', # 0x14 'Tu ', # 0x15 'Tu ', # 0x16 'Tu ', # 0x17 'Tuan ', # 0x18 'Lue ', # 0x19 'Hui ', # 0x1a 'Yi ', # 0x1b 'Yuan ', # 0x1c 'Luan ', # 0x1d 'Luan ', # 0x1e 'Tu ', # 0x1f 'Ya ', # 0x20 'Tu ', # 0x21 'Ting ', # 0x22 'Sheng ', # 0x23 'Pu ', # 0x24 'Lu ', # 0x25 'Iri ', # 0x26 'Ya ', # 0x27 'Zai ', # 0x28 'Wei ', # 0x29 'Ge ', # 0x2a 'Yu ', # 0x2b 'Wu ', # 0x2c 'Gui ', # 0x2d 'Pi ', # 0x2e 'Yi ', # 0x2f 'Di ', # 0x30 'Qian ', # 0x31 'Qian ', # 0x32 'Zhen ', # 0x33 'Zhuo ', # 0x34 'Dang ', # 0x35 'Qia ', # 0x36 'Akutsu ', # 0x37 'Yama ', # 0x38 'Kuang ', # 0x39 'Chang ', # 0x3a 'Qi ', # 0x3b 'Nie ', # 0x3c 'Mo ', # 0x3d 'Ji ', # 0x3e 'Jia ', # 0x3f 'Zhi ', # 0x40 'Zhi ', # 0x41 'Ban ', # 0x42 'Xun ', # 0x43 'Tou ', # 0x44 'Qin ', # 0x45 'Fen ', # 0x46 'Jun ', # 0x47 'Keng ', # 0x48 'Tun ', # 0x49 'Fang ', # 0x4a 'Fen ', # 0x4b 'Ben ', # 0x4c 'Tan ', # 0x4d 'Kan ', # 0x4e 'Pi ', # 0x4f 'Zuo ', # 0x50 'Keng ', # 0x51 'Bi ', # 0x52 'Xing ', # 0x53 'Di ', # 0x54 'Jing ', # 0x55 'Ji ', # 0x56 'Kuai ', # 0x57 'Di ', # 0x58 'Jing ', # 0x59 'Jian ', # 0x5a 'Tan ', # 0x5b 'Li ', # 0x5c 'Ba ', # 0x5d 'Wu ', # 0x5e 'Fen ', # 0x5f 'Zhui ', # 0x60 'Po ', # 0x61 'Pan ', # 0x62 'Tang ', # 0x63 'Kun ', # 0x64 'Qu ', # 0x65 'Tan ', # 0x66 'Zhi ', # 0x67 'Tuo ', # 0x68 'Gan ', # 0x69 'Ping ', # 0x6a 'Dian ', # 0x6b 'Gua ', # 0x6c 'Ni ', # 0x6d 'Tai ', # 0x6e 'Pi ', # 0x6f 'Jiong ', # 0x70 'Yang ', # 0x71 'Fo ', # 0x72 'Ao ', # 0x73 'Liu ', # 0x74 'Qiu ', # 0x75 'Mu ', # 0x76 'Ke ', # 0x77 'Gou ', # 0x78 'Xue ', # 0x79 'Ba ', # 0x7a 'Chi ', # 0x7b 'Che ', # 0x7c 'Ling ', # 0x7d 'Zhu ', # 0x7e 'Fu ', # 0x7f 'Hu ', # 0x80 'Zhi ', # 0x81 'Chui ', # 0x82 'La ', # 0x83 'Long ', # 0x84 'Long ', # 0x85 'Lu ', # 0x86 'Ao ', # 0x87 'Tay ', # 0x88 'Pao ', # 0x89 '[?] ', # 0x8a 'Xing ', # 0x8b 'Dong ', # 0x8c 'Ji ', # 0x8d 'Ke ', # 0x8e 'Lu ', # 0x8f 'Ci ', # 0x90 'Chi ', # 0x91 'Lei ', # 0x92 'Gai ', # 0x93 'Yin ', # 0x94 'Hou ', # 0x95 'Dui ', # 0x96 'Zhao ', # 0x97 'Fu ', # 0x98 'Guang ', # 0x99 'Yao ', # 0x9a 'Duo ', # 0x9b 'Duo ', # 0x9c 'Gui ', # 0x9d 'Cha ', # 0x9e 'Yang ', # 0x9f 'Yin ', # 0xa0 'Fa ', # 0xa1 'Gou ', # 0xa2 'Yuan ', # 0xa3 'Die ', # 0xa4 'Xie ', # 0xa5 'Ken ', # 0xa6 'Jiong ', # 0xa7 'Shou ', # 0xa8 'E ', # 0xa9 'Ha ', # 0xaa 'Dian ', # 0xab 'Hong ', # 0xac 'Wu ', # 0xad 'Kua ', # 0xae '[?] ', # 0xaf 'Tao ', # 0xb0 'Dang ', # 0xb1 'Kai ', # 0xb2 'Gake ', # 0xb3 'Nao ', # 0xb4 'An ', # 0xb5 'Xing ', # 0xb6 'Xian ', # 0xb7 'Huan ', # 0xb8 'Bang ', # 0xb9 'Pei ', # 0xba 'Ba ', # 0xbb 'Yi ', # 0xbc 'Yin ', # 0xbd 'Han ', # 0xbe 'Xu ', # 0xbf 'Chui ', # 0xc0 'Cen ', # 0xc1 'Geng ', # 0xc2 'Ai ', # 0xc3 'Peng ', # 0xc4 'Fang ', # 0xc5 'Que ', # 0xc6 'Yong ', # 0xc7 'Xun ', # 0xc8 'Jia ', # 0xc9 'Di ', # 0xca 'Mai ', # 0xcb 'Lang ', # 0xcc 'Xuan ', # 0xcd 'Cheng ', # 0xce 'Yan ', # 0xcf 'Jin ', # 0xd0 'Zhe ', # 0xd1 'Lei ', # 0xd2 'Lie ', # 0xd3 'Bu ', # 0xd4 'Cheng ', # 0xd5 'Gomi ', # 0xd6 'Bu ', # 0xd7 'Shi ', # 0xd8 'Xun ', # 0xd9 'Guo ', # 0xda 'Jiong ', # 0xdb 'Ye ', # 0xdc 'Nian ', # 0xdd 'Di ', # 0xde 'Yu ', # 0xdf 'Bu ', # 0xe0 'Ya ', # 0xe1 'Juan ', # 0xe2 'Sui ', # 0xe3 'Pi ', # 0xe4 'Cheng ', # 0xe5 'Wan ', # 0xe6 'Ju ', # 0xe7 'Lun ', # 0xe8 'Zheng ', # 0xe9 'Kong ', # 0xea 'Chong ', # 0xeb 'Dong ', # 0xec 'Dai ', # 0xed 'Tan ', # 0xee 'An ', # 0xef 'Cai ', # 0xf0 'Shu ', # 0xf1 'Beng ', # 0xf2 'Kan ', # 0xf3 'Zhi ', # 0xf4 'Duo ', # 0xf5 'Yi ', # 0xf6 'Zhi ', # 0xf7 'Yi ', # 0xf8 'Pei ', # 0xf9 'Ji ', # 0xfa 'Zhun ', # 0xfb 'Qi ', # 0xfc 'Sao ', # 0xfd 'Ju ', # 0xfe 'Ni ', # 0xff )
apache-2.0
jarvys/django-1.7-jdb
django/core/management/sql.py
49
11292
from __future__ import unicode_literals import codecs import os import re import warnings from django.apps import apps from django.conf import settings from django.core.management.base import CommandError from django.db import models, router from django.utils.deprecation import RemovedInDjango19Warning def check_for_migrations(app_config, connection): # Inner import, else tests imports it too early as it needs settings from django.db.migrations.loader import MigrationLoader loader = MigrationLoader(connection) if app_config.label in loader.migrated_apps: raise CommandError("App '%s' has migrations. Only the sqlmigrate and sqlflush commands can be used when an app has migrations." % app_config.label) def sql_create(app_config, style, connection): "Returns a list of the CREATE TABLE SQL statements for the given app." check_for_migrations(app_config, connection) if connection.settings_dict['ENGINE'] == 'django.db.backends.dummy': # This must be the "dummy" database backend, which means the user # hasn't set ENGINE for the database. raise CommandError("Django doesn't know which syntax to use for your SQL statements,\n" + "because you haven't properly specified the ENGINE setting for the database.\n" + "see: https://docs.djangoproject.com/en/dev/ref/settings/#databases") # Get installed models, so we generate REFERENCES right. # We trim models from the current app so that the sqlreset command does not # generate invalid SQL (leaving models out of known_models is harmless, so # we can be conservative). app_models = list(app_config.get_models(include_auto_created=True)) final_output = [] tables = connection.introspection.table_names() known_models = set(model for model in connection.introspection.installed_models(tables) if model not in app_models) pending_references = {} for model in router.get_migratable_models(app_config, connection.alias, include_auto_created=True): output, references = connection.creation.sql_create_model(model, style, known_models) final_output.extend(output) for refto, refs in references.items(): pending_references.setdefault(refto, []).extend(refs) if refto in known_models: final_output.extend(connection.creation.sql_for_pending_references(refto, style, pending_references)) final_output.extend(connection.creation.sql_for_pending_references(model, style, pending_references)) # Keep track of the fact that we've created the table for this model. known_models.add(model) # Handle references to tables that are from other apps # but don't exist physically. not_installed_models = set(pending_references.keys()) if not_installed_models: alter_sql = [] for model in not_installed_models: alter_sql.extend(['-- ' + sql for sql in connection.creation.sql_for_pending_references(model, style, pending_references)]) if alter_sql: final_output.append('-- The following references should be added but depend on non-existent tables:') final_output.extend(alter_sql) return final_output def sql_delete(app_config, style, connection, close_connection=True): "Returns a list of the DROP TABLE SQL statements for the given app." check_for_migrations(app_config, connection) # This should work even if a connection isn't available try: cursor = connection.cursor() except Exception: cursor = None try: # Figure out which tables already exist if cursor: table_names = connection.introspection.table_names(cursor) else: table_names = [] output = [] # Output DROP TABLE statements for standard application tables. to_delete = set() references_to_delete = {} app_models = router.get_migratable_models(app_config, connection.alias, include_auto_created=True) for model in app_models: if cursor and connection.introspection.table_name_converter(model._meta.db_table) in table_names: # The table exists, so it needs to be dropped opts = model._meta for f in opts.local_fields: if f.rel and f.rel.to not in to_delete: references_to_delete.setdefault(f.rel.to, []).append((model, f)) to_delete.add(model) for model in app_models: if connection.introspection.table_name_converter(model._meta.db_table) in table_names: output.extend(connection.creation.sql_destroy_model(model, references_to_delete, style)) finally: # Close database connection explicitly, in case this output is being piped # directly into a database client, to avoid locking issues. if cursor and close_connection: cursor.close() connection.close() return output[::-1] # Reverse it, to deal with table dependencies. def sql_flush(style, connection, only_django=False, reset_sequences=True, allow_cascade=False): """ Returns a list of the SQL statements used to flush the database. If only_django is True, then only table names that have associated Django models and are in INSTALLED_APPS will be included. """ if only_django: tables = connection.introspection.django_table_names(only_existing=True) else: tables = connection.introspection.table_names() seqs = connection.introspection.sequence_list() if reset_sequences else () statements = connection.ops.sql_flush(style, tables, seqs, allow_cascade) return statements def sql_custom(app_config, style, connection): "Returns a list of the custom table modifying SQL statements for the given app." check_for_migrations(app_config, connection) output = [] app_models = router.get_migratable_models(app_config, connection.alias) for model in app_models: output.extend(custom_sql_for_model(model, style, connection)) return output def sql_indexes(app_config, style, connection): "Returns a list of the CREATE INDEX SQL statements for all models in the given app." check_for_migrations(app_config, connection) output = [] for model in router.get_migratable_models(app_config, connection.alias, include_auto_created=True): output.extend(connection.creation.sql_indexes_for_model(model, style)) return output def sql_destroy_indexes(app_config, style, connection): "Returns a list of the DROP INDEX SQL statements for all models in the given app." check_for_migrations(app_config, connection) output = [] for model in router.get_migratable_models(app_config, connection.alias, include_auto_created=True): output.extend(connection.creation.sql_destroy_indexes_for_model(model, style)) return output def sql_all(app_config, style, connection): check_for_migrations(app_config, connection) "Returns a list of CREATE TABLE SQL, initial-data inserts, and CREATE INDEX SQL for the given module." return sql_create(app_config, style, connection) + sql_custom(app_config, style, connection) + sql_indexes(app_config, style, connection) def _split_statements(content): # Private API only called from code that emits a RemovedInDjango19Warning. comment_re = re.compile(r"^((?:'[^']*'|[^'])*?)--.*$") statements = [] statement = [] for line in content.split("\n"): cleaned_line = comment_re.sub(r"\1", line).strip() if not cleaned_line: continue statement.append(cleaned_line) if cleaned_line.endswith(";"): statements.append(" ".join(statement)) statement = [] return statements def custom_sql_for_model(model, style, connection): opts = model._meta app_dirs = [] app_dir = apps.get_app_config(model._meta.app_label).path app_dirs.append(os.path.normpath(os.path.join(app_dir, 'sql'))) # Deprecated location -- remove in Django 1.9 old_app_dir = os.path.normpath(os.path.join(app_dir, 'models/sql')) if os.path.exists(old_app_dir): warnings.warn("Custom SQL location '<app_label>/models/sql' is " "deprecated, use '<app_label>/sql' instead.", RemovedInDjango19Warning) app_dirs.append(old_app_dir) output = [] # Post-creation SQL should come before any initial SQL data is loaded. # However, this should not be done for models that are unmanaged or # for fields that are part of a parent model (via model inheritance). if opts.managed: post_sql_fields = [f for f in opts.local_fields if hasattr(f, 'post_create_sql')] for f in post_sql_fields: output.extend(f.post_create_sql(style, model._meta.db_table)) # Find custom SQL, if it's available. backend_name = connection.settings_dict['ENGINE'].split('.')[-1] sql_files = [] for app_dir in app_dirs: sql_files.append(os.path.join(app_dir, "%s.%s.sql" % (opts.model_name, backend_name))) sql_files.append(os.path.join(app_dir, "%s.sql" % opts.model_name)) for sql_file in sql_files: if os.path.exists(sql_file): with codecs.open(sql_file, 'r', encoding=settings.FILE_CHARSET) as fp: output.extend(connection.ops.prepare_sql_script(fp.read(), _allow_fallback=True)) return output def emit_pre_migrate_signal(create_models, verbosity, interactive, db): # Emit the pre_migrate signal for every application. for app_config in apps.get_app_configs(): if app_config.models_module is None: continue if verbosity >= 2: print("Running pre-migrate handlers for application %s" % app_config.label) models.signals.pre_migrate.send( sender=app_config, app_config=app_config, verbosity=verbosity, interactive=interactive, using=db) # For backwards-compatibility -- remove in Django 1.9. models.signals.pre_syncdb.send( sender=app_config.models_module, app=app_config.models_module, create_models=create_models, verbosity=verbosity, interactive=interactive, db=db) def emit_post_migrate_signal(created_models, verbosity, interactive, db): # Emit the post_migrate signal for every application. for app_config in apps.get_app_configs(): if app_config.models_module is None: continue if verbosity >= 2: print("Running post-migrate handlers for application %s" % app_config.label) models.signals.post_migrate.send( sender=app_config, app_config=app_config, verbosity=verbosity, interactive=interactive, using=db) # For backwards-compatibility -- remove in Django 1.9. models.signals.post_syncdb.send( sender=app_config.models_module, app=app_config.models_module, created_models=created_models, verbosity=verbosity, interactive=interactive, db=db)
bsd-3-clause
simonsfoundation/inferelator_ng
inferelator_ng/tests/test_mi_R.py
3
4576
import unittest, os import pandas as pd import numpy as np from .. import mi_R my_dir = os.path.dirname(__file__) class TestMI(unittest.TestCase): """ Superclass for common methods """ cores = bins = 10 def calculate_mi(self): driver = mi_R.MIDriver() target = driver.target_directory = os.path.join(my_dir, "artifacts") if not os.path.exists(target): os.makedirs(target) driver.cores = self.cores driver.bins = self.bins (self.clr_matrix, self.mi_matrix) = driver.run(self.x_dataframe, self.y_dataframe) def print_results(self): print("\nx") print(self.x_dataframe) print("y") print(self.y_dataframe) print("mi") print(self.mi_matrix) print("clr") print(self.clr_matrix) class Test2By2(TestMI): def test_12_34_identical(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.array(L)) self.calculate_mi() #self.print_results() expected = np.array([[0, 1], [1, 0]]) np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected) def test_12_34_minus(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(-np.array(L)) self.calculate_mi() #self.print_results() expected = np.array([[0, 1], [1, 0]]) np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected) def test_12_34_times_pi(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.pi * np.array(L)) self.calculate_mi() #self.print_results() expected = np.array([[0, 1], [1, 0]]) np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected) def test_12_34_swapped(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] L2 = [[3, 4], [2, 1]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.array(L2)) self.calculate_mi() expected = np.array([[0, 1], [1, 0]]) np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected) def test_12_34_transposed(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.array(L).transpose()) self.calculate_mi() #self.print_results() expected = np.array([[0, 1], [1, 0]]) np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected) def test_12_34_and_zeros(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.zeros((2,2))) self.calculate_mi() #self.print_results() # the entire clr matrix is NAN self.assertTrue(np.isnan(self.clr_matrix.as_matrix()).all()) def test_12_34_and_ones(self): "Compute mi for identical arrays [[1, 2], [2, 4]]." L = [[1, 2], [3, 4]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.ones((2,2))) self.calculate_mi() #self.print_results() self.assertTrue(np.isnan(self.clr_matrix.as_matrix()).all()) class Test2By3(TestMI): def test_12_34_identical(self): "Compute mi for identical arrays [[1, 2, 1], [2, 4, 6]]." L = [[1, 2, 1], [3, 4, 6]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.array(L)) self.calculate_mi() #self.print_results() expected = np.array([[0, 1], [1, 0]]) np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected) def test_mixed(self): "Compute mi for mixed arrays." L = [[1, 2, 1], [3, 4, 6]] L2 = [[3, 7, 1], [9, 0, 2]] self.x_dataframe = pd.DataFrame(np.array(L)) self.y_dataframe = pd.DataFrame(np.array(L2)) self.calculate_mi() self.print_results() expected = np.array([[0, 1], [1, 0]]) #np.testing.assert_almost_equal(self.clr_matrix.as_matrix(), expected)
bsd-2-clause
lemonad/methodiki
methodiki/customcomments/__init__.py
1
1498
# -*- coding: utf-8 -*- from django.contrib.comments.models import Comment from forms import CustomCommentForm from models import CustomComment def get_model(): return CustomComment def get_form(): return CustomCommentForm # FIXME: Remove monkey patching after Django ticket 13411 has been resolved! # (http://code.djangoproject.com/ticket/13411) # The below is the next_redirect code from Django 1.2.3 with patch # from ticket 13411 applied import urllib from django.contrib.comments.views import utils from django.core import urlresolvers from django.http import HttpResponseRedirect def next_redirect(data, default, default_view, **get_kwargs): """ Handle the "where should I go next?" part of comment views. The next value could be a kwarg to the function (``default``), or a ``?next=...`` GET arg, or the URL of a given view (``default_view``). See the view modules for examples. Returns an ``HttpResponseRedirect``. """ next = data.get("next", default) if next is None: next = urlresolvers.reverse(default_view) if get_kwargs: if '#' in next: tmp = next.rsplit('#', 1) next = tmp[0] anchor = '#' + tmp[1] else: anchor = '' joiner = ('?' in next) and '&' or '?' next += joiner + urllib.urlencode(get_kwargs) + anchor return HttpResponseRedirect(next) # Go monkey patch, go! utils.next_redirect = next_redirect
mit
wbcustc/Vintageous
bin/builder.py
8
1751
from fnmatch import fnmatch from itertools import chain from zipfile import ZipFile from zipfile import ZIP_DEFLATED import argparse import glob import json import os THIS_DIR = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path.dirname(THIS_DIR) RESERVED = ['manifest.json', 'dist'] parser = argparse.ArgumentParser( description="Builds .sublime-package archives.") parser.add_argument('-d', dest='target_dir', default='./dist', help="output directory") parser.add_argument('--release', dest='release', default='dev', help="type of build (e.g. 'dev', 'release'...)") def get_manifest(): path = os.path.join(PROJECT_ROOT, 'manifest.json') with open(path) as f: return json.load(f) def unwanted(fn, pats): return any(fnmatch(fn, pat) for pat in pats + RESERVED) def ifind_files(patterns): for fn in (fn for (pat, exclude) in patterns for fn in glob.iglob(pat) if not unwanted(fn, exclude)): yield fn def build(target_dir="dist", release="dev"): os.chdir(PROJECT_ROOT) manifest = get_manifest() name = manifest['name'] + '.sublime-package' target_dir = os.path.join(PROJECT_ROOT, target_dir) if not os.path.exists(target_dir): os.mkdir(target_dir) target_file = os.path.join(target_dir, name) if os.path.exists(target_file): os.unlink(target_file) with ZipFile(target_file, 'a', compression=ZIP_DEFLATED) as package: for fn in ifind_files(manifest['include'][release]): package.write(fn) if __name__ == '__main__': args = parser.parse_args() build(args.target_dir, args.release)
mit
zbal/ansible
test/units/template/test_safe_eval.py
205
1956
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys from collections import defaultdict from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, MagicMock from ansible.template.safe_eval import safe_eval class TestSafeEval(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_safe_eval_usage(self): # test safe eval calls with different possible types for the # locals dictionary, to ensure we don't run into problems like # ansible/ansible/issues/12206 again for locals_vars in (dict(), defaultdict(dict)): self.assertEqual(safe_eval('True', locals=locals_vars), True) self.assertEqual(safe_eval('False', locals=locals_vars), False) self.assertEqual(safe_eval('0', locals=locals_vars), 0) self.assertEqual(safe_eval('[]', locals=locals_vars), []) self.assertEqual(safe_eval('{}', locals=locals_vars), {}) @unittest.skipUnless(sys.version_info[:2] >= (2, 7), "Python 2.6 has no set literals") def test_set_literals(self): self.assertEqual(safe_eval('{0}'), set([0]))
gpl-3.0
SaschaMester/delicium
third_party/pexpect/screen.py
171
11281
"""This implements a virtual screen. This is used to support ANSI terminal emulation. The screen representation and state is implemented in this class. Most of the methods are inspired by ANSI screen control codes. The ANSI class extends this class to add parsing of ANSI escape codes. PEXPECT LICENSE This license is approved by the OSI and FSF as GPL-compatible. http://opensource.org/licenses/isc-license.txt Copyright (c) 2012, Noah Spurrier <noah@noah.org> PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """ import copy NUL = 0 # Fill character; ignored on input. ENQ = 5 # Transmit answerback message. BEL = 7 # Ring the bell. BS = 8 # Move cursor left. HT = 9 # Move cursor to next tab stop. LF = 10 # Line feed. VT = 11 # Same as LF. FF = 12 # Same as LF. CR = 13 # Move cursor to left margin or newline. SO = 14 # Invoke G1 character set. SI = 15 # Invoke G0 character set. XON = 17 # Resume transmission. XOFF = 19 # Halt transmission. CAN = 24 # Cancel escape sequence. SUB = 26 # Same as CAN. ESC = 27 # Introduce a control sequence. DEL = 127 # Fill character; ignored on input. SPACE = chr(32) # Space or blank character. def constrain (n, min, max): """This returns a number, n constrained to the min and max bounds. """ if n < min: return min if n > max: return max return n class screen: """This object maintains the state of a virtual text screen as a rectangluar array. This maintains a virtual cursor position and handles scrolling as characters are added. This supports most of the methods needed by an ANSI text screen. Row and column indexes are 1-based (not zero-based, like arrays). """ def __init__ (self, r=24,c=80): """This initializes a blank scree of the given dimentions.""" self.rows = r self.cols = c self.cur_r = 1 self.cur_c = 1 self.cur_saved_r = 1 self.cur_saved_c = 1 self.scroll_row_start = 1 self.scroll_row_end = self.rows self.w = [ [SPACE] * self.cols for c in range(self.rows)] def __str__ (self): """This returns a printable representation of the screen. The end of each screen line is terminated by a newline. """ return '\n'.join ([ ''.join(c) for c in self.w ]) def dump (self): """This returns a copy of the screen as a string. This is similar to __str__ except that lines are not terminated with line feeds. """ return ''.join ([ ''.join(c) for c in self.w ]) def pretty (self): """This returns a copy of the screen as a string with an ASCII text box around the screen border. This is similar to __str__ except that it adds a box. """ top_bot = '+' + '-'*self.cols + '+\n' return top_bot + '\n'.join(['|'+line+'|' for line in str(self).split('\n')]) + '\n' + top_bot def fill (self, ch=SPACE): self.fill_region (1,1,self.rows,self.cols, ch) def fill_region (self, rs,cs, re,ce, ch=SPACE): rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs for r in range (rs, re+1): for c in range (cs, ce + 1): self.put_abs (r,c,ch) def cr (self): """This moves the cursor to the beginning (col 1) of the current row. """ self.cursor_home (self.cur_r, 1) def lf (self): """This moves the cursor down with scrolling. """ old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line() def crlf (self): """This advances the cursor with CRLF properties. The cursor will line wrap and the screen may scroll. """ self.cr () self.lf () def newline (self): """This is an alias for crlf(). """ self.crlf() def put_abs (self, r, c, ch): """Screen array starts at 1 index.""" r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) ch = str(ch)[0] self.w[r-1][c-1] = ch def put (self, ch): """This puts a characters at the current cursor position. """ self.put_abs (self.cur_r, self.cur_c, ch) def insert_abs (self, r, c, ch): """This inserts a character at (r,c). Everything under and to the right is shifted right one character. The last character of the line is lost. """ r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) for ci in range (self.cols, c, -1): self.put_abs (r,ci, self.get_abs(r,ci-1)) self.put_abs (r,c,ch) def insert (self, ch): self.insert_abs (self.cur_r, self.cur_c, ch) def get_abs (self, r, c): r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) return self.w[r-1][c-1] def get (self): self.get_abs (self.cur_r, self.cur_c) def get_region (self, rs,cs, re,ce): """This returns a list of lines representing the region. """ rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs sc = [] for r in range (rs, re+1): line = '' for c in range (cs, ce + 1): ch = self.get_abs (r,c) line = line + ch sc.append (line) return sc def cursor_constrain (self): """This keeps the cursor within the screen area. """ self.cur_r = constrain (self.cur_r, 1, self.rows) self.cur_c = constrain (self.cur_c, 1, self.cols) def cursor_home (self, r=1, c=1): # <ESC>[{ROW};{COLUMN}H self.cur_r = r self.cur_c = c self.cursor_constrain () def cursor_back (self,count=1): # <ESC>[{COUNT}D (not confused with down) self.cur_c = self.cur_c - count self.cursor_constrain () def cursor_down (self,count=1): # <ESC>[{COUNT}B (not confused with back) self.cur_r = self.cur_r + count self.cursor_constrain () def cursor_forward (self,count=1): # <ESC>[{COUNT}C self.cur_c = self.cur_c + count self.cursor_constrain () def cursor_up (self,count=1): # <ESC>[{COUNT}A self.cur_r = self.cur_r - count self.cursor_constrain () def cursor_up_reverse (self): # <ESC> M (called RI -- Reverse Index) old_r = self.cur_r self.cursor_up() if old_r == self.cur_r: self.scroll_up() def cursor_force_position (self, r, c): # <ESC>[{ROW};{COLUMN}f """Identical to Cursor Home.""" self.cursor_home (r, c) def cursor_save (self): # <ESC>[s """Save current cursor position.""" self.cursor_save_attrs() def cursor_unsave (self): # <ESC>[u """Restores cursor position after a Save Cursor.""" self.cursor_restore_attrs() def cursor_save_attrs (self): # <ESC>7 """Save current cursor position.""" self.cur_saved_r = self.cur_r self.cur_saved_c = self.cur_c def cursor_restore_attrs (self): # <ESC>8 """Restores cursor position after a Save Cursor.""" self.cursor_home (self.cur_saved_r, self.cur_saved_c) def scroll_constrain (self): """This keeps the scroll region within the screen region.""" if self.scroll_row_start <= 0: self.scroll_row_start = 1 if self.scroll_row_end > self.rows: self.scroll_row_end = self.rows def scroll_screen (self): # <ESC>[r """Enable scrolling for entire display.""" self.scroll_row_start = 1 self.scroll_row_end = self.rows def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r """Enable scrolling from row {start} to row {end}.""" self.scroll_row_start = rs self.scroll_row_end = re self.scroll_constrain() def scroll_down (self): # <ESC>D """Scroll display down one line.""" # Screen is indexed from 1, but arrays are indexed from 0. s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s+1:e+1] = copy.deepcopy(self.w[s:e]) def scroll_up (self): # <ESC>M """Scroll display up one line.""" # Screen is indexed from 1, but arrays are indexed from 0. s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s:e] = copy.deepcopy(self.w[s+1:e+1]) def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K """Erases from the current cursor position to the end of the current line.""" self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols) def erase_start_of_line (self): # <ESC>[1K """Erases from the current cursor position to the start of the current line.""" self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c) def erase_line (self): # <ESC>[2K """Erases the entire current line.""" self.fill_region (self.cur_r, 1, self.cur_r, self.cols) def erase_down (self): # <ESC>[0J -or- <ESC>[J """Erases the screen from the current line down to the bottom of the screen.""" self.erase_end_of_line () self.fill_region (self.cur_r + 1, 1, self.rows, self.cols) def erase_up (self): # <ESC>[1J """Erases the screen from the current line up to the top of the screen.""" self.erase_start_of_line () self.fill_region (self.cur_r-1, 1, 1, self.cols) def erase_screen (self): # <ESC>[2J """Erases the screen with the background color.""" self.fill () def set_tab (self): # <ESC>H """Sets a tab at the current position.""" pass def clear_tab (self): # <ESC>[g """Clears tab at the current position.""" pass def clear_all_tabs (self): # <ESC>[3g """Clears all tabs.""" pass # Insert line Esc [ Pn L # Delete line Esc [ Pn M # Delete character Esc [ Pn P # Scrolling region Esc [ Pn(top);Pn(bot) r
bsd-3-clause
alhashash/odoomrp-wip
mrp_product_variants_types/models/mrp.py
16
1382
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields, api, exceptions, _ class SaleOrderLineAttribute(models.Model): _inherit = 'mrp.production.attribute' custom_value = fields.Float(string='Custom value') attr_type = fields.Selection(string='Type', store=False, related='attribute.attr_type') def _is_custom_value_in_range(self): if self.attr_type == 'range': if not (self.value.min_range <= self.custom_value and self.value.max_range >= self.custom_value): return False return True @api.one @api.constrains('custom_value', 'attr_type', 'value') def _custom_value_in_range(self): if not self._is_custom_value_in_range(): raise exceptions.Warning( _("Custom value for attribute '%s' must be between %s and" " %s.") % (self.attribute.name, self.value.min_range, self.value.max_range)) @api.one @api.onchange('custom_value', 'value') def _onchange_custom_value(self): self._custom_value_in_range()
agpl-3.0
yyjiang/scikit-learn
sklearn/preprocessing/data.py
113
56747
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Olivier Grisel <olivier.grisel@ensta.org> # Andreas Mueller <amueller@ais.uni-bonn.de> # Eric Martin <eric@ericmart.in> # License: BSD 3 clause from itertools import chain, combinations import numbers import warnings import numpy as np from scipy import sparse from ..base import BaseEstimator, TransformerMixin from ..externals import six from ..utils import check_array from ..utils.extmath import row_norms from ..utils.fixes import combinations_with_replacement as combinations_w_r from ..utils.sparsefuncs_fast import (inplace_csr_row_normalize_l1, inplace_csr_row_normalize_l2) from ..utils.sparsefuncs import (inplace_column_scale, mean_variance_axis, min_max_axis, inplace_row_scale) from ..utils.validation import check_is_fitted, FLOAT_DTYPES zip = six.moves.zip map = six.moves.map range = six.moves.range __all__ = [ 'Binarizer', 'KernelCenterer', 'MinMaxScaler', 'MaxAbsScaler', 'Normalizer', 'OneHotEncoder', 'RobustScaler', 'StandardScaler', 'add_dummy_feature', 'binarize', 'normalize', 'scale', 'robust_scale', 'maxabs_scale', 'minmax_scale', ] def _mean_and_std(X, axis=0, with_mean=True, with_std=True): """Compute mean and std deviation for centering, scaling. Zero valued std components are reset to 1.0 to avoid NaNs when scaling. """ X = np.asarray(X) Xr = np.rollaxis(X, axis) if with_mean: mean_ = Xr.mean(axis=0) else: mean_ = None if with_std: std_ = Xr.std(axis=0) std_ = _handle_zeros_in_scale(std_) else: std_ = None return mean_, std_ def _handle_zeros_in_scale(scale): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features.''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): if scale == 0: scale = 1. elif isinstance(scale, np.ndarray): scale[scale == 0.0] = 1.0 scale[~np.isfinite(scale)] = 1.0 return scale def scale(X, axis=0, with_mean=True, with_std=True, copy=True): """Standardize a dataset along any axis Center to the mean and component wise scale to unit variance. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- X : array-like or CSR matrix. The data to center and scale. axis : int (0 by default) axis used to compute the means and standard deviations along. If 0, independently standardize each feature, otherwise (if 1) standardize each sample. with_mean : boolean, True by default If True, center the data before scaling. with_std : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation). copy : boolean, optional, default True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1). Notes ----- This implementation will refuse to center scipy.sparse matrices since it would make them non-sparse and would potentially crash the program with memory exhaustion problems. Instead the caller is expected to either set explicitly `with_mean=False` (in that case, only variance scaling will be performed on the features of the CSR matrix) or to call `X.toarray()` if he/she expects the materialized dense array to fit in memory. To avoid memory copy the caller should pass a CSR matrix. See also -------- :class:`sklearn.preprocessing.StandardScaler` to perform centering and scaling using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`) """ X = check_array(X, accept_sparse='csr', copy=copy, ensure_2d=False, warn_on_dtype=True, estimator='the scale function', dtype=FLOAT_DTYPES) if sparse.issparse(X): if with_mean: raise ValueError( "Cannot center sparse matrices: pass `with_mean=False` instead" " See docstring for motivation and alternatives.") if axis != 0: raise ValueError("Can only scale sparse matrix on axis=0, " " got axis=%d" % axis) if not sparse.isspmatrix_csr(X): X = X.tocsr() copy = False if copy: X = X.copy() _, var = mean_variance_axis(X, axis=0) var = _handle_zeros_in_scale(var) inplace_column_scale(X, 1 / np.sqrt(var)) else: X = np.asarray(X) mean_, std_ = _mean_and_std( X, axis, with_mean=with_mean, with_std=with_std) if copy: X = X.copy() # Xr is a view on the original array that enables easy use of # broadcasting on the axis in which we are interested in Xr = np.rollaxis(X, axis) if with_mean: Xr -= mean_ mean_1 = Xr.mean(axis=0) # Verify that mean_1 is 'close to zero'. If X contains very # large values, mean_1 can also be very large, due to a lack of # precision of mean_. In this case, a pre-scaling of the # concerned feature is efficient, for instance by its mean or # maximum. if not np.allclose(mean_1, 0): warnings.warn("Numerical issues were encountered " "when centering the data " "and might not be solved. Dataset may " "contain too large values. You may need " "to prescale your features.") Xr -= mean_1 if with_std: Xr /= std_ if with_mean: mean_2 = Xr.mean(axis=0) # If mean_2 is not 'close to zero', it comes from the fact that # std_ is very small so that mean_2 = mean_1/std_ > 0, even if # mean_1 was close to zero. The problem is thus essentially due # to the lack of precision of mean_. A solution is then to # substract the mean again: if not np.allclose(mean_2, 0): warnings.warn("Numerical issues were encountered " "when scaling the data " "and might not be solved. The standard " "deviation of the data is probably " "very close to 0. ") Xr -= mean_2 return X class MinMaxScaler(BaseEstimator, TransformerMixin): """Transforms features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, i.e. between zero and one. The transformation is given by:: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min where min, max = feature_range. This transformation is often used as an alternative to zero mean, unit variance scaling. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- feature_range: tuple (min, max), default=(0, 1) Desired range of transformed data. copy : boolean, optional, default True Set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array). Attributes ---------- min_ : ndarray, shape (n_features,) Per feature adjustment for minimum. scale_ : ndarray, shape (n_features,) Per feature relative scaling of the data. """ def __init__(self, feature_range=(0, 1), copy=True): self.feature_range = feature_range self.copy = copy def fit(self, X, y=None): """Compute the minimum and maximum to be used for later scaling. Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to compute the per-feature minimum and maximum used for later scaling along the features axis. """ X = check_array(X, copy=self.copy, ensure_2d=False, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) feature_range = self.feature_range if feature_range[0] >= feature_range[1]: raise ValueError("Minimum of desired feature range must be smaller" " than maximum. Got %s." % str(feature_range)) data_min = np.min(X, axis=0) data_range = np.max(X, axis=0) - data_min data_range = _handle_zeros_in_scale(data_range) self.scale_ = (feature_range[1] - feature_range[0]) / data_range self.min_ = feature_range[0] - data_min * self.scale_ self.data_range = data_range self.data_min = data_min return self def transform(self, X): """Scaling features of X according to feature_range. Parameters ---------- X : array-like with shape [n_samples, n_features] Input data that will be transformed. """ check_is_fitted(self, 'scale_') X = check_array(X, copy=self.copy, ensure_2d=False) X *= self.scale_ X += self.min_ return X def inverse_transform(self, X): """Undo the scaling of X according to feature_range. Parameters ---------- X : array-like with shape [n_samples, n_features] Input data that will be transformed. """ check_is_fitted(self, 'scale_') X = check_array(X, copy=self.copy, ensure_2d=False) X -= self.min_ X /= self.scale_ return X def minmax_scale(X, feature_range=(0, 1), axis=0, copy=True): """Transforms features by scaling each feature to a given range. This estimator scales and translates each feature individually such that it is in the given range on the training set, i.e. between zero and one. The transformation is given by:: X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(axis=0)) X_scaled = X_std * (max - min) + min where min, max = feature_range. This transformation is often used as an alternative to zero mean, unit variance scaling. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- feature_range: tuple (min, max), default=(0, 1) Desired range of transformed data. axis : int (0 by default) axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample. copy : boolean, optional, default is True Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array). """ s = MinMaxScaler(feature_range=feature_range, copy=copy) if axis == 0: return s.fit_transform(X) else: return s.fit_transform(X.T).T class StandardScaler(BaseEstimator, TransformerMixin): """Standardize features by removing the mean and scaling to unit variance Centering and scaling happen independently on each feature by computing the relevant statistics on the samples in the training set. Mean and standard deviation are then stored to be used on later data using the `transform` method. Standardization of a dataset is a common requirement for many machine learning estimators: they might behave badly if the individual feature do not more or less look like standard normally distributed data (e.g. Gaussian with 0 mean and unit variance). For instance many elements used in the objective function of a learning algorithm (such as the RBF kernel of Support Vector Machines or the L1 and L2 regularizers of linear models) assume that all features are centered around 0 and have variance in the same order. If a feature has a variance that is orders of magnitude larger that others, it might dominate the objective function and make the estimator unable to learn from other features correctly as expected. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- with_mean : boolean, True by default If True, center the data before scaling. This does not work (and will raise an exception) when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory. with_std : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation). copy : boolean, optional, default True If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned. Attributes ---------- mean_ : array of floats with shape [n_features] The mean value for each feature in the training set. std_ : array of floats with shape [n_features] The standard deviation for each feature in the training set. Set to one if the standard deviation is zero for a given feature. See also -------- :func:`sklearn.preprocessing.scale` to perform centering and scaling without using the ``Transformer`` object oriented API :class:`sklearn.decomposition.RandomizedPCA` with `whiten=True` to further remove the linear correlation across features. """ def __init__(self, copy=True, with_mean=True, with_std=True): self.with_mean = with_mean self.with_std = with_std self.copy = copy def fit(self, X, y=None): """Compute the mean and std to be used for later scaling. Parameters ---------- X : array-like or CSR matrix with shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. """ X = check_array(X, accept_sparse='csr', copy=self.copy, ensure_2d=False, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot center sparse matrices: pass `with_mean=False` " "instead. See docstring for motivation and alternatives.") self.mean_ = None if self.with_std: var = mean_variance_axis(X, axis=0)[1] self.std_ = np.sqrt(var) self.std_ = _handle_zeros_in_scale(self.std_) else: self.std_ = None return self else: self.mean_, self.std_ = _mean_and_std( X, axis=0, with_mean=self.with_mean, with_std=self.with_std) return self def transform(self, X, y=None, copy=None): """Perform standardization by centering and scaling Parameters ---------- X : array-like with shape [n_samples, n_features] The data used to scale along the features axis. """ check_is_fitted(self, 'std_') copy = copy if copy is not None else self.copy X = check_array(X, accept_sparse='csr', copy=copy, ensure_2d=False, warn_on_dtype=True, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot center sparse matrices: pass `with_mean=False` " "instead. See docstring for motivation and alternatives.") if self.std_ is not None: inplace_column_scale(X, 1 / self.std_) else: if self.with_mean: X -= self.mean_ if self.with_std: X /= self.std_ return X def inverse_transform(self, X, copy=None): """Scale back the data to the original representation Parameters ---------- X : array-like with shape [n_samples, n_features] The data used to scale along the features axis. """ check_is_fitted(self, 'std_') copy = copy if copy is not None else self.copy if sparse.issparse(X): if self.with_mean: raise ValueError( "Cannot uncenter sparse matrices: pass `with_mean=False` " "instead See docstring for motivation and alternatives.") if not sparse.isspmatrix_csr(X): X = X.tocsr() copy = False if copy: X = X.copy() if self.std_ is not None: inplace_column_scale(X, self.std_) else: X = np.asarray(X) if copy: X = X.copy() if self.with_std: X *= self.std_ if self.with_mean: X += self.mean_ return X class MaxAbsScaler(BaseEstimator, TransformerMixin): """Scale each feature by its maximum absolute value. This estimator scales and translates each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. It does not shift/center the data, and thus does not destroy any sparsity. This scaler can also be applied to sparse CSR or CSC matrices. Parameters ---------- copy : boolean, optional, default is True Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array). Attributes ---------- scale_ : ndarray, shape (n_features,) Per feature relative scaling of the data. """ def __init__(self, copy=True): self.copy = copy def fit(self, X, y=None): """Compute the minimum and maximum to be used for later scaling. Parameters ---------- X : array-like, shape [n_samples, n_features] The data used to compute the per-feature minimum and maximum used for later scaling along the features axis. """ X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): mins, maxs = min_max_axis(X, axis=0) scales = np.maximum(np.abs(mins), np.abs(maxs)) else: scales = np.abs(X).max(axis=0) scales = np.array(scales) scales = scales.reshape(-1) self.scale_ = _handle_zeros_in_scale(scales) return self def transform(self, X, y=None): """Scale the data Parameters ---------- X : array-like or CSR matrix. The data that should be scaled. """ check_is_fitted(self, 'scale_') X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if X.shape[0] == 1: inplace_row_scale(X, 1.0 / self.scale_) else: inplace_column_scale(X, 1.0 / self.scale_) else: X /= self.scale_ return X def inverse_transform(self, X): """Scale back the data to the original representation Parameters ---------- X : array-like or CSR matrix. The data that should be transformed back. """ check_is_fitted(self, 'scale_') X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if X.shape[0] == 1: inplace_row_scale(X, self.scale_) else: inplace_column_scale(X, self.scale_) else: X *= self.scale_ return X def maxabs_scale(X, axis=0, copy=True): """Scale each feature to the [-1, 1] range without breaking the sparsity. This estimator scales each feature individually such that the maximal absolute value of each feature in the training set will be 1.0. This scaler can also be applied to sparse CSR or CSC matrices. Parameters ---------- axis : int (0 by default) axis used to scale along. If 0, independently scale each feature, otherwise (if 1) scale each sample. copy : boolean, optional, default is True Set to False to perform inplace scaling and avoid a copy (if the input is already a numpy array). """ s = MaxAbsScaler(copy=copy) if axis == 0: return s.fit_transform(X) else: return s.fit_transform(X.T).T class RobustScaler(BaseEstimator, TransformerMixin): """Scale features using statistics that are robust to outliers. This Scaler removes the median and scales the data according to the Interquartile Range (IQR). The IQR is the range between the 1st quartile (25th quantile) and the 3rd quartile (75th quantile). Centering and scaling happen independently on each feature (or each sample, depending on the `axis` argument) by computing the relevant statistics on the samples in the training set. Median and interquartile range are then stored to be used on later data using the `transform` method. Standardization of a dataset is a common requirement for many machine learning estimators. Typically this is done by removing the mean and scaling to unit variance. However, outliers can often influence the sample mean / variance in a negative way. In such cases, the median and the interquartile range often give better results. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- with_centering : boolean, True by default If True, center the data before scaling. This does not work (and will raise an exception) when attempted on sparse matrices, because centering them entails building a dense matrix which in common use cases is likely to be too large to fit in memory. with_scaling : boolean, True by default If True, scale the data to interquartile range. copy : boolean, optional, default is True If False, try to avoid a copy and do inplace scaling instead. This is not guaranteed to always work inplace; e.g. if the data is not a NumPy array or scipy.sparse CSR matrix, a copy may still be returned. Attributes ---------- center_ : array of floats The median value for each feature in the training set. scale_ : array of floats The (scaled) interquartile range for each feature in the training set. See also -------- :class:`sklearn.preprocessing.StandardScaler` to perform centering and scaling using mean and variance. :class:`sklearn.decomposition.RandomizedPCA` with `whiten=True` to further remove the linear correlation across features. Notes ----- See examples/preprocessing/plot_robust_scaling.py for an example. http://en.wikipedia.org/wiki/Median_(statistics) http://en.wikipedia.org/wiki/Interquartile_range """ def __init__(self, with_centering=True, with_scaling=True, copy=True): self.with_centering = with_centering self.with_scaling = with_scaling self.copy = copy def _check_array(self, X, copy): """Makes sure centering is not enabled for sparse matrices.""" X = check_array(X, accept_sparse=('csr', 'csc'), copy=self.copy, ensure_2d=False, estimator=self, dtype=FLOAT_DTYPES) if sparse.issparse(X): if self.with_centering: raise ValueError( "Cannot center sparse matrices: use `with_centering=False`" " instead. See docstring for motivation and alternatives.") return X def fit(self, X, y=None): """Compute the median and quantiles to be used for scaling. Parameters ---------- X : array-like with shape [n_samples, n_features] The data used to compute the median and quantiles used for later scaling along the features axis. """ if sparse.issparse(X): raise TypeError("RobustScaler cannot be fitted on sparse inputs") X = self._check_array(X, self.copy) if self.with_centering: self.center_ = np.median(X, axis=0) if self.with_scaling: q = np.percentile(X, (25, 75), axis=0) self.scale_ = (q[1] - q[0]) self.scale_ = _handle_zeros_in_scale(self.scale_) return self def transform(self, X, y=None): """Center and scale the data Parameters ---------- X : array-like or CSR matrix. The data used to scale along the specified axis. """ if self.with_centering: check_is_fitted(self, 'center_') if self.with_scaling: check_is_fitted(self, 'scale_') X = self._check_array(X, self.copy) if sparse.issparse(X): if self.with_scaling: if X.shape[0] == 1: inplace_row_scale(X, 1.0 / self.scale_) elif self.axis == 0: inplace_column_scale(X, 1.0 / self.scale_) else: if self.with_centering: X -= self.center_ if self.with_scaling: X /= self.scale_ return X def inverse_transform(self, X): """Scale back the data to the original representation Parameters ---------- X : array-like or CSR matrix. The data used to scale along the specified axis. """ if self.with_centering: check_is_fitted(self, 'center_') if self.with_scaling: check_is_fitted(self, 'scale_') X = self._check_array(X, self.copy) if sparse.issparse(X): if self.with_scaling: if X.shape[0] == 1: inplace_row_scale(X, self.scale_) else: inplace_column_scale(X, self.scale_) else: if self.with_scaling: X *= self.scale_ if self.with_centering: X += self.center_ return X def robust_scale(X, axis=0, with_centering=True, with_scaling=True, copy=True): """Standardize a dataset along any axis Center to the median and component wise scale according to the interquartile range. Read more in the :ref:`User Guide <preprocessing_scaler>`. Parameters ---------- X : array-like. The data to center and scale. axis : int (0 by default) axis used to compute the medians and IQR along. If 0, independently scale each feature, otherwise (if 1) scale each sample. with_centering : boolean, True by default If True, center the data before scaling. with_scaling : boolean, True by default If True, scale the data to unit variance (or equivalently, unit standard deviation). copy : boolean, optional, default is True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1). Notes ----- This implementation will refuse to center scipy.sparse matrices since it would make them non-sparse and would potentially crash the program with memory exhaustion problems. Instead the caller is expected to either set explicitly `with_centering=False` (in that case, only variance scaling will be performed on the features of the CSR matrix) or to call `X.toarray()` if he/she expects the materialized dense array to fit in memory. To avoid memory copy the caller should pass a CSR matrix. See also -------- :class:`sklearn.preprocessing.RobustScaler` to perform centering and scaling using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`) """ s = RobustScaler(with_centering=with_centering, with_scaling=with_scaling, copy=copy) if axis == 0: return s.fit_transform(X) else: return s.fit_transform(X.T).T class PolynomialFeatures(BaseEstimator, TransformerMixin): """Generate polynomial and interaction features. Generate a new feature matrix consisting of all polynomial combinations of the features with degree less than or equal to the specified degree. For example, if an input sample is two dimensional and of the form [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2]. Parameters ---------- degree : integer The degree of the polynomial features. Default = 2. interaction_only : boolean, default = False If true, only interaction features are produced: features that are products of at most ``degree`` *distinct* input features (so not ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.). include_bias : boolean If True (default), then include a bias column, the feature in which all polynomial powers are zero (i.e. a column of ones - acts as an intercept term in a linear model). Examples -------- >>> X = np.arange(6).reshape(3, 2) >>> X array([[0, 1], [2, 3], [4, 5]]) >>> poly = PolynomialFeatures(2) >>> poly.fit_transform(X) array([[ 1, 0, 1, 0, 0, 1], [ 1, 2, 3, 4, 6, 9], [ 1, 4, 5, 16, 20, 25]]) >>> poly = PolynomialFeatures(interaction_only=True) >>> poly.fit_transform(X) array([[ 1, 0, 1, 0], [ 1, 2, 3, 6], [ 1, 4, 5, 20]]) Attributes ---------- powers_ : array, shape (n_input_features, n_output_features) powers_[i, j] is the exponent of the jth input in the ith output. n_input_features_ : int The total number of input features. n_output_features_ : int The total number of polynomial output features. The number of output features is computed by iterating over all suitably sized combinations of input features. Notes ----- Be aware that the number of features in the output array scales polynomially in the number of features of the input array, and exponentially in the degree. High degrees can cause overfitting. See :ref:`examples/linear_model/plot_polynomial_interpolation.py <example_linear_model_plot_polynomial_interpolation.py>` """ def __init__(self, degree=2, interaction_only=False, include_bias=True): self.degree = degree self.interaction_only = interaction_only self.include_bias = include_bias @staticmethod def _combinations(n_features, degree, interaction_only, include_bias): comb = (combinations if interaction_only else combinations_w_r) start = int(not include_bias) return chain.from_iterable(comb(range(n_features), i) for i in range(start, degree + 1)) @property def powers_(self): check_is_fitted(self, 'n_input_features_') combinations = self._combinations(self.n_input_features_, self.degree, self.interaction_only, self.include_bias) return np.vstack(np.bincount(c, minlength=self.n_input_features_) for c in combinations) def fit(self, X, y=None): """ Compute number of output features. """ n_samples, n_features = check_array(X).shape combinations = self._combinations(n_features, self.degree, self.interaction_only, self.include_bias) self.n_input_features_ = n_features self.n_output_features_ = sum(1 for _ in combinations) return self def transform(self, X, y=None): """Transform data to polynomial features Parameters ---------- X : array with shape [n_samples, n_features] The data to transform, row by row. Returns ------- XP : np.ndarray shape [n_samples, NP] The matrix of features, where NP is the number of polynomial features generated from the combination of inputs. """ check_is_fitted(self, ['n_input_features_', 'n_output_features_']) X = check_array(X) n_samples, n_features = X.shape if n_features != self.n_input_features_: raise ValueError("X shape does not match training shape") # allocate output data XP = np.empty((n_samples, self.n_output_features_), dtype=X.dtype) combinations = self._combinations(n_features, self.degree, self.interaction_only, self.include_bias) for i, c in enumerate(combinations): XP[:, i] = X[:, c].prod(1) return XP def normalize(X, norm='l2', axis=1, copy=True): """Scale input vectors individually to unit norm (vector length). Read more in the :ref:`User Guide <preprocessing_normalization>`. Parameters ---------- X : array or scipy.sparse matrix with shape [n_samples, n_features] The data to normalize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy. norm : 'l1', 'l2', or 'max', optional ('l2' by default) The norm to use to normalize each non zero sample (or each non-zero feature if axis is 0). axis : 0 or 1, optional (1 by default) axis used to normalize the data along. If 1, independently normalize each sample, otherwise (if 0) normalize each feature. copy : boolean, optional, default True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix and if axis is 1). See also -------- :class:`sklearn.preprocessing.Normalizer` to perform normalization using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`) """ if norm not in ('l1', 'l2', 'max'): raise ValueError("'%s' is not a supported norm" % norm) if axis == 0: sparse_format = 'csc' elif axis == 1: sparse_format = 'csr' else: raise ValueError("'%d' is not a supported axis" % axis) X = check_array(X, sparse_format, copy=copy, warn_on_dtype=True, estimator='the normalize function', dtype=FLOAT_DTYPES) if axis == 0: X = X.T if sparse.issparse(X): if norm == 'l1': inplace_csr_row_normalize_l1(X) elif norm == 'l2': inplace_csr_row_normalize_l2(X) elif norm == 'max': _, norms = min_max_axis(X, 1) norms = norms.repeat(np.diff(X.indptr)) mask = norms != 0 X.data[mask] /= norms[mask] else: if norm == 'l1': norms = np.abs(X).sum(axis=1) elif norm == 'l2': norms = row_norms(X) elif norm == 'max': norms = np.max(X, axis=1) norms = _handle_zeros_in_scale(norms) X /= norms[:, np.newaxis] if axis == 0: X = X.T return X class Normalizer(BaseEstimator, TransformerMixin): """Normalize samples individually to unit norm. Each sample (i.e. each row of the data matrix) with at least one non zero component is rescaled independently of other samples so that its norm (l1 or l2) equals one. This transformer is able to work both with dense numpy arrays and scipy.sparse matrix (use CSR format if you want to avoid the burden of a copy / conversion). Scaling inputs to unit norms is a common operation for text classification or clustering for instance. For instance the dot product of two l2-normalized TF-IDF vectors is the cosine similarity of the vectors and is the base similarity metric for the Vector Space Model commonly used by the Information Retrieval community. Read more in the :ref:`User Guide <preprocessing_normalization>`. Parameters ---------- norm : 'l1', 'l2', or 'max', optional ('l2' by default) The norm to use to normalize each non zero sample. copy : boolean, optional, default True set to False to perform inplace row normalization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix). Notes ----- This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline. See also -------- :func:`sklearn.preprocessing.normalize` equivalent function without the object oriented API """ def __init__(self, norm='l2', copy=True): self.norm = norm self.copy = copy def fit(self, X, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. """ X = check_array(X, accept_sparse='csr') return self def transform(self, X, y=None, copy=None): """Scale each non zero row of X to unit norm Parameters ---------- X : array or scipy.sparse matrix with shape [n_samples, n_features] The data to normalize, row by row. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy. """ copy = copy if copy is not None else self.copy X = check_array(X, accept_sparse='csr') return normalize(X, norm=self.norm, axis=1, copy=copy) def binarize(X, threshold=0.0, copy=True): """Boolean thresholding of array-like or scipy.sparse matrix Read more in the :ref:`User Guide <preprocessing_binarization>`. Parameters ---------- X : array or scipy.sparse matrix with shape [n_samples, n_features] The data to binarize, element by element. scipy.sparse matrices should be in CSR or CSC format to avoid an un-necessary copy. threshold : float, optional (0.0 by default) Feature values below or equal to this are replaced by 0, above it by 1. Threshold may not be less than 0 for operations on sparse matrices. copy : boolean, optional, default True set to False to perform inplace binarization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR / CSC matrix and if axis is 1). See also -------- :class:`sklearn.preprocessing.Binarizer` to perform binarization using the ``Transformer`` API (e.g. as part of a preprocessing :class:`sklearn.pipeline.Pipeline`) """ X = check_array(X, accept_sparse=['csr', 'csc'], copy=copy) if sparse.issparse(X): if threshold < 0: raise ValueError('Cannot binarize a sparse matrix with threshold ' '< 0') cond = X.data > threshold not_cond = np.logical_not(cond) X.data[cond] = 1 X.data[not_cond] = 0 X.eliminate_zeros() else: cond = X > threshold not_cond = np.logical_not(cond) X[cond] = 1 X[not_cond] = 0 return X class Binarizer(BaseEstimator, TransformerMixin): """Binarize data (set feature values to 0 or 1) according to a threshold Values greater than the threshold map to 1, while values less than or equal to the threshold map to 0. With the default threshold of 0, only positive values map to 1. Binarization is a common operation on text count data where the analyst can decide to only consider the presence or absence of a feature rather than a quantified number of occurrences for instance. It can also be used as a pre-processing step for estimators that consider boolean random variables (e.g. modelled using the Bernoulli distribution in a Bayesian setting). Read more in the :ref:`User Guide <preprocessing_binarization>`. Parameters ---------- threshold : float, optional (0.0 by default) Feature values below or equal to this are replaced by 0, above it by 1. Threshold may not be less than 0 for operations on sparse matrices. copy : boolean, optional, default True set to False to perform inplace binarization and avoid a copy (if the input is already a numpy array or a scipy.sparse CSR matrix). Notes ----- If the input is a sparse matrix, only the non-zero values are subject to update by the Binarizer class. This estimator is stateless (besides constructor parameters), the fit method does nothing but is useful when used in a pipeline. """ def __init__(self, threshold=0.0, copy=True): self.threshold = threshold self.copy = copy def fit(self, X, y=None): """Do nothing and return the estimator unchanged This method is just there to implement the usual API and hence work in pipelines. """ check_array(X, accept_sparse='csr') return self def transform(self, X, y=None, copy=None): """Binarize each element of X Parameters ---------- X : array or scipy.sparse matrix with shape [n_samples, n_features] The data to binarize, element by element. scipy.sparse matrices should be in CSR format to avoid an un-necessary copy. """ copy = copy if copy is not None else self.copy return binarize(X, threshold=self.threshold, copy=copy) class KernelCenterer(BaseEstimator, TransformerMixin): """Center a kernel matrix Let K(x, z) be a kernel defined by phi(x)^T phi(z), where phi is a function mapping x to a Hilbert space. KernelCenterer centers (i.e., normalize to have zero mean) the data without explicitly computing phi(x). It is equivalent to centering phi(x) with sklearn.preprocessing.StandardScaler(with_std=False). Read more in the :ref:`User Guide <kernel_centering>`. """ def fit(self, K, y=None): """Fit KernelCenterer Parameters ---------- K : numpy array of shape [n_samples, n_samples] Kernel matrix. Returns ------- self : returns an instance of self. """ K = check_array(K) n_samples = K.shape[0] self.K_fit_rows_ = np.sum(K, axis=0) / n_samples self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples return self def transform(self, K, y=None, copy=True): """Center kernel matrix. Parameters ---------- K : numpy array of shape [n_samples1, n_samples2] Kernel matrix. copy : boolean, optional, default True Set to False to perform inplace computation. Returns ------- K_new : numpy array of shape [n_samples1, n_samples2] """ check_is_fitted(self, 'K_fit_all_') K = check_array(K) if copy: K = K.copy() K_pred_cols = (np.sum(K, axis=1) / self.K_fit_rows_.shape[0])[:, np.newaxis] K -= self.K_fit_rows_ K -= K_pred_cols K += self.K_fit_all_ return K def add_dummy_feature(X, value=1.0): """Augment dataset with an additional dummy feature. This is useful for fitting an intercept term with implementations which cannot otherwise fit it directly. Parameters ---------- X : array or scipy.sparse matrix with shape [n_samples, n_features] Data. value : float Value to use for the dummy feature. Returns ------- X : array or scipy.sparse matrix with shape [n_samples, n_features + 1] Same data with dummy feature added as first column. Examples -------- >>> from sklearn.preprocessing import add_dummy_feature >>> add_dummy_feature([[0, 1], [1, 0]]) array([[ 1., 0., 1.], [ 1., 1., 0.]]) """ X = check_array(X, accept_sparse=['csc', 'csr', 'coo']) n_samples, n_features = X.shape shape = (n_samples, n_features + 1) if sparse.issparse(X): if sparse.isspmatrix_coo(X): # Shift columns to the right. col = X.col + 1 # Column indices of dummy feature are 0 everywhere. col = np.concatenate((np.zeros(n_samples), col)) # Row indices of dummy feature are 0, ..., n_samples-1. row = np.concatenate((np.arange(n_samples), X.row)) # Prepend the dummy feature n_samples times. data = np.concatenate((np.ones(n_samples) * value, X.data)) return sparse.coo_matrix((data, (row, col)), shape) elif sparse.isspmatrix_csc(X): # Shift index pointers since we need to add n_samples elements. indptr = X.indptr + n_samples # indptr[0] must be 0. indptr = np.concatenate((np.array([0]), indptr)) # Row indices of dummy feature are 0, ..., n_samples-1. indices = np.concatenate((np.arange(n_samples), X.indices)) # Prepend the dummy feature n_samples times. data = np.concatenate((np.ones(n_samples) * value, X.data)) return sparse.csc_matrix((data, indices, indptr), shape) else: klass = X.__class__ return klass(add_dummy_feature(X.tocoo(), value)) else: return np.hstack((np.ones((n_samples, 1)) * value, X)) def _transform_selected(X, transform, selected="all", copy=True): """Apply a transform function to portion of selected features Parameters ---------- X : array-like or sparse matrix, shape=(n_samples, n_features) Dense array or sparse matrix. transform : callable A callable transform(X) -> X_transformed copy : boolean, optional Copy X even if it could be avoided. selected: "all" or array of indices or mask Specify which features to apply the transform to. Returns ------- X : array or sparse matrix, shape=(n_samples, n_features_new) """ if selected == "all": return transform(X) X = check_array(X, accept_sparse='csc', copy=copy) if len(selected) == 0: return X n_features = X.shape[1] ind = np.arange(n_features) sel = np.zeros(n_features, dtype=bool) sel[np.asarray(selected)] = True not_sel = np.logical_not(sel) n_selected = np.sum(sel) if n_selected == 0: # No features selected. return X elif n_selected == n_features: # All features selected. return transform(X) else: X_sel = transform(X[:, ind[sel]]) X_not_sel = X[:, ind[not_sel]] if sparse.issparse(X_sel) or sparse.issparse(X_not_sel): return sparse.hstack((X_sel, X_not_sel)) else: return np.hstack((X_sel, X_not_sel)) class OneHotEncoder(BaseEstimator, TransformerMixin): """Encode categorical integer features using a one-hot aka one-of-K scheme. The input to this transformer should be a matrix of integers, denoting the values taken on by categorical (discrete) features. The output will be a sparse matrix where each column corresponds to one possible value of one feature. It is assumed that input features take on values in the range [0, n_values). This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels. Read more in the :ref:`User Guide <preprocessing_categorical_features>`. Parameters ---------- n_values : 'auto', int or array of ints Number of values per feature. - 'auto' : determine value range from training data. - int : maximum value for all features. - array : maximum value per feature. categorical_features: "all" or array of indices or mask Specify what features are treated as categorical. - 'all' (default): All features are treated as categorical. - array of indices: Array of categorical feature indices. - mask: Array of length n_features and with dtype=bool. Non-categorical features are always stacked to the right of the matrix. dtype : number type, default=np.float Desired dtype of output. sparse : boolean, default=True Will return sparse matrix if set True else will return an array. handle_unknown : str, 'error' or 'ignore' Whether to raise an error or ignore if a unknown categorical feature is present during transform. Attributes ---------- active_features_ : array Indices for active features, meaning values that actually occur in the training set. Only available when n_values is ``'auto'``. feature_indices_ : array of shape (n_features,) Indices to feature ranges. Feature ``i`` in the original data is mapped to features from ``feature_indices_[i]`` to ``feature_indices_[i+1]`` (and then potentially masked by `active_features_` afterwards) n_values_ : array of shape (n_features,) Maximum number of values per feature. Examples -------- Given a dataset with three features and two samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder >>> enc = OneHotEncoder() >>> enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], \ [1, 0, 2]]) # doctest: +ELLIPSIS OneHotEncoder(categorical_features='all', dtype=<... 'float'>, handle_unknown='error', n_values='auto', sparse=True) >>> enc.n_values_ array([2, 3, 4]) >>> enc.feature_indices_ array([0, 2, 5, 9]) >>> enc.transform([[0, 1, 1]]).toarray() array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.]]) See also -------- sklearn.feature_extraction.DictVectorizer : performs a one-hot encoding of dictionary items (also handles string-valued features). sklearn.feature_extraction.FeatureHasher : performs an approximate one-hot encoding of dictionary items or strings. """ def __init__(self, n_values="auto", categorical_features="all", dtype=np.float, sparse=True, handle_unknown='error'): self.n_values = n_values self.categorical_features = categorical_features self.dtype = dtype self.sparse = sparse self.handle_unknown = handle_unknown def fit(self, X, y=None): """Fit OneHotEncoder to X. Parameters ---------- X : array-like, shape=(n_samples, n_feature) Input array of type int. Returns ------- self """ self.fit_transform(X) return self def _fit_transform(self, X): """Assumes X contains only categorical features.""" X = check_array(X, dtype=np.int) if np.any(X < 0): raise ValueError("X needs to contain only non-negative integers.") n_samples, n_features = X.shape if self.n_values == 'auto': n_values = np.max(X, axis=0) + 1 elif isinstance(self.n_values, numbers.Integral): if (np.max(X, axis=0) >= self.n_values).any(): raise ValueError("Feature out of bounds for n_values=%d" % self.n_values) n_values = np.empty(n_features, dtype=np.int) n_values.fill(self.n_values) else: try: n_values = np.asarray(self.n_values, dtype=int) except (ValueError, TypeError): raise TypeError("Wrong type for parameter `n_values`. Expected" " 'auto', int or array of ints, got %r" % type(X)) if n_values.ndim < 1 or n_values.shape[0] != X.shape[1]: raise ValueError("Shape mismatch: if n_values is an array," " it has to be of shape (n_features,).") self.n_values_ = n_values n_values = np.hstack([[0], n_values]) indices = np.cumsum(n_values) self.feature_indices_ = indices column_indices = (X + indices[:-1]).ravel() row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), n_features) data = np.ones(n_samples * n_features) out = sparse.coo_matrix((data, (row_indices, column_indices)), shape=(n_samples, indices[-1]), dtype=self.dtype).tocsr() if self.n_values == 'auto': mask = np.array(out.sum(axis=0)).ravel() != 0 active_features = np.where(mask)[0] out = out[:, active_features] self.active_features_ = active_features return out if self.sparse else out.toarray() def fit_transform(self, X, y=None): """Fit OneHotEncoder to X, then transform X. Equivalent to self.fit(X).transform(X), but more convenient and more efficient. See fit for the parameters, transform for the return value. """ return _transform_selected(X, self._fit_transform, self.categorical_features, copy=True) def _transform(self, X): """Assumes X contains only categorical features.""" X = check_array(X, dtype=np.int) if np.any(X < 0): raise ValueError("X needs to contain only non-negative integers.") n_samples, n_features = X.shape indices = self.feature_indices_ if n_features != indices.shape[0] - 1: raise ValueError("X has different shape than during fitting." " Expected %d, got %d." % (indices.shape[0] - 1, n_features)) # We use only those catgorical features of X that are known using fit. # i.e lesser than n_values_ using mask. # This means, if self.handle_unknown is "ignore", the row_indices and # col_indices corresponding to the unknown categorical feature are # ignored. mask = (X < self.n_values_).ravel() if np.any(~mask): if self.handle_unknown not in ['error', 'ignore']: raise ValueError("handle_unknown should be either error or " "unknown got %s" % self.handle_unknown) if self.handle_unknown == 'error': raise ValueError("unknown categorical feature present %s " "during transform." % X[~mask]) column_indices = (X + indices[:-1]).ravel()[mask] row_indices = np.repeat(np.arange(n_samples, dtype=np.int32), n_features)[mask] data = np.ones(np.sum(mask)) out = sparse.coo_matrix((data, (row_indices, column_indices)), shape=(n_samples, indices[-1]), dtype=self.dtype).tocsr() if self.n_values == 'auto': out = out[:, self.active_features_] return out if self.sparse else out.toarray() def transform(self, X): """Transform X using one-hot encoding. Parameters ---------- X : array-like, shape=(n_samples, n_features) Input array of type int. Returns ------- X_out : sparse matrix if sparse=True else a 2-d array, dtype=int Transformed input. """ return _transform_selected(X, self._transform, self.categorical_features, copy=True)
bsd-3-clause
uche40/appmaker
public/vendor/bootstrap/test-infra/s3_cache.py
1700
3523
#!/usr/bin/env python2.7 from __future__ import absolute_import, unicode_literals, print_function, division from sys import argv from os import environ, stat, remove as _delete_file from os.path import isfile, dirname, basename, abspath from hashlib import sha256 from subprocess import check_call as run from boto.s3.connection import S3Connection from boto.s3.key import Key from boto.exception import S3ResponseError NEED_TO_UPLOAD_MARKER = '.need-to-upload' BYTES_PER_MB = 1024 * 1024 try: BUCKET_NAME = environ['TWBS_S3_BUCKET'] except KeyError: raise SystemExit("TWBS_S3_BUCKET environment variable not set!") def _sha256_of_file(filename): hasher = sha256() with open(filename, 'rb') as input_file: hasher.update(input_file.read()) file_hash = hasher.hexdigest() print('sha256({}) = {}'.format(filename, file_hash)) return file_hash def _delete_file_quietly(filename): try: _delete_file(filename) except (OSError, IOError): pass def _tarball_size(directory): kib = stat(_tarball_filename_for(directory)).st_size // BYTES_PER_MB return "{} MiB".format(kib) def _tarball_filename_for(directory): return abspath('./{}.tar.gz'.format(basename(directory))) def _create_tarball(directory): print("Creating tarball of {}...".format(directory)) run(['tar', '-czf', _tarball_filename_for(directory), '-C', dirname(directory), basename(directory)]) def _extract_tarball(directory): print("Extracting tarball of {}...".format(directory)) run(['tar', '-xzf', _tarball_filename_for(directory), '-C', dirname(directory)]) def download(directory): _delete_file_quietly(NEED_TO_UPLOAD_MARKER) try: print("Downloading {} tarball from S3...".format(friendly_name)) key.get_contents_to_filename(_tarball_filename_for(directory)) except S3ResponseError as err: open(NEED_TO_UPLOAD_MARKER, 'a').close() print(err) raise SystemExit("Cached {} download failed!".format(friendly_name)) print("Downloaded {}.".format(_tarball_size(directory))) _extract_tarball(directory) print("{} successfully installed from cache.".format(friendly_name)) def upload(directory): _create_tarball(directory) print("Uploading {} tarball to S3... ({})".format(friendly_name, _tarball_size(directory))) key.set_contents_from_filename(_tarball_filename_for(directory)) print("{} cache successfully updated.".format(friendly_name)) _delete_file_quietly(NEED_TO_UPLOAD_MARKER) if __name__ == '__main__': # Uses environment variables: # AWS_ACCESS_KEY_ID -- AWS Access Key ID # AWS_SECRET_ACCESS_KEY -- AWS Secret Access Key argv.pop(0) if len(argv) != 4: raise SystemExit("USAGE: s3_cache.py <download | upload> <friendly name> <dependencies file> <directory>") mode, friendly_name, dependencies_file, directory = argv conn = S3Connection() bucket = conn.lookup(BUCKET_NAME, validate=False) if bucket is None: raise SystemExit("Could not access bucket!") dependencies_file_hash = _sha256_of_file(dependencies_file) key = Key(bucket, dependencies_file_hash) key.storage_class = 'REDUCED_REDUNDANCY' if mode == 'download': download(directory) elif mode == 'upload': if isfile(NEED_TO_UPLOAD_MARKER): # FIXME upload(directory) else: print("No need to upload anything.") else: raise SystemExit("Unrecognized mode {!r}".format(mode))
mpl-2.0
yangdongsheng/autotest
scheduler/drone_manager.py
3
25405
import os, heapq, traceback try: import autotest.common as common except ImportError: import common import logging from autotest.client.shared import error from autotest.client.shared.settings import settings from autotest.scheduler import email_manager, drone_utility, drones from autotest.scheduler import scheduler_config # results on drones will be placed under the drone_installation_directory in a # directory with this name _DRONE_RESULTS_DIR_SUFFIX = 'results' WORKING_DIRECTORY = object() # see execute_command() AUTOSERV_PID_FILE = '.autoserv_execute' CRASHINFO_PID_FILE = '.collect_crashinfo_execute' PARSER_PID_FILE = '.parser_execute' ARCHIVER_PID_FILE = '.archiver_execute' ALL_PIDFILE_NAMES = (AUTOSERV_PID_FILE, CRASHINFO_PID_FILE, PARSER_PID_FILE, ARCHIVER_PID_FILE) class DroneManagerError(Exception): pass class CustomEquals(object): def _id(self): raise NotImplementedError def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented return self._id() == other._id() def __ne__(self, other): return not self == other def __hash__(self): return hash(self._id()) class Process(CustomEquals): def __init__(self, hostname, pid, ppid=None): self.hostname = hostname self.pid = pid self.ppid = ppid def _id(self): return (self.hostname, self.pid) def __str__(self): return '%s/%s' % (self.hostname, self.pid) def __repr__(self): return super(Process, self).__repr__() + '<%s>' % self class PidfileId(CustomEquals): def __init__(self, path): self.path = path def _id(self): return self.path def __str__(self): return str(self.path) class _PidfileInfo(object): age = 0 num_processes = None class PidfileContents(object): process = None exit_status = None num_tests_failed = None def is_invalid(self): return False def is_running(self): return self.process and not self.exit_status class InvalidPidfile(object): def __init__(self, error): self.error = error def is_invalid(self): return True def is_running(self): return False def __str__(self): return self.error class _DroneHeapWrapper(object): """Wrapper to compare drones based on used_capacity(). These objects can be used to keep a heap of drones by capacity. """ def __init__(self, drone): self.drone = drone def __cmp__(self, other): assert isinstance(other, _DroneHeapWrapper) return cmp(self.drone.used_capacity(), other.drone.used_capacity()) class DroneManager(object): """ This class acts as an interface from the scheduler to drones, whether it be only a single "drone" for localhost or multiple remote drones. All paths going into and out of this class are relative to the full results directory, except for those returns by absolute_path(). """ def __init__(self): # absolute path of base results dir self._results_dir = None # holds Process objects self._process_set = set() # maps PidfileId to PidfileContents self._pidfiles = {} # same as _pidfiles self._pidfiles_second_read = {} # maps PidfileId to _PidfileInfo self._registered_pidfile_info = {} # used to generate unique temporary paths self._temporary_path_counter = 0 # maps hostname to Drone object self._drones = {} self._results_drone = None # maps results dir to dict mapping file path to contents self._attached_files = {} # heapq of _DroneHeapWrappers self._drone_queue = [] def initialize(self, base_results_dir, drone_hostnames, results_repository_hostname): self._results_dir = base_results_dir for hostname in drone_hostnames: self._add_drone(hostname) if not self._drones: # all drones failed to initialize raise DroneManagerError('No valid drones found') self.refresh_drone_configs() logging.info('Using results repository on %s', results_repository_hostname) self._results_drone = drones.get_drone(results_repository_hostname) results_installation_dir = settings.get_value( scheduler_config.CONFIG_SECTION, 'results_host_installation_directory', default=None) if results_installation_dir: self._results_drone.set_autotest_install_dir( results_installation_dir) # don't initialize() the results drone - we don't want to clear out any # directories and we don't need to kill any processes def reinitialize_drones(self): self._call_all_drones('initialize', self._results_dir) def shutdown(self): for drone in self.get_drones(): drone.shutdown() def _get_max_pidfile_refreshes(self): """ Normally refresh() is called on every monitor_db.Dispatcher.tick(). @returns: The number of refresh() calls before we forget a pidfile. """ pidfile_timeout = settings.get_value( scheduler_config.CONFIG_SECTION, 'max_pidfile_refreshes', type=int, default=2000) return pidfile_timeout def _add_drone(self, hostname): logging.info('Adding drone %s' % hostname) drone = drones.get_drone(hostname) if drone: self._drones[drone.hostname] = drone drone.call('initialize', self.absolute_path('')) def _remove_drone(self, hostname): self._drones.pop(hostname, None) def refresh_drone_configs(self): """ Reread global config options for all drones. """ section = scheduler_config.CONFIG_SECTION settings.parse_config_file() for hostname, drone in self._drones.iteritems(): disabled = settings.get_value(section, '%s_disabled' % hostname, default='') drone.enabled = not bool(disabled) drone.max_processes = settings.get_value( section, '%s_max_processes' % hostname, type=int, default=scheduler_config.config.max_processes_per_drone) allowed_users = settings.get_value(section, '%s_users' % hostname, default=None) if allowed_users is not None: allowed_users = set(allowed_users.split()) drone.allowed_users = allowed_users self._reorder_drone_queue() # max_processes may have changed def get_drones(self): return self._drones.itervalues() def _get_drone_for_process(self, process): return self._drones[process.hostname] def _get_drone_for_pidfile_id(self, pidfile_id): pidfile_contents = self.get_pidfile_contents(pidfile_id) assert pidfile_contents.process is not None return self._get_drone_for_process(pidfile_contents.process) def _drop_old_pidfiles(self): # use items() since the dict is modified in unregister_pidfile() for pidfile_id, info in self._registered_pidfile_info.items(): if info.age > self._get_max_pidfile_refreshes(): logging.warning('dropping leaked pidfile %s', pidfile_id) self.unregister_pidfile(pidfile_id) else: info.age += 1 def _reset(self): self._process_set = set() self._pidfiles = {} self._pidfiles_second_read = {} self._drone_queue = [] def _call_all_drones(self, method, *args, **kwargs): all_results = {} for drone in self.get_drones(): all_results[drone] = drone.call(method, *args, **kwargs) return all_results def _parse_pidfile(self, drone, raw_contents): contents = PidfileContents() if not raw_contents: return contents lines = raw_contents.splitlines() if len(lines) > 3: return InvalidPidfile('Corrupt pid file (%d lines):\n%s' % (len(lines), lines)) try: pid = int(lines[0]) contents.process = Process(drone.hostname, pid) # if len(lines) == 2, assume we caught Autoserv between writing # exit_status and num_failed_tests, so just ignore it and wait for # the next cycle if len(lines) == 3: contents.exit_status = int(lines[1]) contents.num_tests_failed = int(lines[2]) except ValueError, exc: return InvalidPidfile('Corrupt pid file: ' + str(exc.args)) return contents def _process_pidfiles(self, drone, pidfiles, store_in_dict): for pidfile_path, contents in pidfiles.iteritems(): pidfile_id = PidfileId(pidfile_path) contents = self._parse_pidfile(drone, contents) store_in_dict[pidfile_id] = contents def _add_process(self, drone, process_info): process = Process(drone.hostname, int(process_info['pid']), int(process_info['ppid'])) self._process_set.add(process) def _add_autoserv_process(self, drone, process_info): assert process_info['comm'] in ['autoserv', 'autotest-remote'] # only root autoserv processes have pgid == pid if process_info['pgid'] != process_info['pid']: return self._add_process(drone, process_info) def _enqueue_drone(self, drone): heapq.heappush(self._drone_queue, _DroneHeapWrapper(drone)) def _reorder_drone_queue(self): heapq.heapify(self._drone_queue) def _compute_active_processes(self, drone): drone.active_processes = 0 for pidfile_id, contents in self._pidfiles.iteritems(): is_running = contents.exit_status is None on_this_drone = (contents.process and contents.process.hostname == drone.hostname) if is_running and on_this_drone: info = self._registered_pidfile_info[pidfile_id] if info.num_processes is not None: drone.active_processes += info.num_processes def refresh(self): """ Called at the beginning of a scheduler cycle to refresh all process information. """ self._reset() self._drop_old_pidfiles() pidfile_paths = [pidfile_id.path for pidfile_id in self._registered_pidfile_info] all_results = self._call_all_drones('refresh', pidfile_paths) for drone, results_list in all_results.iteritems(): results = results_list[0] for process_info in results['autoserv_processes']: self._add_autoserv_process(drone, process_info) for process_info in results['parse_processes']: self._add_process(drone, process_info) self._process_pidfiles(drone, results['pidfiles'], self._pidfiles) self._process_pidfiles(drone, results['pidfiles_second_read'], self._pidfiles_second_read) self._compute_active_processes(drone) if drone.enabled: self._enqueue_drone(drone) def execute_actions(self): """ Called at the end of a scheduler cycle to execute all queued actions on drones. """ for drone in self._drones.values(): drone.execute_queued_calls() try: self._results_drone.execute_queued_calls() except error.AutoservError: warning = ('Results repository failed to execute calls:\n' + traceback.format_exc()) email_manager.manager.enqueue_notify_email( 'Results repository error', warning) self._results_drone.clear_call_queue() def get_orphaned_autoserv_processes(self): """ Returns a set of Process objects for orphaned processes only. """ return set(process for process in self._process_set if process.ppid == 1) def kill_process(self, process): """ Kill the given process. """ logging.info('killing %s', process) drone = self._get_drone_for_process(process) drone.queue_call('kill_process', process) def _ensure_directory_exists(self, path): if not os.path.exists(path): os.makedirs(path) def total_running_processes(self): return sum(drone.active_processes for drone in self.get_drones()) def max_runnable_processes(self, username, drone_hostnames_allowed): """ Return the maximum number of processes that can be run (in a single execution) given the current load on drones. @param username: login of user to run a process. may be None. @param drone_hostnames_allowed: list of drones that can be used. May be None """ usable_drone_wrappers = [wrapper for wrapper in self._drone_queue if wrapper.drone.usable_by(username) and (drone_hostnames_allowed is None or wrapper.drone.hostname in drone_hostnames_allowed)] if not usable_drone_wrappers: # all drones disabled or inaccessible return 0 runnable_processes = [ wrapper.drone.max_processes - wrapper.drone.active_processes for wrapper in usable_drone_wrappers] return max([0] + runnable_processes) def _least_loaded_drone(self, drones): drone_to_use = drones[0] for drone in drones[1:]: if drone.used_capacity() < drone_to_use.used_capacity(): drone_to_use = drone return drone_to_use def _choose_drone_for_execution(self, num_processes, username, drone_hostnames_allowed): # cycle through drones is order of increasing used capacity until # we find one that can handle these processes checked_drones = [] usable_drones = [] drone_to_use = None while self._drone_queue: drone = heapq.heappop(self._drone_queue).drone checked_drones.append(drone) logging.info('Checking drone %s', drone.hostname) if not drone.usable_by(username): continue drone_allowed = (drone_hostnames_allowed is None or drone.hostname in drone_hostnames_allowed) if not drone_allowed: logging.debug('Drone %s not allowed: ', drone.hostname) continue usable_drones.append(drone) if drone.active_processes + num_processes <= drone.max_processes: drone_to_use = drone break logging.info('Drone %s has %d active + %s requested > %s max', drone.hostname, drone.active_processes, num_processes, drone.max_processes) if not drone_to_use and usable_drones: drone_summary = ','.join('%s %s/%s' % (drone.hostname, drone.active_processes, drone.max_processes) for drone in usable_drones) logging.error('No drone has capacity to handle %d processes (%s) ' 'for user %s', num_processes, drone_summary, username) drone_to_use = self._least_loaded_drone(usable_drones) # refill _drone_queue for drone in checked_drones: self._enqueue_drone(drone) return drone_to_use def _substitute_working_directory_into_command(self, command, working_directory): for i, item in enumerate(command): if item is WORKING_DIRECTORY: command[i] = working_directory def execute_command(self, command, working_directory, pidfile_name, num_processes, log_file=None, paired_with_pidfile=None, username=None, drone_hostnames_allowed=None): """ Execute the given command, taken as an argv list. @param command: command to execute as a list. if any item is WORKING_DIRECTORY, the absolute path to the working directory will be substituted for it. @param working_directory: directory in which the pidfile will be written @param pidfile_name: name of the pidfile this process will write @param num_processes: number of processes to account for from this execution @param log_file (optional): path (in the results repository) to hold command output. @param paired_with_pidfile (optional): a PidfileId for an already-executed process; the new process will execute on the same drone as the previous process. @param username (optional): login of the user responsible for this process. @param drone_hostnames_allowed (optional): hostnames of the drones that this command is allowed to execute on """ abs_working_directory = self.absolute_path(working_directory) if not log_file: log_file = self.get_temporary_path('execute') log_file = self.absolute_path(log_file) self._substitute_working_directory_into_command(command, abs_working_directory) if paired_with_pidfile: drone = self._get_drone_for_pidfile_id(paired_with_pidfile) else: drone = self._choose_drone_for_execution(num_processes, username, drone_hostnames_allowed) if not drone: raise DroneManagerError('command failed; no drones available: %s' % command) logging.info("command = %s" % command) logging.info('log file = %s:%s' % (drone.hostname, log_file)) self._write_attached_files(working_directory, drone) drone.queue_call('execute_command', command, abs_working_directory, log_file, pidfile_name) drone.active_processes += num_processes self._reorder_drone_queue() pidfile_path = os.path.join(abs_working_directory, pidfile_name) pidfile_id = PidfileId(pidfile_path) self.register_pidfile(pidfile_id) self._registered_pidfile_info[pidfile_id].num_processes = num_processes return pidfile_id def get_pidfile_id_from(self, execution_tag, pidfile_name): path = os.path.join(self.absolute_path(execution_tag), pidfile_name) return PidfileId(path) def register_pidfile(self, pidfile_id): """ Indicate that the DroneManager should look for the given pidfile when refreshing. """ if pidfile_id not in self._registered_pidfile_info: logging.info('monitoring pidfile %s', pidfile_id) self._registered_pidfile_info[pidfile_id] = _PidfileInfo() self._reset_pidfile_age(pidfile_id) def _reset_pidfile_age(self, pidfile_id): if pidfile_id in self._registered_pidfile_info: self._registered_pidfile_info[pidfile_id].age = 0 def unregister_pidfile(self, pidfile_id): if pidfile_id in self._registered_pidfile_info: logging.info('forgetting pidfile %s', pidfile_id) del self._registered_pidfile_info[pidfile_id] def declare_process_count(self, pidfile_id, num_processes): self._registered_pidfile_info[pidfile_id].num_processes = num_processes def get_pidfile_contents(self, pidfile_id, use_second_read=False): """ Retrieve a PidfileContents object for the given pidfile_id. If use_second_read is True, use results that were read after the processes were checked, instead of before. """ self._reset_pidfile_age(pidfile_id) if use_second_read: pidfile_map = self._pidfiles_second_read else: pidfile_map = self._pidfiles return pidfile_map.get(pidfile_id, PidfileContents()) def is_process_running(self, process): """ Check if the given process is in the running process list. """ return process in self._process_set def get_temporary_path(self, base_name): """ Get a new temporary path guaranteed to be unique across all drones for this scheduler execution. """ self._temporary_path_counter += 1 return os.path.join(drone_utility._TEMPORARY_DIRECTORY, '%s.%s' % (base_name, self._temporary_path_counter)) def absolute_path(self, path, on_results_repository=False): if on_results_repository: base_dir = self._results_dir else: output_dir = settings.get_value('COMMON', 'test_output_dir', default="") if output_dir: base_dir = output_dir else: base_dir = drones.AUTOTEST_INSTALL_DIR base_dir = os.path.join(base_dir, _DRONE_RESULTS_DIR_SUFFIX) return os.path.join(base_dir, path) def _copy_results_helper(self, process, source_path, destination_path, to_results_repository=False): full_source = self.absolute_path(source_path) full_destination = self.absolute_path( destination_path, on_results_repository=to_results_repository) source_drone = self._get_drone_for_process(process) if to_results_repository: source_drone.send_file_to(self._results_drone, full_source, full_destination, can_fail=True) else: source_drone.queue_call('copy_file_or_directory', full_source, full_destination) def copy_to_results_repository(self, process, source_path, destination_path=None): """ Copy results from the given process at source_path to destination_path in the results repository. """ if destination_path is None: destination_path = source_path self._copy_results_helper(process, source_path, destination_path, to_results_repository=True) def copy_results_on_drone(self, process, source_path, destination_path): """ Copy a results directory from one place to another on the drone. """ self._copy_results_helper(process, source_path, destination_path) def _write_attached_files(self, results_dir, drone): attached_files = self._attached_files.pop(results_dir, {}) for file_path, contents in attached_files.iteritems(): drone.queue_call('write_to_file', self.absolute_path(file_path), contents) def attach_file_to_execution(self, results_dir, file_contents, file_path=None): """ When the process for the results directory is executed, the given file contents will be placed in a file on the drone. Returns the path at which the file will be placed. """ if not file_path: file_path = self.get_temporary_path('attach') files_for_execution = self._attached_files.setdefault(results_dir, {}) assert file_path not in files_for_execution files_for_execution[file_path] = file_contents return file_path def write_lines_to_file(self, file_path, lines, paired_with_process=None): """ Write the given lines (as a list of strings) to a file. If paired_with_process is given, the file will be written on the drone running the given Process. Otherwise, the file will be written to the results repository. """ file_contents = '\n'.join(lines) + '\n' if paired_with_process: drone = self._get_drone_for_process(paired_with_process) on_results_repository = False else: drone = self._results_drone on_results_repository = True full_path = self.absolute_path( file_path, on_results_repository=on_results_repository) drone.queue_call('write_to_file', full_path, file_contents) _the_instance = None def instance(): if _the_instance is None: _set_instance(DroneManager()) return _the_instance def _set_instance(instance): # usable for testing global _the_instance _the_instance = instance
gpl-2.0
dagwieers/ansible
lib/ansible/modules/network/fortios/fortios_authentication_rule.py
24
12053
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2018 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # # the lib use python logging can get it if the following is set in your # Ansible config. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fortios_authentication_rule short_description: Configure Authentication Rules in Fortinet's FortiOS and FortiGate. description: - This module is able to configure a FortiGate or FortiOS by allowing the user to configure authentication feature and rule category. Examples includes all options and need to be adjusted to datasources before usage. Tested with FOS v6.0.2 version_added: "2.8" author: - Miguel Angel Munoz (@mamunozgonzalez) - Nicolas Thomas (@thomnico) notes: - Requires fortiosapi library developed by Fortinet - Run as a local_action in your playbook requirements: - fortiosapi>=0.9.8 options: host: description: - FortiOS or FortiGate ip address. required: true username: description: - FortiOS or FortiGate username. required: true password: description: - FortiOS or FortiGate password. default: "" vdom: description: - Virtual domain, among those defined previously. A vdom is a virtual instance of the FortiGate that can be configured and used as a different unit. default: root https: description: - Indicates if the requests towards FortiGate must use HTTPS protocol type: bool default: false authentication_rule: description: - Configure Authentication Rules. default: null suboptions: state: description: - Indicates whether to create or remove the object choices: - present - absent active-auth-method: description: - Select an active authentication method. Source authentication.scheme.name. comments: description: - Comment. ip-based: description: - Enable/disable IP-based authentication. Once a user authenticates all traffic from the IP address the user authenticated from is allowed. choices: - enable - disable name: description: - Authentication rule name. required: true protocol: description: - Select the protocol to use for authentication (default = http). Users connect to the FortiGate using this protocol and are asked to authenticate. choices: - http - ftp - socks - ssh srcaddr: description: - Select an IPv4 source address from available options. Required for web proxy authentication. suboptions: name: description: - Address name. Source firewall.address.name firewall.addrgrp.name firewall.proxy-address.name firewall.proxy-addrgrp.name. required: true srcaddr6: description: - Select an IPv6 source address. Required for web proxy authentication. suboptions: name: description: - Address name. Source firewall.address6.name firewall.addrgrp6.name. required: true sso-auth-method: description: - Select a single-sign on (SSO) authentication method. Source authentication.scheme.name. status: description: - Enable/disable this authentication rule. choices: - enable - disable transaction-based: description: - Enable/disable transaction based authentication (default = disable). choices: - enable - disable web-auth-cookie: description: - Enable/disable Web authentication cookies (default = disable). choices: - enable - disable ''' EXAMPLES = ''' - hosts: localhost vars: host: "192.168.122.40" username: "admin" password: "" vdom: "root" tasks: - name: Configure Authentication Rules. fortios_authentication_rule: host: "{{ host }}" username: "{{ username }}" password: "{{ password }}" vdom: "{{ vdom }}" authentication_rule: state: "present" active-auth-method: "<your_own_value> (source authentication.scheme.name)" comments: "<your_own_value>" ip-based: "enable" name: "default_name_6" protocol: "http" srcaddr: - name: "default_name_9 (source firewall.address.name firewall.addrgrp.name firewall.proxy-address.name firewall.proxy-addrgrp.name)" srcaddr6: - name: "default_name_11 (source firewall.address6.name firewall.addrgrp6.name)" sso-auth-method: "<your_own_value> (source authentication.scheme.name)" status: "enable" transaction-based: "enable" web-auth-cookie: "enable" ''' RETURN = ''' build: description: Build number of the fortigate image returned: always type: str sample: '1547' http_method: description: Last method used to provision the content into FortiGate returned: always type: str sample: 'PUT' http_status: description: Last result given by FortiGate on last operation applied returned: always type: str sample: "200" mkey: description: Master key (id) used in the last call to FortiGate returned: success type: str sample: "id" name: description: Name of the table used to fulfill the request returned: always type: str sample: "urlfilter" path: description: Path of the table used to fulfill the request returned: always type: str sample: "webfilter" revision: description: Internal revision number returned: always type: str sample: "17.0.2.10658" serial: description: Serial number of the unit returned: always type: str sample: "FGVMEVYYQT3AB5352" status: description: Indication of the operation's result returned: always type: str sample: "success" vdom: description: Virtual domain used returned: always type: str sample: "root" version: description: Version of the FortiGate returned: always type: str sample: "v5.6.3" ''' from ansible.module_utils.basic import AnsibleModule fos = None def login(data): host = data['host'] username = data['username'] password = data['password'] fos.debug('on') if 'https' in data and not data['https']: fos.https('off') else: fos.https('on') fos.login(host, username, password) def filter_authentication_rule_data(json): option_list = ['active-auth-method', 'comments', 'ip-based', 'name', 'protocol', 'srcaddr', 'srcaddr6', 'sso-auth-method', 'status', 'transaction-based', 'web-auth-cookie'] dictionary = {} for attribute in option_list: if attribute in json and json[attribute] is not None: dictionary[attribute] = json[attribute] return dictionary def authentication_rule(data, fos): vdom = data['vdom'] authentication_rule_data = data['authentication_rule'] filtered_data = filter_authentication_rule_data(authentication_rule_data) if authentication_rule_data['state'] == "present": return fos.set('authentication', 'rule', data=filtered_data, vdom=vdom) elif authentication_rule_data['state'] == "absent": return fos.delete('authentication', 'rule', mkey=filtered_data['name'], vdom=vdom) def fortios_authentication(data, fos): login(data) methodlist = ['authentication_rule'] for method in methodlist: if data[method]: resp = eval(method)(data, fos) break fos.logout() return not resp['status'] == "success", resp['status'] == "success", resp def main(): fields = { "host": {"required": True, "type": "str"}, "username": {"required": True, "type": "str"}, "password": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": "False"}, "authentication_rule": { "required": False, "type": "dict", "options": { "state": {"required": True, "type": "str", "choices": ["present", "absent"]}, "active-auth-method": {"required": False, "type": "str"}, "comments": {"required": False, "type": "str"}, "ip-based": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "name": {"required": True, "type": "str"}, "protocol": {"required": False, "type": "str", "choices": ["http", "ftp", "socks", "ssh"]}, "srcaddr": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "srcaddr6": {"required": False, "type": "list", "options": { "name": {"required": True, "type": "str"} }}, "sso-auth-method": {"required": False, "type": "str"}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "transaction-based": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "web-auth-cookie": {"required": False, "type": "str", "choices": ["enable", "disable"]} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") global fos fos = FortiOSAPI() is_error, has_changed, result = fortios_authentication(module.params, fos) if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result) if __name__ == '__main__': main()
gpl-3.0
ryfeus/lambda-packs
pytorch/source/caffe2/python/cached_reader.py
1
4306
## @package cached_reader # Module caffe2.python.cached_reader from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os from caffe2.python import core from caffe2.python.db_file_reader import DBFileReader from caffe2.python.pipeline import pipe from caffe2.python.task import Cluster, TaskGroup class CachedReader(DBFileReader): default_name_suffix = 'cached_reader' """Reader with persistent in-file cache. Example usage: cached_reader = CachedReader( reader, db_path='/tmp/cache.db', db_type='LevelDB', ) build_cache_step = cached_reader.build_cache_step() with LocalSession() as session: session.run(build_cache_step) Every time new CachedReader is created, it's expected that db_path exists before calling .setup_ex(...) and .read(...). If db_path doesn't exist, it's expected build_cache_step to be called first to build a cache at db_path. build_cache_step will check existence of provided db_path and in case it's missing will initialize it by reading data from original reader. All consequent attempts to read will ignore original reader (i.e. no additional data will be read from it). Args: original_reader: Reader. If provided, it's the original reader used to build the cache file. db_path: str. db_type: str. DB type of file. A db_type is registed by `REGISTER_CAFFE2_DB(<db_type>, <DB Class>)`. Default to 'LevelDB'. name: str or None. Name of CachedReader. Optional name to prepend to blobs that will store the data. Default to '<db_name>_<default_name_suffix>'. batch_size: int. How many examples are read for each time the read_net is run. """ def __init__( self, original_reader, db_path, db_type='LevelDB', name=None, batch_size=100, ): assert original_reader is not None, "original_reader can't be None" self.original_reader = original_reader super(CachedReader, self).__init__( db_path, db_type, name, batch_size, ) def _init_reader_schema(self, *args, **kwargs): """Prepare the reader schema. Since an original reader is given, use it's schema as ground truth. Returns: schema: schema.Struct. Used in Reader.__init__(...). """ return self.original_reader._schema def build_cache_step(self, overwrite=False): """Build a step for generating cache DB file. If self.db_path exists and not overwritting, build an empty step. Overwise, build a step as follows. Pipe original reader to the _DatasetWriter, so that dataset field blobs are populated. Then save these blobs into a file. Args: overwrite: bool. If true, ignore the existing file and build a new one overwritting the existing one anyway. Returns: build_cache_step: ExcutionStep. The step to be run for building a cache DB file. """ if os.path.exists(self.db_path) and not overwrite: # cache already exists, no need to rebuild it return core.execution_step('build_step', []) init_net = core.Net('init') self._init_field_blobs_as_empty(init_net) with Cluster(), core.NameScope(self.name), TaskGroup() as copy_tg: pipe(self.original_reader, self.ds.writer(), num_threads=16) copy_step = copy_tg.to_task().get_step() save_net = core.Net('save') self._save_field_blobs_to_db_file(save_net) return core.execution_step('build_cache', [init_net, copy_step, save_net]) def _save_field_blobs_to_db_file(self, net): """Save dataset field blobs to a DB file at db_path""" net.Save( self.ds.get_blobs(), [], db=self.db_path, db_type=self.db_type, blob_name_overrides=self.ds.field_names(), absolute_path=True, )
mit
kmoocdev2/edx-platform
openedx/core/djangoapps/ccxcon/api.py
24
5194
""" Module containing API functions for the CCXCon """ import logging import urlparse from django.core.exceptions import ValidationError from django.core.validators import URLValidator from django.http import Http404 from oauthlib.oauth2 import BackendApplicationClient from requests_oauthlib import OAuth2Session from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED from lms.djangoapps.courseware.courses import get_course_by_id from openedx.core.djangoapps.models.course_details import CourseDetails from student.models import anonymous_id_for_user from student.roles import CourseInstructorRole from .models import CCXCon log = logging.getLogger(__name__) CCXCON_COURSEXS_URL = '/api/v1/coursexs/' CCXCON_TOKEN_URL = '/o/token/' CCXCON_REQUEST_TIMEOUT = 30 class CCXConnServerError(Exception): """ Custom exception to be raised in case there is any issue with the request to the server """ def is_valid_url(url): """ Helper function used to check if a string is a valid url. Args: url (str): the url string to be validated Returns: bool: whether the url is valid or not """ validate = URLValidator() try: validate(url) return True except ValidationError: return False def get_oauth_client(server_token_url, client_id, client_secret): """ Function that creates an oauth client and fetches a token. It intentionally doesn't handle errors. Args: server_token_url (str): server URL where to get an authentication token client_id (str): oauth client ID client_secret (str): oauth client secret Returns: OAuth2Session: an instance of OAuth2Session with a token """ if not is_valid_url(server_token_url): return client = BackendApplicationClient(client_id=client_id) oauth_ccxcon = OAuth2Session(client=client) oauth_ccxcon.fetch_token( token_url=server_token_url, client_id=client_id, client_secret=client_secret, timeout=CCXCON_REQUEST_TIMEOUT ) return oauth_ccxcon def course_info_to_ccxcon(course_key): """ Function that gathers informations about the course and makes a post request to a CCXCon with the data. Args: course_key (CourseLocator): the master course key """ try: course = get_course_by_id(course_key) except Http404: log.error('Master Course with key "%s" not found', unicode(course_key)) return if not course.enable_ccx: log.debug('ccx not enabled for course key "%s"', unicode(course_key)) return if not course.ccx_connector: log.debug('ccx connector not defined for course key "%s"', unicode(course_key)) return if not is_valid_url(course.ccx_connector): log.error( 'ccx connector URL "%s" for course key "%s" is not a valid URL.', course.ccx_connector, unicode(course_key) ) return # get the oauth credential for this URL try: ccxcon = CCXCon.objects.get(url=course.ccx_connector) except CCXCon.DoesNotExist: log.error('ccx connector Oauth credentials not configured for URL "%s".', course.ccx_connector) return # get an oauth client with a valid token oauth_ccxcon = get_oauth_client( server_token_url=urlparse.urljoin(course.ccx_connector, CCXCON_TOKEN_URL), client_id=ccxcon.oauth_client_id, client_secret=ccxcon.oauth_client_secret ) # get the entire list of instructors course_instructors = CourseInstructorRole(course.id).users_with_role() # get anonymous ids for each of them course_instructors_ids = [anonymous_id_for_user(user, course_key) for user in course_instructors] # extract the course details course_details = CourseDetails.fetch(course_key) payload = { 'course_id': unicode(course_key), 'title': course.display_name, 'author_name': None, 'overview': course_details.overview, 'description': course_details.short_description, 'image_url': course_details.course_image_asset_path, 'instructors': course_instructors_ids } headers = {'content-type': 'application/json'} # make the POST request add_course_url = urlparse.urljoin(course.ccx_connector, CCXCON_COURSEXS_URL) resp = oauth_ccxcon.post( url=add_course_url, json=payload, headers=headers, timeout=CCXCON_REQUEST_TIMEOUT ) if resp.status_code >= 500: raise CCXConnServerError('Server returned error Status: %s, Content: %s', resp.status_code, resp.content) if resp.status_code >= 400: log.error("Error creating course on ccxcon. Status: %s, Content: %s", resp.status_code, resp.content) # this API performs a POST request both for POST and PATCH, but the POST returns 201 and the PATCH returns 200 elif resp.status_code != HTTP_200_OK and resp.status_code != HTTP_201_CREATED: log.error('Server returned unexpected status code %s', resp.status_code) else: log.debug('Request successful. Status: %s, Content: %s', resp.status_code, resp.content)
agpl-3.0
mattvick/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/layout_tests/views/metered_stream_unittest.py
124
6044
# Copyright (C) 2010, 2012 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import logging import re import StringIO import unittest2 as unittest from webkitpy.layout_tests.views.metered_stream import MeteredStream class RegularTest(unittest.TestCase): verbose = False isatty = False def setUp(self): self.stream = StringIO.StringIO() self.buflist = self.stream.buflist self.stream.isatty = lambda: self.isatty # configure a logger to test that log calls do normally get included. self.logger = logging.getLogger(__name__) self.logger.setLevel(logging.DEBUG) self.logger.propagate = False # add a dummy time counter for a default behavior. self.times = range(10) self.meter = MeteredStream(self.stream, self.verbose, self.logger, self.time_fn, 8675) def tearDown(self): if self.meter: self.meter.cleanup() self.meter = None def time_fn(self): return self.times.pop(0) def test_logging_not_included(self): # This tests that if we don't hand a logger to the MeteredStream, # nothing is logged. logging_stream = StringIO.StringIO() handler = logging.StreamHandler(logging_stream) root_logger = logging.getLogger() orig_level = root_logger.level root_logger.addHandler(handler) root_logger.setLevel(logging.DEBUG) try: self.meter = MeteredStream(self.stream, self.verbose, None, self.time_fn, 8675) self.meter.write_throttled_update('foo') self.meter.write_update('bar') self.meter.write('baz') self.assertEqual(logging_stream.buflist, []) finally: root_logger.removeHandler(handler) root_logger.setLevel(orig_level) def _basic(self, times): self.times = times self.meter.write_update('foo') self.meter.write_update('bar') self.meter.write_throttled_update('baz') self.meter.write_throttled_update('baz 2') self.meter.writeln('done') self.assertEqual(self.times, []) return self.buflist def test_basic(self): buflist = self._basic([0, 1, 2, 13, 14]) self.assertEqual(buflist, ['foo\n', 'bar\n', 'baz 2\n', 'done\n']) def _log_after_update(self): self.meter.write_update('foo') self.logger.info('bar') return self.buflist def test_log_after_update(self): buflist = self._log_after_update() self.assertEqual(buflist, ['foo\n', 'bar\n']) def test_log_args(self): self.logger.info('foo %s %d', 'bar', 2) self.assertEqual(self.buflist, ['foo bar 2\n']) class TtyTest(RegularTest): verbose = False isatty = True def test_basic(self): buflist = self._basic([0, 1, 1.05, 1.1, 2]) self.assertEqual(buflist, ['foo', MeteredStream._erasure('foo'), 'bar', MeteredStream._erasure('bar'), 'baz 2', MeteredStream._erasure('baz 2'), 'done\n']) def test_log_after_update(self): buflist = self._log_after_update() self.assertEqual(buflist, ['foo', MeteredStream._erasure('foo'), 'bar\n']) class VerboseTest(RegularTest): isatty = False verbose = True def test_basic(self): buflist = self._basic([0, 1, 2.1, 13, 14.1234]) # We don't bother to match the hours and minutes of the timestamp since # the local timezone can vary and we can't set that portably and easily. self.assertTrue(re.match('\d\d:\d\d:00.000 8675 foo\n', buflist[0])) self.assertTrue(re.match('\d\d:\d\d:01.000 8675 bar\n', buflist[1])) self.assertTrue(re.match('\d\d:\d\d:13.000 8675 baz 2\n', buflist[2])) self.assertTrue(re.match('\d\d:\d\d:14.123 8675 done\n', buflist[3])) self.assertEqual(len(buflist), 4) def test_log_after_update(self): buflist = self._log_after_update() self.assertTrue(re.match('\d\d:\d\d:00.000 8675 foo\n', buflist[0])) # The second argument should have a real timestamp and pid, so we just check the format. self.assertTrue(re.match('\d\d:\d\d:\d\d.\d\d\d \d+ bar\n', buflist[1])) self.assertEqual(len(buflist), 2) def test_log_args(self): self.logger.info('foo %s %d', 'bar', 2) self.assertEqual(len(self.buflist), 1) self.assertTrue(self.buflist[0].endswith('foo bar 2\n'))
bsd-3-clause
stevenmizuno/QGIS
python/plugins/processing/algs/gdal/hillshade.py
6
7991
# -*- coding: utf-8 -*- """ *************************************************************************** hillshade.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Alexander Bruy' __date__ = 'October 2013' __copyright__ = '(C) 2013, Alexander Bruy' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os from qgis.core import (QgsRasterFileWriter, QgsProcessingParameterDefinition, QgsProcessingParameterRasterLayer, QgsProcessingParameterBand, QgsProcessingParameterBoolean, QgsProcessingParameterNumber, QgsProcessingParameterString, QgsProcessingParameterRasterDestination) from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm from processing.algs.gdal.GdalUtils import GdalUtils pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0] class hillshade(GdalAlgorithm): INPUT = 'INPUT' BAND = 'BAND' COMPUTE_EDGES = 'COMPUTE_EDGES' ZEVENBERGEN = 'ZEVENBERGEN' Z_FACTOR = 'Z_FACTOR' SCALE = 'SCALE' AZIMUTH = 'AZIMUTH' ALTITUDE = 'ALTITUDE' COMBINED = 'COMBINED' MULTIDIRECTIONAL = 'MULTIDIRECTIONAL' OPTIONS = 'OPTIONS' OUTPUT = 'OUTPUT' def __init__(self): super().__init__() def initAlgorithm(self, config=None): self.addParameter(QgsProcessingParameterRasterLayer(self.INPUT, self.tr('Input layer'))) self.addParameter(QgsProcessingParameterBand(self.BAND, self.tr('Band number'), parentLayerParameterName=self.INPUT)) self.addParameter(QgsProcessingParameterNumber(self.Z_FACTOR, self.tr('Z factor (vertical exaggeration)'), type=QgsProcessingParameterNumber.Double, minValue=0.0, defaultValue=1.0)) self.addParameter(QgsProcessingParameterNumber(self.SCALE, self.tr('Scale (ratio of vertical units to horizontal)'), type=QgsProcessingParameterNumber.Double, minValue=0.0, defaultValue=1.0)) self.addParameter(QgsProcessingParameterNumber(self.AZIMUTH, self.tr('Azimuth of the light'), type=QgsProcessingParameterNumber.Double, minValue=0.0, maxValue=360, defaultValue=315.0)) self.addParameter(QgsProcessingParameterNumber(self.ALTITUDE, self.tr('Altitude of the light'), type=QgsProcessingParameterNumber.Double, minValue=0.0, defaultValue=45.0)) self.addParameter(QgsProcessingParameterBoolean(self.COMPUTE_EDGES, self.tr('Compute edges'), defaultValue=False)) self.addParameter(QgsProcessingParameterBoolean(self.ZEVENBERGEN, self.tr("Use Zevenbergen&Thorne formula instead of the Horn's one"), defaultValue=False)) self.addParameter(QgsProcessingParameterBoolean(self.COMBINED, self.tr("Combined shading"), defaultValue=False)) self.addParameter(QgsProcessingParameterBoolean(self.MULTIDIRECTIONAL, self.tr("Multidirectional shading"), defaultValue=False)) options_param = QgsProcessingParameterString(self.OPTIONS, self.tr('Additional creation parameters'), defaultValue='', optional=True) options_param.setFlags(options_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) options_param.setMetadata({ 'widget_wrapper': { 'class': 'processing.algs.gdal.ui.RasterOptionsWidget.RasterOptionsWidgetWrapper'}}) self.addParameter(options_param) self.addParameter(QgsProcessingParameterRasterDestination(self.OUTPUT, self.tr('Hillshade'))) def name(self): return 'hillshade' def displayName(self): return self.tr('Hillshade') def group(self): return self.tr('Raster analysis') def groupId(self): return 'rasteranalysis' def getConsoleCommands(self, parameters, context, feedback, executing=True): arguments = ['hillshade'] inLayer = self.parameterAsRasterLayer(parameters, self.INPUT, context) arguments.append(inLayer.source()) out = self.parameterAsOutputLayer(parameters, self.OUTPUT, context) arguments.append(out) arguments.append('-of') arguments.append(QgsRasterFileWriter.driverForExtension(os.path.splitext(out)[1])) arguments.append('-b') arguments.append(str(self.parameterAsInt(parameters, self.BAND, context))) arguments.append('-z') arguments.append(str(self.parameterAsDouble(parameters, self.Z_FACTOR, context))) arguments.append('-s') arguments.append(str(self.parameterAsDouble(parameters, self.SCALE, context))) arguments.append('-az') arguments.append(str(self.parameterAsDouble(parameters, self.AZIMUTH, context))) arguments.append('-alt') arguments.append(str(self.parameterAsDouble(parameters, self.ALTITUDE, context))) if self.parameterAsBool(parameters, self.COMPUTE_EDGES, context): arguments.append('-compute_edges') if self.parameterAsBool(parameters, self.ZEVENBERGEN, context): arguments.append('-alg') arguments.append('ZevenbergenThorne') if self.parameterAsBool(parameters, self.COMBINED, context): arguments.append('-combined') if self.parameterAsBool(parameters, self.MULTIDIRECTIONAL, context): arguments.append('-multidirectional') options = self.parameterAsString(parameters, self.OPTIONS, context) if options: arguments.append('-co') arguments.append(options) return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
gpl-2.0
halberom/ansible
contrib/inventory/ec2.py
12
66590
#!/usr/bin/env python ''' EC2 external inventory script ================================= Generates inventory that Ansible can understand by making API request to AWS EC2 using the Boto library. NOTE: This script assumes Ansible is being executed where the environment variables needed for Boto have already been set: export AWS_ACCESS_KEY_ID='AK123' export AWS_SECRET_ACCESS_KEY='abc123' optional region environement variable if region is 'auto' This script also assumes there is an ec2.ini file alongside it. To specify a different path to ec2.ini, define the EC2_INI_PATH environment variable: export EC2_INI_PATH=/path/to/my_ec2.ini If you're using eucalyptus you need to set the above variables and you need to define: export EC2_URL=http://hostname_of_your_cc:port/services/Eucalyptus If you're using boto profiles (requires boto>=2.24.0) you can choose a profile using the --boto-profile command line argument (e.g. ec2.py --boto-profile prod) or using the AWS_PROFILE variable: AWS_PROFILE=prod ansible-playbook -i ec2.py myplaybook.yml For more details, see: http://docs.pythonboto.org/en/latest/boto_config_tut.html When run against a specific host, this script returns the following variables: - ec2_ami_launch_index - ec2_architecture - ec2_association - ec2_attachTime - ec2_attachment - ec2_attachmentId - ec2_block_devices - ec2_client_token - ec2_deleteOnTermination - ec2_description - ec2_deviceIndex - ec2_dns_name - ec2_eventsSet - ec2_group_name - ec2_hypervisor - ec2_id - ec2_image_id - ec2_instanceState - ec2_instance_type - ec2_ipOwnerId - ec2_ip_address - ec2_item - ec2_kernel - ec2_key_name - ec2_launch_time - ec2_monitored - ec2_monitoring - ec2_networkInterfaceId - ec2_ownerId - ec2_persistent - ec2_placement - ec2_platform - ec2_previous_state - ec2_private_dns_name - ec2_private_ip_address - ec2_publicIp - ec2_public_dns_name - ec2_ramdisk - ec2_reason - ec2_region - ec2_requester_id - ec2_root_device_name - ec2_root_device_type - ec2_security_group_ids - ec2_security_group_names - ec2_shutdown_state - ec2_sourceDestCheck - ec2_spot_instance_request_id - ec2_state - ec2_state_code - ec2_state_reason - ec2_status - ec2_subnet_id - ec2_tenancy - ec2_virtualization_type - ec2_vpc_id These variables are pulled out of a boto.ec2.instance object. There is a lack of consistency with variable spellings (camelCase and underscores) since this just loops through all variables the object exposes. It is preferred to use the ones with underscores when multiple exist. In addition, if an instance has AWS Tags associated with it, each tag is a new variable named: - ec2_tag_[Key] = [Value] Security groups are comma-separated in 'ec2_security_group_ids' and 'ec2_security_group_names'. ''' # (c) 2012, Peter Sankauskas # # This file is part of Ansible, # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ###################################################################### import sys import os import argparse import re from time import time import boto from boto import ec2 from boto import rds from boto import elasticache from boto import route53 import six from ansible.module_utils import ec2 as ec2_utils HAS_BOTO3 = False try: import boto3 HAS_BOTO3 = True except ImportError: pass from six.moves import configparser from collections import defaultdict try: import json except ImportError: import simplejson as json class Ec2Inventory(object): def _empty_inventory(self): return {"_meta" : {"hostvars" : {}}} def __init__(self): ''' Main execution path ''' # Inventory grouped by instance IDs, tags, security groups, regions, # and availability zones self.inventory = self._empty_inventory() self.aws_account_id = None # Index of hostname (address) to instance ID self.index = {} # Boto profile to use (if any) self.boto_profile = None # AWS credentials. self.credentials = {} # Read settings and parse CLI arguments self.parse_cli_args() self.read_settings() # Make sure that profile_name is not passed at all if not set # as pre 2.24 boto will fall over otherwise if self.boto_profile: if not hasattr(boto.ec2.EC2Connection, 'profile_name'): self.fail_with_error("boto version must be >= 2.24 to use profile") # Cache if self.args.refresh_cache: self.do_api_calls_update_cache() elif not self.is_cache_valid(): self.do_api_calls_update_cache() # Data to print if self.args.host: data_to_print = self.get_host_info() elif self.args.list: # Display list of instances for inventory if self.inventory == self._empty_inventory(): data_to_print = self.get_inventory_from_cache() else: data_to_print = self.json_format_dict(self.inventory, True) print(data_to_print) def is_cache_valid(self): ''' Determines if the cache files have expired, or if it is still valid ''' if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if (mod_time + self.cache_max_age) > current_time: if os.path.isfile(self.cache_path_index): return True return False def read_settings(self): ''' Reads the settings from the ec2.ini file ''' scriptbasename = __file__ scriptbasename = os.path.basename(scriptbasename) scriptbasename = scriptbasename.replace('.py', '') defaults = {'ec2': { 'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename) } } if six.PY3: config = configparser.ConfigParser() else: config = configparser.SafeConfigParser() ec2_ini_path = os.environ.get('EC2_INI_PATH', defaults['ec2']['ini_path']) ec2_ini_path = os.path.expanduser(os.path.expandvars(ec2_ini_path)) config.read(ec2_ini_path) # is eucalyptus? self.eucalyptus_host = None self.eucalyptus = False if config.has_option('ec2', 'eucalyptus'): self.eucalyptus = config.getboolean('ec2', 'eucalyptus') if self.eucalyptus and config.has_option('ec2', 'eucalyptus_host'): self.eucalyptus_host = config.get('ec2', 'eucalyptus_host') # Regions self.regions = [] configRegions = config.get('ec2', 'regions') configRegions_exclude = config.get('ec2', 'regions_exclude') if (configRegions == 'all'): if self.eucalyptus_host: self.regions.append(boto.connect_euca(host=self.eucalyptus_host).region.name, **self.credentials) else: for regionInfo in ec2.regions(): if regionInfo.name not in configRegions_exclude: self.regions.append(regionInfo.name) else: self.regions = configRegions.split(",") if 'auto' in self.regions: env_region = os.environ.get('AWS_REGION') if env_region is None: env_region = os.environ.get('AWS_DEFAULT_REGION') self.regions = [ env_region ] # Destination addresses self.destination_variable = config.get('ec2', 'destination_variable') self.vpc_destination_variable = config.get('ec2', 'vpc_destination_variable') if config.has_option('ec2', 'hostname_variable'): self.hostname_variable = config.get('ec2', 'hostname_variable') else: self.hostname_variable = None if config.has_option('ec2', 'destination_format') and \ config.has_option('ec2', 'destination_format_tags'): self.destination_format = config.get('ec2', 'destination_format') self.destination_format_tags = config.get('ec2', 'destination_format_tags').split(',') else: self.destination_format = None self.destination_format_tags = None # Route53 self.route53_enabled = config.getboolean('ec2', 'route53') if config.has_option('ec2', 'route53_hostnames'): self.route53_hostnames = config.get('ec2', 'route53_hostnames') else: self.route53_hostnames = None self.route53_excluded_zones = [] if config.has_option('ec2', 'route53_excluded_zones'): self.route53_excluded_zones.extend( config.get('ec2', 'route53_excluded_zones', '').split(',')) # Include RDS instances? self.rds_enabled = True if config.has_option('ec2', 'rds'): self.rds_enabled = config.getboolean('ec2', 'rds') # Include RDS cluster instances? if config.has_option('ec2', 'include_rds_clusters'): self.include_rds_clusters = config.getboolean('ec2', 'include_rds_clusters') else: self.include_rds_clusters = False # Include ElastiCache instances? self.elasticache_enabled = True if config.has_option('ec2', 'elasticache'): self.elasticache_enabled = config.getboolean('ec2', 'elasticache') # Return all EC2 instances? if config.has_option('ec2', 'all_instances'): self.all_instances = config.getboolean('ec2', 'all_instances') else: self.all_instances = False # Instance states to be gathered in inventory. Default is 'running'. # Setting 'all_instances' to 'yes' overrides this option. ec2_valid_instance_states = [ 'pending', 'running', 'shutting-down', 'terminated', 'stopping', 'stopped' ] self.ec2_instance_states = [] if self.all_instances: self.ec2_instance_states = ec2_valid_instance_states elif config.has_option('ec2', 'instance_states'): for instance_state in config.get('ec2', 'instance_states').split(','): instance_state = instance_state.strip() if instance_state not in ec2_valid_instance_states: continue self.ec2_instance_states.append(instance_state) else: self.ec2_instance_states = ['running'] # Return all RDS instances? (if RDS is enabled) if config.has_option('ec2', 'all_rds_instances') and self.rds_enabled: self.all_rds_instances = config.getboolean('ec2', 'all_rds_instances') else: self.all_rds_instances = False # Return all ElastiCache replication groups? (if ElastiCache is enabled) if config.has_option('ec2', 'all_elasticache_replication_groups') and self.elasticache_enabled: self.all_elasticache_replication_groups = config.getboolean('ec2', 'all_elasticache_replication_groups') else: self.all_elasticache_replication_groups = False # Return all ElastiCache clusters? (if ElastiCache is enabled) if config.has_option('ec2', 'all_elasticache_clusters') and self.elasticache_enabled: self.all_elasticache_clusters = config.getboolean('ec2', 'all_elasticache_clusters') else: self.all_elasticache_clusters = False # Return all ElastiCache nodes? (if ElastiCache is enabled) if config.has_option('ec2', 'all_elasticache_nodes') and self.elasticache_enabled: self.all_elasticache_nodes = config.getboolean('ec2', 'all_elasticache_nodes') else: self.all_elasticache_nodes = False # boto configuration profile (prefer CLI argument then environment variables then config file) self.boto_profile = self.args.boto_profile or os.environ.get('AWS_PROFILE') if config.has_option('ec2', 'boto_profile') and not self.boto_profile: self.boto_profile = config.get('ec2', 'boto_profile') # AWS credentials (prefer environment variables) if not (self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID') or os.environ.get('AWS_PROFILE')): if config.has_option('credentials', 'aws_access_key_id'): aws_access_key_id = config.get('credentials', 'aws_access_key_id') else: aws_access_key_id = None if config.has_option('credentials', 'aws_secret_access_key'): aws_secret_access_key = config.get('credentials', 'aws_secret_access_key') else: aws_secret_access_key = None if config.has_option('credentials', 'aws_security_token'): aws_security_token = config.get('credentials', 'aws_security_token') else: aws_security_token = None if aws_access_key_id: self.credentials = { 'aws_access_key_id': aws_access_key_id, 'aws_secret_access_key': aws_secret_access_key } if aws_security_token: self.credentials['security_token'] = aws_security_token # Cache related cache_dir = os.path.expanduser(config.get('ec2', 'cache_path')) if self.boto_profile: cache_dir = os.path.join(cache_dir, 'profile_' + self.boto_profile) if not os.path.exists(cache_dir): os.makedirs(cache_dir) cache_name = 'ansible-ec2' cache_id = self.boto_profile or os.environ.get('AWS_ACCESS_KEY_ID', self.credentials.get('aws_access_key_id')) if cache_id: cache_name = '%s-%s' % (cache_name, cache_id) self.cache_path_cache = os.path.join(cache_dir, "%s.cache" % cache_name) self.cache_path_index = os.path.join(cache_dir, "%s.index" % cache_name) self.cache_max_age = config.getint('ec2', 'cache_max_age') if config.has_option('ec2', 'expand_csv_tags'): self.expand_csv_tags = config.getboolean('ec2', 'expand_csv_tags') else: self.expand_csv_tags = False # Configure nested groups instead of flat namespace. if config.has_option('ec2', 'nested_groups'): self.nested_groups = config.getboolean('ec2', 'nested_groups') else: self.nested_groups = False # Replace dash or not in group names if config.has_option('ec2', 'replace_dash_in_groups'): self.replace_dash_in_groups = config.getboolean('ec2', 'replace_dash_in_groups') else: self.replace_dash_in_groups = True # Configure which groups should be created. group_by_options = [ 'group_by_instance_id', 'group_by_region', 'group_by_availability_zone', 'group_by_ami_id', 'group_by_instance_type', 'group_by_instance_state', 'group_by_key_pair', 'group_by_vpc_id', 'group_by_security_group', 'group_by_tag_keys', 'group_by_tag_none', 'group_by_route53_names', 'group_by_rds_engine', 'group_by_rds_parameter_group', 'group_by_elasticache_engine', 'group_by_elasticache_cluster', 'group_by_elasticache_parameter_group', 'group_by_elasticache_replication_group', 'group_by_aws_account', ] for option in group_by_options: if config.has_option('ec2', option): setattr(self, option, config.getboolean('ec2', option)) else: setattr(self, option, True) # Do we need to just include hosts that match a pattern? try: pattern_include = config.get('ec2', 'pattern_include') if pattern_include and len(pattern_include) > 0: self.pattern_include = re.compile(pattern_include) else: self.pattern_include = None except configparser.NoOptionError: self.pattern_include = None # Do we need to exclude hosts that match a pattern? try: pattern_exclude = config.get('ec2', 'pattern_exclude') if pattern_exclude and len(pattern_exclude) > 0: self.pattern_exclude = re.compile(pattern_exclude) else: self.pattern_exclude = None except configparser.NoOptionError: self.pattern_exclude = None # Do we want to stack multiple filters? if config.has_option('ec2', 'stack_filters'): self.stack_filters = config.getboolean('ec2', 'stack_filters') else: self.stack_filters = False # Instance filters (see boto and EC2 API docs). Ignore invalid filters. self.ec2_instance_filters = defaultdict(list) if config.has_option('ec2', 'instance_filters'): filters = [f for f in config.get('ec2', 'instance_filters').split(',') if f] for instance_filter in filters: instance_filter = instance_filter.strip() if not instance_filter or '=' not in instance_filter: continue filter_key, filter_value = [x.strip() for x in instance_filter.split('=', 1)] if not filter_key: continue self.ec2_instance_filters[filter_key].append(filter_value) def parse_cli_args(self): ''' Command line argument processing ''' parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on EC2') parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)') parser.add_argument('--host', action='store', help='Get all the variables about a specific instance') parser.add_argument('--refresh-cache', action='store_true', default=False, help='Force refresh of cache by making API requests to EC2 (default: False - use cache files)') parser.add_argument('--profile', '--boto-profile', action='store', dest='boto_profile', help='Use boto profile for connections to EC2') self.args = parser.parse_args() def do_api_calls_update_cache(self): ''' Do API calls to each region, and save data in cache files ''' if self.route53_enabled: self.get_route53_records() for region in self.regions: self.get_instances_by_region(region) if self.rds_enabled: self.get_rds_instances_by_region(region) if self.elasticache_enabled: self.get_elasticache_clusters_by_region(region) self.get_elasticache_replication_groups_by_region(region) if self.include_rds_clusters: self.include_rds_clusters_by_region(region) self.write_to_cache(self.inventory, self.cache_path_cache) self.write_to_cache(self.index, self.cache_path_index) def connect(self, region): ''' create connection to api server''' if self.eucalyptus: conn = boto.connect_euca(host=self.eucalyptus_host, **self.credentials) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) return conn def boto_fix_security_token_in_profile(self, connect_args): ''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + self.boto_profile if boto.config.has_option(profile, 'aws_security_token'): connect_args['security_token'] = boto.config.get(profile, 'aws_security_token') return connect_args def connect_to_aws(self, module, region): connect_args = self.credentials # only pass the profile name if it's set (as it is not supported by older boto versions) if self.boto_profile: connect_args['profile_name'] = self.boto_profile self.boto_fix_security_token_in_profile(connect_args) conn = module.connect_to_region(region, **connect_args) # connect_to_region will fail "silently" by returning None if the region name is wrong or not supported if conn is None: self.fail_with_error("region name: %s likely not supported, or AWS is down. connection to region failed." % region) return conn def get_instances_by_region(self, region): ''' Makes an AWS EC2 API call to the list of instances in a particular region ''' try: conn = self.connect(region) reservations = [] if self.ec2_instance_filters: if self.stack_filters: filters_dict = {} for filter_key, filter_values in self.ec2_instance_filters.items(): filters_dict[filter_key] = filter_values reservations.extend(conn.get_all_instances(filters = filters_dict)) else: for filter_key, filter_values in self.ec2_instance_filters.items(): reservations.extend(conn.get_all_instances(filters = { filter_key : filter_values })) else: reservations = conn.get_all_instances() # Pull the tags back in a second step # AWS are on record as saying that the tags fetched in the first `get_all_instances` request are not # reliable and may be missing, and the only way to guarantee they are there is by calling `get_all_tags` instance_ids = [] for reservation in reservations: instance_ids.extend([instance.id for instance in reservation.instances]) max_filter_value = 199 tags = [] for i in range(0, len(instance_ids), max_filter_value): tags.extend(conn.get_all_tags(filters={'resource-type': 'instance', 'resource-id': instance_ids[i:i+max_filter_value]})) tags_by_instance_id = defaultdict(dict) for tag in tags: tags_by_instance_id[tag.res_id][tag.name] = tag.value if (not self.aws_account_id) and reservations: self.aws_account_id = reservations[0].owner_id for reservation in reservations: for instance in reservation.instances: instance.tags = tags_by_instance_id[instance.id] self.add_instance(instance, region) except boto.exception.BotoServerError as e: if e.error_code == 'AuthFailure': error = self.get_auth_error_message() else: backend = 'Eucalyptus' if self.eucalyptus else 'AWS' error = "Error connecting to %s backend.\n%s" % (backend, e.message) self.fail_with_error(error, 'getting EC2 instances') def get_rds_instances_by_region(self, region): ''' Makes an AWS API call to the list of RDS instances in a particular region ''' try: conn = self.connect_to_aws(rds, region) if conn: marker = None while True: instances = conn.get_all_dbinstances(marker=marker) marker = instances.marker for instance in instances: self.add_rds_instance(instance, region) if not marker: break except boto.exception.BotoServerError as e: error = e.reason if e.error_code == 'AuthFailure': error = self.get_auth_error_message() if not e.reason == "Forbidden": error = "Looks like AWS RDS is down:\n%s" % e.message self.fail_with_error(error, 'getting RDS instances') def include_rds_clusters_by_region(self, region): if not HAS_BOTO3: self.fail_with_error("Working with RDS clusters requires boto3 - please install boto3 and try again", "getting RDS clusters") client = ec2_utils.boto3_inventory_conn('client', 'rds', region, **self.credentials) marker, clusters = '', [] while marker is not None: resp = client.describe_db_clusters(Marker=marker) clusters.extend(resp["DBClusters"]) marker = resp.get('Marker', None) account_id = boto.connect_iam().get_user().arn.split(':')[4] c_dict = {} for c in clusters: # remove these datetime objects as there is no serialisation to json # currently in place and we don't need the data yet if 'EarliestRestorableTime' in c: del c['EarliestRestorableTime'] if 'LatestRestorableTime' in c: del c['LatestRestorableTime'] if self.ec2_instance_filters == {}: matches_filter = True else: matches_filter = False try: # arn:aws:rds:<region>:<account number>:<resourcetype>:<name> tags = client.list_tags_for_resource( ResourceName='arn:aws:rds:' + region + ':' + account_id + ':cluster:' + c['DBClusterIdentifier']) c['Tags'] = tags['TagList'] if self.ec2_instance_filters: for filter_key, filter_values in self.ec2_instance_filters.items(): # get AWS tag key e.g. tag:env will be 'env' tag_name = filter_key.split(":", 1)[1] # Filter values is a list (if you put multiple values for the same tag name) matches_filter = any(d['Key'] == tag_name and d['Value'] in filter_values for d in c['Tags']) if matches_filter: # it matches a filter, so stop looking for further matches break except Exception as e: if e.message.find('DBInstanceNotFound') >= 0: # AWS RDS bug (2016-01-06) means deletion does not fully complete and leave an 'empty' cluster. # Ignore errors when trying to find tags for these pass # ignore empty clusters caused by AWS bug if len(c['DBClusterMembers']) == 0: continue elif matches_filter: c_dict[c['DBClusterIdentifier']] = c self.inventory['db_clusters'] = c_dict def get_elasticache_clusters_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache clusters (with nodes' info) in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would be called by # the shorthand method anyway...) try: conn = self.connect_to_aws(elasticache, region) if conn: # show_cache_node_info = True # because we also want nodes' information response = conn.describe_cache_clusters(None, None, None, True) except boto.exception.BotoServerError as e: error = e.reason if e.error_code == 'AuthFailure': error = self.get_auth_error_message() if not e.reason == "Forbidden": error = "Looks like AWS ElastiCache is down:\n%s" % e.message self.fail_with_error(error, 'getting ElastiCache clusters') try: # Boto also doesn't provide wrapper classes to CacheClusters or # CacheNodes. Because of that we can't make use of the get_list # method in the AWSQueryConnection. Let's do the work manually clusters = response['DescribeCacheClustersResponse']['DescribeCacheClustersResult']['CacheClusters'] except KeyError as e: error = "ElastiCache query to AWS failed (unexpected format)." self.fail_with_error(error, 'getting ElastiCache clusters') for cluster in clusters: self.add_elasticache_cluster(cluster, region) def get_elasticache_replication_groups_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache replication groups in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would be called by # the shorthand method anyway...) try: conn = self.connect_to_aws(elasticache, region) if conn: response = conn.describe_replication_groups() except boto.exception.BotoServerError as e: error = e.reason if e.error_code == 'AuthFailure': error = self.get_auth_error_message() if not e.reason == "Forbidden": error = "Looks like AWS ElastiCache [Replication Groups] is down:\n%s" % e.message self.fail_with_error(error, 'getting ElastiCache clusters') try: # Boto also doesn't provide wrapper classes to ReplicationGroups # Because of that we can't make use of the get_list method in the # AWSQueryConnection. Let's do the work manually replication_groups = response['DescribeReplicationGroupsResponse']['DescribeReplicationGroupsResult']['ReplicationGroups'] except KeyError as e: error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)." self.fail_with_error(error, 'getting ElastiCache clusters') for replication_group in replication_groups: self.add_elasticache_replication_group(replication_group, region) def get_auth_error_message(self): ''' create an informative error message if there is an issue authenticating''' errors = ["Authentication error retrieving ec2 inventory."] if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]: errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACCESS_KEY environment vars found') else: errors.append(' - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment vars found but may not be correct') boto_paths = ['/etc/boto.cfg', '~/.boto', '~/.aws/credentials'] boto_config_found = list(p for p in boto_paths if os.path.isfile(os.path.expanduser(p))) if len(boto_config_found) > 0: errors.append(" - Boto configs found at '%s', but the credentials contained may not be correct" % ', '.join(boto_config_found)) else: errors.append(" - No Boto config found at any expected location '%s'" % ', '.join(boto_paths)) return '\n'.join(errors) def fail_with_error(self, err_msg, err_operation=None): '''log an error to std err for ansible-playbook to consume and exit''' if err_operation: err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format( err_msg=err_msg, err_operation=err_operation) sys.stderr.write(err_msg) sys.exit(1) def get_instance(self, region, instance_id): conn = self.connect(region) reservations = conn.get_all_instances([instance_id]) for reservation in reservations: for instance in reservation.instances: return instance def add_instance(self, instance, region): ''' Adds an instance to the inventory and index, as long as it is addressable ''' # Only return instances with desired instance states if instance.state not in self.ec2_instance_states: return # Select the best destination address if self.destination_format and self.destination_format_tags: dest = self.destination_format.format(*[ getattr(instance, 'tags').get(tag, '') for tag in self.destination_format_tags ]) elif instance.subnet_id: dest = getattr(instance, self.vpc_destination_variable, None) if dest is None: dest = getattr(instance, 'tags').get(self.vpc_destination_variable, None) else: dest = getattr(instance, self.destination_variable, None) if dest is None: dest = getattr(instance, 'tags').get(self.destination_variable, None) if not dest: # Skip instances we cannot address (e.g. private VPC subnet) return # Set the inventory name hostname = None if self.hostname_variable: if self.hostname_variable.startswith('tag_'): hostname = instance.tags.get(self.hostname_variable[4:], None) else: hostname = getattr(instance, self.hostname_variable) # set the hostname from route53 if self.route53_enabled and self.route53_hostnames: route53_names = self.get_instance_route53_names(instance) for name in route53_names: if name.endswith(self.route53_hostnames): hostname = name # If we can't get a nice hostname, use the destination address if not hostname: hostname = dest # to_safe strips hostname characters like dots, so don't strip route53 hostnames elif self.route53_enabled and self.route53_hostnames and hostname.endswith(self.route53_hostnames): hostname = hostname.lower() else: hostname = self.to_safe(hostname).lower() # if we only want to include hosts that match a pattern, skip those that don't if self.pattern_include and not self.pattern_include.match(hostname): return # if we need to exclude hosts that match a pattern, skip those if self.pattern_exclude and self.pattern_exclude.match(hostname): return # Add to index self.index[hostname] = [region, instance.id] # Inventory: Group by instance ID (always a group of 1) if self.group_by_instance_id: self.inventory[instance.id] = [hostname] if self.nested_groups: self.push_group(self.inventory, 'instances', instance.id) # Inventory: Group by region if self.group_by_region: self.push(self.inventory, region, hostname) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone if self.group_by_availability_zone: self.push(self.inventory, instance.placement, hostname) if self.nested_groups: if self.group_by_region: self.push_group(self.inventory, region, instance.placement) self.push_group(self.inventory, 'zones', instance.placement) # Inventory: Group by Amazon Machine Image (AMI) ID if self.group_by_ami_id: ami_id = self.to_safe(instance.image_id) self.push(self.inventory, ami_id, hostname) if self.nested_groups: self.push_group(self.inventory, 'images', ami_id) # Inventory: Group by instance type if self.group_by_instance_type: type_name = self.to_safe('type_' + instance.instance_type) self.push(self.inventory, type_name, hostname) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by instance state if self.group_by_instance_state: state_name = self.to_safe('instance_state_' + instance.state) self.push(self.inventory, state_name, hostname) if self.nested_groups: self.push_group(self.inventory, 'instance_states', state_name) # Inventory: Group by key pair if self.group_by_key_pair and instance.key_name: key_name = self.to_safe('key_' + instance.key_name) self.push(self.inventory, key_name, hostname) if self.nested_groups: self.push_group(self.inventory, 'keys', key_name) # Inventory: Group by VPC if self.group_by_vpc_id and instance.vpc_id: vpc_id_name = self.to_safe('vpc_id_' + instance.vpc_id) self.push(self.inventory, vpc_id_name, hostname) if self.nested_groups: self.push_group(self.inventory, 'vpcs', vpc_id_name) # Inventory: Group by security group if self.group_by_security_group: try: for group in instance.groups: key = self.to_safe("security_group_" + group.name) self.push(self.inventory, key, hostname) if self.nested_groups: self.push_group(self.inventory, 'security_groups', key) except AttributeError: self.fail_with_error('\n'.join(['Package boto seems a bit older.', 'Please upgrade boto >= 2.3.0.'])) # Inventory: Group by AWS account ID if self.group_by_aws_account: self.push(self.inventory, self.aws_account_id, dest) if self.nested_groups: self.push_group(self.inventory, 'accounts', self.aws_account_id) # Inventory: Group by tag keys if self.group_by_tag_keys: for k, v in instance.tags.items(): if self.expand_csv_tags and v and ',' in v: values = map(lambda x: x.strip(), v.split(',')) else: values = [v] for v in values: if v: key = self.to_safe("tag_" + k + "=" + v) else: key = self.to_safe("tag_" + k) self.push(self.inventory, key, hostname) if self.nested_groups: self.push_group(self.inventory, 'tags', self.to_safe("tag_" + k)) if v: self.push_group(self.inventory, self.to_safe("tag_" + k), key) # Inventory: Group by Route53 domain names if enabled if self.route53_enabled and self.group_by_route53_names: route53_names = self.get_instance_route53_names(instance) for name in route53_names: self.push(self.inventory, name, hostname) if self.nested_groups: self.push_group(self.inventory, 'route53', name) # Global Tag: instances without tags if self.group_by_tag_none and len(instance.tags) == 0: self.push(self.inventory, 'tag_none', hostname) if self.nested_groups: self.push_group(self.inventory, 'tags', 'tag_none') # Global Tag: tag all EC2 instances self.push(self.inventory, 'ec2', hostname) self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance) self.inventory["_meta"]["hostvars"][hostname]['ansible_ssh_host'] = dest def add_rds_instance(self, instance, region): ''' Adds an RDS instance to the inventory and index, as long as it is addressable ''' # Only want available instances unless all_rds_instances is True if not self.all_rds_instances and instance.status != 'available': return # Select the best destination address dest = instance.endpoint[0] if not dest: # Skip instances we cannot address (e.g. private VPC subnet) return # Set the inventory name hostname = None if self.hostname_variable: if self.hostname_variable.startswith('tag_'): hostname = instance.tags.get(self.hostname_variable[4:], None) else: hostname = getattr(instance, self.hostname_variable) # If we can't get a nice hostname, use the destination address if not hostname: hostname = dest hostname = self.to_safe(hostname).lower() # Add to index self.index[hostname] = [region, instance.id] # Inventory: Group by instance ID (always a group of 1) if self.group_by_instance_id: self.inventory[instance.id] = [hostname] if self.nested_groups: self.push_group(self.inventory, 'instances', instance.id) # Inventory: Group by region if self.group_by_region: self.push(self.inventory, region, hostname) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone if self.group_by_availability_zone: self.push(self.inventory, instance.availability_zone, hostname) if self.nested_groups: if self.group_by_region: self.push_group(self.inventory, region, instance.availability_zone) self.push_group(self.inventory, 'zones', instance.availability_zone) # Inventory: Group by instance type if self.group_by_instance_type: type_name = self.to_safe('type_' + instance.instance_class) self.push(self.inventory, type_name, hostname) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by VPC if self.group_by_vpc_id and instance.subnet_group and instance.subnet_group.vpc_id: vpc_id_name = self.to_safe('vpc_id_' + instance.subnet_group.vpc_id) self.push(self.inventory, vpc_id_name, hostname) if self.nested_groups: self.push_group(self.inventory, 'vpcs', vpc_id_name) # Inventory: Group by security group if self.group_by_security_group: try: if instance.security_group: key = self.to_safe("security_group_" + instance.security_group.name) self.push(self.inventory, key, hostname) if self.nested_groups: self.push_group(self.inventory, 'security_groups', key) except AttributeError: self.fail_with_error('\n'.join(['Package boto seems a bit older.', 'Please upgrade boto >= 2.3.0.'])) # Inventory: Group by engine if self.group_by_rds_engine: self.push(self.inventory, self.to_safe("rds_" + instance.engine), hostname) if self.nested_groups: self.push_group(self.inventory, 'rds_engines', self.to_safe("rds_" + instance.engine)) # Inventory: Group by parameter group if self.group_by_rds_parameter_group: self.push(self.inventory, self.to_safe("rds_parameter_group_" + instance.parameter_group.name), hostname) if self.nested_groups: self.push_group(self.inventory, 'rds_parameter_groups', self.to_safe("rds_parameter_group_" + instance.parameter_group.name)) # Global Tag: all RDS instances self.push(self.inventory, 'rds', hostname) self.inventory["_meta"]["hostvars"][hostname] = self.get_host_info_dict_from_instance(instance) self.inventory["_meta"]["hostvars"][hostname]['ansible_ssh_host'] = dest def add_elasticache_cluster(self, cluster, region): ''' Adds an ElastiCache cluster to the inventory and index, as long as it's nodes are addressable ''' # Only want available clusters unless all_elasticache_clusters is True if not self.all_elasticache_clusters and cluster['CacheClusterStatus'] != 'available': return # Select the best destination address if 'ConfigurationEndpoint' in cluster and cluster['ConfigurationEndpoint']: # Memcached cluster dest = cluster['ConfigurationEndpoint']['Address'] is_redis = False else: # Redis sigle node cluster # Because all Redis clusters are single nodes, we'll merge the # info from the cluster with info about the node dest = cluster['CacheNodes'][0]['Endpoint']['Address'] is_redis = True if not dest: # Skip clusters we cannot address (e.g. private VPC subnet) return # Add to index self.index[dest] = [region, cluster['CacheClusterId']] # Inventory: Group by instance ID (always a group of 1) if self.group_by_instance_id: self.inventory[cluster['CacheClusterId']] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', cluster['CacheClusterId']) # Inventory: Group by region if self.group_by_region and not is_redis: self.push(self.inventory, region, dest) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone if self.group_by_availability_zone and not is_redis: self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest) if self.nested_groups: if self.group_by_region: self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone']) self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone']) # Inventory: Group by node type if self.group_by_instance_type and not is_redis: type_name = self.to_safe('type_' + cluster['CacheNodeType']) self.push(self.inventory, type_name, dest) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by VPC (information not available in the current # AWS API version for ElastiCache) # Inventory: Group by security group if self.group_by_security_group and not is_redis: # Check for the existence of the 'SecurityGroups' key and also if # this key has some value. When the cluster is not placed in a SG # the query can return None here and cause an error. if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None: for security_group in cluster['SecurityGroups']: key = self.to_safe("security_group_" + security_group['SecurityGroupId']) self.push(self.inventory, key, dest) if self.nested_groups: self.push_group(self.inventory, 'security_groups', key) # Inventory: Group by engine if self.group_by_elasticache_engine and not is_redis: self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest) if self.nested_groups: self.push_group(self.inventory, 'elasticache_engines', self.to_safe(cluster['Engine'])) # Inventory: Group by parameter group if self.group_by_elasticache_parameter_group: self.push(self.inventory, self.to_safe("elasticache_parameter_group_" + cluster['CacheParameterGroup']['CacheParameterGroupName']), dest) if self.nested_groups: self.push_group(self.inventory, 'elasticache_parameter_groups', self.to_safe(cluster['CacheParameterGroup']['CacheParameterGroupName'])) # Inventory: Group by replication group if self.group_by_elasticache_replication_group and 'ReplicationGroupId' in cluster and cluster['ReplicationGroupId']: self.push(self.inventory, self.to_safe("elasticache_replication_group_" + cluster['ReplicationGroupId']), dest) if self.nested_groups: self.push_group(self.inventory, 'elasticache_replication_groups', self.to_safe(cluster['ReplicationGroupId'])) # Global Tag: all ElastiCache clusters self.push(self.inventory, 'elasticache_clusters', cluster['CacheClusterId']) host_info = self.get_host_info_dict_from_describe_dict(cluster) self.inventory["_meta"]["hostvars"][dest] = host_info # Add the nodes for node in cluster['CacheNodes']: self.add_elasticache_node(node, cluster, region) def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available': return # Select the best destination address dest = node['Endpoint']['Address'] if not dest: # Skip nodes we cannot address (e.g. private VPC subnet) return node_id = self.to_safe(cluster['CacheClusterId'] + '_' + node['CacheNodeId']) # Add to index self.index[dest] = [region, node_id] # Inventory: Group by node ID (always a group of 1) if self.group_by_instance_id: self.inventory[node_id] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', node_id) # Inventory: Group by region if self.group_by_region: self.push(self.inventory, region, dest) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone if self.group_by_availability_zone: self.push(self.inventory, cluster['PreferredAvailabilityZone'], dest) if self.nested_groups: if self.group_by_region: self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone']) self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone']) # Inventory: Group by node type if self.group_by_instance_type: type_name = self.to_safe('type_' + cluster['CacheNodeType']) self.push(self.inventory, type_name, dest) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by VPC (information not available in the current # AWS API version for ElastiCache) # Inventory: Group by security group if self.group_by_security_group: # Check for the existence of the 'SecurityGroups' key and also if # this key has some value. When the cluster is not placed in a SG # the query can return None here and cause an error. if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None: for security_group in cluster['SecurityGroups']: key = self.to_safe("security_group_" + security_group['SecurityGroupId']) self.push(self.inventory, key, dest) if self.nested_groups: self.push_group(self.inventory, 'security_groups', key) # Inventory: Group by engine if self.group_by_elasticache_engine: self.push(self.inventory, self.to_safe("elasticache_" + cluster['Engine']), dest) if self.nested_groups: self.push_group(self.inventory, 'elasticache_engines', self.to_safe("elasticache_" + cluster['Engine'])) # Inventory: Group by parameter group (done at cluster level) # Inventory: Group by replication group (done at cluster level) # Inventory: Group by ElastiCache Cluster if self.group_by_elasticache_cluster: self.push(self.inventory, self.to_safe("elasticache_cluster_" + cluster['CacheClusterId']), dest) # Global Tag: all ElastiCache nodes self.push(self.inventory, 'elasticache_nodes', dest) host_info = self.get_host_info_dict_from_describe_dict(node) if dest in self.inventory["_meta"]["hostvars"]: self.inventory["_meta"]["hostvars"][dest].update(host_info) else: self.inventory["_meta"]["hostvars"][dest] = host_info def add_elasticache_replication_group(self, replication_group, region): ''' Adds an ElastiCache replication group to the inventory and index ''' # Only want available clusters unless all_elasticache_replication_groups is True if not self.all_elasticache_replication_groups and replication_group['Status'] != 'available': return # Select the best destination address (PrimaryEndpoint) dest = replication_group['NodeGroups'][0]['PrimaryEndpoint']['Address'] if not dest: # Skip clusters we cannot address (e.g. private VPC subnet) return # Add to index self.index[dest] = [region, replication_group['ReplicationGroupId']] # Inventory: Group by ID (always a group of 1) if self.group_by_instance_id: self.inventory[replication_group['ReplicationGroupId']] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', replication_group['ReplicationGroupId']) # Inventory: Group by region if self.group_by_region: self.push(self.inventory, region, dest) if self.nested_groups: self.push_group(self.inventory, 'regions', region) # Inventory: Group by availability zone (doesn't apply to replication groups) # Inventory: Group by node type (doesn't apply to replication groups) # Inventory: Group by VPC (information not available in the current # AWS API version for replication groups # Inventory: Group by security group (doesn't apply to replication groups) # Check this value in cluster level # Inventory: Group by engine (replication groups are always Redis) if self.group_by_elasticache_engine: self.push(self.inventory, 'elasticache_redis', dest) if self.nested_groups: self.push_group(self.inventory, 'elasticache_engines', 'redis') # Global Tag: all ElastiCache clusters self.push(self.inventory, 'elasticache_replication_groups', replication_group['ReplicationGroupId']) host_info = self.get_host_info_dict_from_describe_dict(replication_group) self.inventory["_meta"]["hostvars"][dest] = host_info def get_route53_records(self): ''' Get and store the map of resource records to domain names that point to them. ''' if self.boto_profile: r53_conn = route53.Route53Connection(profile_name=self.boto_profile) else: r53_conn = route53.Route53Connection() all_zones = r53_conn.get_zones() route53_zones = [ zone for zone in all_zones if zone.name[:-1] not in self.route53_excluded_zones ] self.route53_records = {} for zone in route53_zones: rrsets = r53_conn.get_all_rrsets(zone.id) for record_set in rrsets: record_name = record_set.name if record_name.endswith('.'): record_name = record_name[:-1] for resource in record_set.resource_records: self.route53_records.setdefault(resource, set()) self.route53_records[resource].add(record_name) def get_instance_route53_names(self, instance): ''' Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list. ''' instance_attributes = [ 'public_dns_name', 'private_dns_name', 'ip_address', 'private_ip_address' ] name_list = set() for attrib in instance_attributes: try: value = getattr(instance, attrib) except AttributeError: continue if value in self.route53_records: name_list.update(self.route53_records[value]) return list(name_list) def get_host_info_dict_from_instance(self, instance): instance_vars = {} for key in vars(instance): value = getattr(instance, key) key = self.to_safe('ec2_' + key) # Handle complex types # state/previous_state changed to properties in boto in https://github.com/boto/boto/commit/a23c379837f698212252720d2af8dec0325c9518 if key == 'ec2__state': instance_vars['ec2_state'] = instance.state or '' instance_vars['ec2_state_code'] = instance.state_code elif key == 'ec2__previous_state': instance_vars['ec2_previous_state'] = instance.previous_state or '' instance_vars['ec2_previous_state_code'] = instance.previous_state_code elif type(value) in [int, bool]: instance_vars[key] = value elif isinstance(value, six.string_types): instance_vars[key] = value.strip() elif value is None: instance_vars[key] = '' elif key == 'ec2_region': instance_vars[key] = value.name elif key == 'ec2__placement': instance_vars['ec2_placement'] = value.zone elif key == 'ec2_tags': for k, v in value.items(): if self.expand_csv_tags and ',' in v: v = list(map(lambda x: x.strip(), v.split(','))) key = self.to_safe('ec2_tag_' + k) instance_vars[key] = v elif key == 'ec2_groups': group_ids = [] group_names = [] for group in value: group_ids.append(group.id) group_names.append(group.name) instance_vars["ec2_security_group_ids"] = ','.join([str(i) for i in group_ids]) instance_vars["ec2_security_group_names"] = ','.join([str(i) for i in group_names]) elif key == 'ec2_block_device_mapping': instance_vars["ec2_block_devices"] = {} for k, v in value.items(): instance_vars["ec2_block_devices"][ os.path.basename(k) ] = v.volume_id else: pass # TODO Product codes if someone finds them useful #print key #print type(value) #print value instance_vars[self.to_safe('ec2_account_id')] = self.aws_account_id return instance_vars def get_host_info_dict_from_describe_dict(self, describe_dict): ''' Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes. ''' # I really don't agree with prefixing everything with 'ec2' # because EC2, RDS and ElastiCache are different services. # I'm just following the pattern used until now to not break any # compatibility. host_info = {} for key in describe_dict: value = describe_dict[key] key = self.to_safe('ec2_' + self.uncammelize(key)) # Handle complex types # Target: Memcached Cache Clusters if key == 'ec2_configuration_endpoint' and value: host_info['ec2_configuration_endpoint_address'] = value['Address'] host_info['ec2_configuration_endpoint_port'] = value['Port'] # Target: Cache Nodes and Redis Cache Clusters (single node) if key == 'ec2_endpoint' and value: host_info['ec2_endpoint_address'] = value['Address'] host_info['ec2_endpoint_port'] = value['Port'] # Target: Redis Replication Groups if key == 'ec2_node_groups' and value: host_info['ec2_endpoint_address'] = value[0]['PrimaryEndpoint']['Address'] host_info['ec2_endpoint_port'] = value[0]['PrimaryEndpoint']['Port'] replica_count = 0 for node in value[0]['NodeGroupMembers']: if node['CurrentRole'] == 'primary': host_info['ec2_primary_cluster_address'] = node['ReadEndpoint']['Address'] host_info['ec2_primary_cluster_port'] = node['ReadEndpoint']['Port'] host_info['ec2_primary_cluster_id'] = node['CacheClusterId'] elif node['CurrentRole'] == 'replica': host_info['ec2_replica_cluster_address_'+ str(replica_count)] = node['ReadEndpoint']['Address'] host_info['ec2_replica_cluster_port_'+ str(replica_count)] = node['ReadEndpoint']['Port'] host_info['ec2_replica_cluster_id_'+ str(replica_count)] = node['CacheClusterId'] replica_count += 1 # Target: Redis Replication Groups if key == 'ec2_member_clusters' and value: host_info['ec2_member_clusters'] = ','.join([str(i) for i in value]) # Target: All Cache Clusters elif key == 'ec2_cache_parameter_group': host_info["ec2_cache_node_ids_to_reboot"] = ','.join([str(i) for i in value['CacheNodeIdsToReboot']]) host_info['ec2_cache_parameter_group_name'] = value['CacheParameterGroupName'] host_info['ec2_cache_parameter_apply_status'] = value['ParameterApplyStatus'] # Target: Almost everything elif key == 'ec2_security_groups': # Skip if SecurityGroups is None # (it is possible to have the key defined but no value in it). if value is not None: sg_ids = [] for sg in value: sg_ids.append(sg['SecurityGroupId']) host_info["ec2_security_group_ids"] = ','.join([str(i) for i in sg_ids]) # Target: Everything # Preserve booleans and integers elif type(value) in [int, bool]: host_info[key] = value # Target: Everything # Sanitize string values elif isinstance(value, six.string_types): host_info[key] = value.strip() # Target: Everything # Replace None by an empty string elif value is None: host_info[key] = '' else: # Remove non-processed complex types pass return host_info def get_host_info(self): ''' Get variables about a specific host ''' if len(self.index) == 0: # Need to load index from cache self.load_index_from_cache() if not self.args.host in self.index: # try updating the cache self.do_api_calls_update_cache() if not self.args.host in self.index: # host might not exist anymore return self.json_format_dict({}, True) (region, instance_id) = self.index[self.args.host] instance = self.get_instance(region, instance_id) return self.json_format_dict(self.get_host_info_dict_from_instance(instance), True) def push(self, my_dict, key, element): ''' Push an element onto an array that may not have been defined in the dict ''' group_info = my_dict.setdefault(key, []) if isinstance(group_info, dict): host_list = group_info.setdefault('hosts', []) host_list.append(element) else: group_info.append(element) def push_group(self, my_dict, key, element): ''' Push a group as a child of another group. ''' parent_group = my_dict.setdefault(key, {}) if not isinstance(parent_group, dict): parent_group = my_dict[key] = {'hosts': parent_group} child_groups = parent_group.setdefault('children', []) if element not in child_groups: child_groups.append(element) def get_inventory_from_cache(self): ''' Reads the inventory from the cache file and returns it as a JSON object ''' with open(self.cache_path_cache, 'r') as f: json_inventory = f.read() return json_inventory def load_index_from_cache(self): ''' Reads the index from the cache file sets self.index ''' with open(self.cache_path_index, 'rb') as f: self.index = json.load(f) def write_to_cache(self, data, filename): ''' Writes data in JSON format to a file ''' json_data = self.json_format_dict(data, True) with open(filename, 'w') as f: f.write(json_data) def uncammelize(self, key): temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', key) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', temp).lower() def to_safe(self, word): ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = "[^A-Za-z0-9\_" if not self.replace_dash_in_groups: regex += "\-" return re.sub(regex + "]", "_", word) def json_format_dict(self, data, pretty=False): ''' Converts a dict to a JSON object and dumps it as a formatted string ''' if pretty: return json.dumps(data, sort_keys=True, indent=2) else: return json.dumps(data) if __name__ == '__main__': # Run the script Ec2Inventory()
gpl-3.0
blighj/django
django/db/models/base.py
9
71133
import copy import inspect import warnings from itertools import chain from django.apps import apps from django.conf import settings from django.core import checks from django.core.exceptions import ( NON_FIELD_ERRORS, FieldDoesNotExist, FieldError, MultipleObjectsReturned, ObjectDoesNotExist, ValidationError, ) from django.db import ( DEFAULT_DB_ALIAS, DJANGO_VERSION_PICKLE_KEY, DatabaseError, connection, connections, router, transaction, ) from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import CASCADE, Collector from django.db.models.fields.related import ( ForeignObjectRel, OneToOneField, lazy_related_operation, resolve_relation, ) from django.db.models.manager import Manager from django.db.models.options import Options from django.db.models.query import Q from django.db.models.signals import ( class_prepared, post_init, post_save, pre_init, pre_save, ) from django.db.models.utils import make_model_tuple from django.utils.encoding import force_text from django.utils.functional import curry from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext_lazy as _ from django.utils.version import get_version class Deferred: def __repr__(self): return '<Deferred field>' def __str__(self): return '<Deferred field>' DEFERRED = Deferred() def subclass_exception(name, parents, module, attached_to=None): """ Create exception subclass. Used by ModelBase below. If 'attached_to' is supplied, the exception will be created in a way that allows it to be pickled, assuming the returned exception class will be added as an attribute to the 'attached_to' class. """ class_dict = {'__module__': module} if attached_to is not None: def __reduce__(self): # Exceptions are special - they've got state that isn't # in self.__dict__. We assume it is all in self.args. return (unpickle_inner_exception, (attached_to, name), self.args) def __setstate__(self, args): self.args = args class_dict['__reduce__'] = __reduce__ class_dict['__setstate__'] = __setstate__ return type(name, parents, class_dict) class ModelBase(type): """Metaclass for all models.""" def __new__(cls, name, bases, attrs): super_new = super().__new__ # Also ensure initialization is only performed for subclasses of Model # (excluding Model class itself). parents = [b for b in bases if isinstance(b, ModelBase)] if not parents: return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop('__module__') new_attrs = {'__module__': module} classcell = attrs.pop('__classcell__', None) if classcell is not None: new_attrs['__classcell__'] = classcell new_class = super_new(cls, name, bases, new_attrs) attr_meta = attrs.pop('Meta', None) abstract = getattr(attr_meta, 'abstract', False) if not attr_meta: meta = getattr(new_class, 'Meta', None) else: meta = attr_meta base_meta = getattr(new_class, '_meta', None) app_label = None # Look for an application configuration to attach the model to. app_config = apps.get_containing_app_config(module) if getattr(meta, 'app_label', None) is None: if app_config is None: if not abstract: raise RuntimeError( "Model class %s.%s doesn't declare an explicit " "app_label and isn't in an application in " "INSTALLED_APPS." % (module, name) ) else: app_label = app_config.label new_class.add_to_class('_meta', Options(meta, app_label)) if not abstract: new_class.add_to_class( 'DoesNotExist', subclass_exception( 'DoesNotExist', tuple( x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract ) or (ObjectDoesNotExist,), module, attached_to=new_class)) new_class.add_to_class( 'MultipleObjectsReturned', subclass_exception( 'MultipleObjectsReturned', tuple( x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract ) or (MultipleObjectsReturned,), module, attached_to=new_class)) if base_meta and not base_meta.abstract: # Non-abstract child classes inherit some attributes from their # non-abstract parent (unless an ABC comes before it in the # method resolution order). if not hasattr(meta, 'ordering'): new_class._meta.ordering = base_meta.ordering if not hasattr(meta, 'get_latest_by'): new_class._meta.get_latest_by = base_meta.get_latest_by is_proxy = new_class._meta.proxy # If the model is a proxy, ensure that the base class # hasn't been swapped out. if is_proxy and base_meta and base_meta.swapped: raise TypeError("%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped)) # Add all attributes to the class. for obj_name, obj in attrs.items(): new_class.add_to_class(obj_name, obj) # All the fields of any type declared on this model new_fields = chain( new_class._meta.local_fields, new_class._meta.local_many_to_many, new_class._meta.private_fields ) field_names = {f.name for f in new_fields} # Basic setup for proxy models. if is_proxy: base = None for parent in [kls for kls in parents if hasattr(kls, '_meta')]: if parent._meta.abstract: if parent._meta.fields: raise TypeError( "Abstract base class containing model fields not " "permitted for proxy model '%s'." % name ) else: continue if base is None: base = parent elif parent._meta.concrete_model is not base._meta.concrete_model: raise TypeError("Proxy model '%s' has more than one non-abstract model base class." % name) if base is None: raise TypeError("Proxy model '%s' has no non-abstract model base class." % name) new_class._meta.setup_proxy(base) new_class._meta.concrete_model = base._meta.concrete_model else: new_class._meta.concrete_model = new_class # Collect the parent links for multi-table inheritance. parent_links = {} for base in reversed([new_class] + parents): # Conceptually equivalent to `if base is Model`. if not hasattr(base, '_meta'): continue # Skip concrete parent classes. if base != new_class and not base._meta.abstract: continue # Locate OneToOneField instances. for field in base._meta.local_fields: if isinstance(field, OneToOneField): related = resolve_relation(new_class, field.remote_field.model) parent_links[make_model_tuple(related)] = field # Track fields inherited from base models. inherited_attributes = set() # Do the appropriate setup for any model parents. for base in new_class.mro(): if base not in parents or not hasattr(base, '_meta'): # Things without _meta aren't functional models, so they're # uninteresting parents. inherited_attributes |= set(base.__dict__.keys()) continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many if not base._meta.abstract: # Check for clashes between locally declared fields and those # on the base classes. for field in parent_fields: if field.name in field_names: raise FieldError( 'Local field %r in class %r clashes with field of ' 'the same name from base class %r.' % ( field.name, name, base.__name__, ) ) else: inherited_attributes.add(field.name) # Concrete classes... base = base._meta.concrete_model base_key = make_model_tuple(base) if base_key in parent_links: field = parent_links[base_key] elif not is_proxy: attr_name = '%s_ptr' % base._meta.model_name field = OneToOneField( base, on_delete=CASCADE, name=attr_name, auto_created=True, parent_link=True, ) if attr_name in field_names: raise FieldError( "Auto-generated field '%s' in class %r for " "parent_link to base class %r clashes with " "declared field of the same name." % ( attr_name, name, base.__name__, ) ) # Only add the ptr field if it's not already present; # e.g. migrations will already have it specified if not hasattr(new_class, attr_name): new_class.add_to_class(attr_name, field) else: field = None new_class._meta.parents[base] = field else: base_parents = base._meta.parents.copy() # Add fields from abstract base class if it wasn't overridden. for field in parent_fields: if (field.name not in field_names and field.name not in new_class.__dict__ and field.name not in inherited_attributes): new_field = copy.deepcopy(field) new_class.add_to_class(field.name, new_field) # Replace parent links defined on this base by the new # field. It will be appropriately resolved if required. if field.one_to_one: for parent, parent_link in base_parents.items(): if field == parent_link: base_parents[parent] = new_field # Pass any non-abstract parent classes onto child. new_class._meta.parents.update(base_parents) # Inherit private fields (like GenericForeignKey) from the parent # class for field in base._meta.private_fields: if field.name in field_names: if not base._meta.abstract: raise FieldError( 'Local field %r in class %r clashes with field of ' 'the same name from base class %r.' % ( field.name, name, base.__name__, ) ) else: new_class.add_to_class(field.name, copy.deepcopy(field)) if base_meta and base_meta.abstract and not abstract: new_class._meta.indexes = [copy.deepcopy(idx) for idx in new_class._meta.indexes] # Set the name of _meta.indexes. This can't be done in # Options.contribute_to_class() because fields haven't been added # to the model at that point. for index in new_class._meta.indexes: if not index.name: index.set_name_with_model(new_class) if abstract: # Abstract base models can't be instantiated and don't appear in # the list of models for an app. We do the final setup for them a # little differently from normal models. attr_meta.abstract = False new_class.Meta = attr_meta return new_class new_class._prepare() new_class._meta.apps.register_model(new_class._meta.app_label, new_class) return new_class def add_to_class(cls, name, value): # We should call the contribute_to_class method only if it's bound if not inspect.isclass(value) and hasattr(value, 'contribute_to_class'): value.contribute_to_class(cls, name) else: setattr(cls, name, value) def _prepare(cls): """Create some methods once self._meta has been populated.""" opts = cls._meta opts._prepare(cls) if opts.order_with_respect_to: cls.get_next_in_order = curry(cls._get_next_or_previous_in_order, is_next=True) cls.get_previous_in_order = curry(cls._get_next_or_previous_in_order, is_next=False) # Defer creating accessors on the foreign class until it has been # created and registered. If remote_field is None, we're ordering # with respect to a GenericForeignKey and don't know what the # foreign class is - we'll add those accessors later in # contribute_to_class(). if opts.order_with_respect_to.remote_field: wrt = opts.order_with_respect_to remote = wrt.remote_field.model lazy_related_operation(make_foreign_order_accessors, cls, remote) # Give the class a docstring -- its definition. if cls.__doc__ is None: cls.__doc__ = "%s(%s)" % (cls.__name__, ", ".join(f.name for f in opts.fields)) get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get(opts.label_lower) if get_absolute_url_override: setattr(cls, 'get_absolute_url', get_absolute_url_override) if not opts.managers: if any(f.name == 'objects' for f in opts.fields): raise ValueError( "Model %s must specify a custom Manager, because it has a " "field named 'objects'." % cls.__name__ ) manager = Manager() manager.auto_created = True cls.add_to_class('objects', manager) class_prepared.send(sender=cls) @property def _base_manager(cls): return cls._meta.base_manager @property def _default_manager(cls): return cls._meta.default_manager class ModelState: """Store model instance state.""" def __init__(self, db=None): self.db = db # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object. # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs. # This impacts validation only; it has no effect on the actual save. self.adding = True class Model(metaclass=ModelBase): def __init__(self, *args, **kwargs): # Alias some things as locals to avoid repeat global lookups cls = self.__class__ opts = self._meta _setattr = setattr _DEFERRED = DEFERRED pre_init.send(sender=cls, args=args, kwargs=kwargs) # Set up the storage for instance state self._state = ModelState() # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The reason for the kwargs check is that standard iterator passes in by # args, and instantiation for iteration is 33% faster. if len(args) > len(opts.concrete_fields): # Daft, but matches old exception sans the err msg. raise IndexError("Number of args exceeds number of fields") if not kwargs: fields_iter = iter(opts.concrete_fields) # The ordering of the zip calls matter - zip throws StopIteration # when an iter throws it. So if the first iter throws it, the second # is *not* consumed. We rely on this, so don't change the order # without changing the logic. for val, field in zip(args, fields_iter): if val is _DEFERRED: continue _setattr(self, field.attname, val) else: # Slower, kwargs-ready version. fields_iter = iter(opts.fields) for val, field in zip(args, fields_iter): if val is _DEFERRED: continue _setattr(self, field.attname, val) kwargs.pop(field.name, None) # Now we're left with the unprocessed fields that *must* come from # keywords, or default. for field in fields_iter: is_related_object = False # Virtual field if field.attname not in kwargs and field.column is None: continue if kwargs: if isinstance(field.remote_field, ForeignObjectRel): try: # Assume object instance was passed in. rel_obj = kwargs.pop(field.name) is_related_object = True except KeyError: try: # Object instance wasn't passed in -- must be an ID. val = kwargs.pop(field.attname) except KeyError: val = field.get_default() else: # Object instance was passed in. Special case: You can # pass in "None" for related objects if it's allowed. if rel_obj is None and field.null: val = None else: try: val = kwargs.pop(field.attname) except KeyError: # This is done with an exception rather than the # default argument on pop because we don't want # get_default() to be evaluated, and then not used. # Refs #12057. val = field.get_default() else: val = field.get_default() if is_related_object: # If we are passed a related instance, set it using the # field.name instead of field.attname (e.g. "user" instead of # "user_id") so that the object gets properly cached (and type # checked) by the RelatedObjectDescriptor. if rel_obj is not _DEFERRED: _setattr(self, field.name, rel_obj) else: if val is not _DEFERRED: _setattr(self, field.attname, val) if kwargs: property_names = opts._property_names for prop in tuple(kwargs): try: # Any remaining kwargs must correspond to properties or # virtual fields. if prop in property_names or opts.get_field(prop): if kwargs[prop] is not _DEFERRED: _setattr(self, prop, kwargs[prop]) del kwargs[prop] except (AttributeError, FieldDoesNotExist): pass if kwargs: raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) super().__init__() post_init.send(sender=cls, instance=self) @classmethod def from_db(cls, db, field_names, values): if len(values) != len(cls._meta.concrete_fields): values = list(values) values.reverse() values = [values.pop() if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields] new = cls(*values) new._state.adding = False new._state.db = db return new def __repr__(self): try: u = str(self) except (UnicodeEncodeError, UnicodeDecodeError): u = '[Bad Unicode data]' return '<%s: %s>' % (self.__class__.__name__, u) def __str__(self): return '%s object' % self.__class__.__name__ def __eq__(self, other): if not isinstance(other, Model): return False if self._meta.concrete_model != other._meta.concrete_model: return False my_pk = self._get_pk_val() if my_pk is None: return self is other return my_pk == other._get_pk_val() def __hash__(self): if self._get_pk_val() is None: raise TypeError("Model instances without primary key value are unhashable") return hash(self._get_pk_val()) def __reduce__(self): data = self.__dict__ data[DJANGO_VERSION_PICKLE_KEY] = get_version() class_id = self._meta.app_label, self._meta.object_name return model_unpickle, (class_id,), data def __setstate__(self, state): msg = None pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: current_version = get_version() if current_version != pickled_version: msg = ( "Pickled model instance's Django version %s does not match " "the current version %s." % (pickled_version, current_version) ) else: msg = "Pickled model instance's Django version is not specified." if msg: warnings.warn(msg, RuntimeWarning, stacklevel=2) self.__dict__.update(state) def _get_pk_val(self, meta=None): if not meta: meta = self._meta return getattr(self, meta.pk.attname) def _set_pk_val(self, value): return setattr(self, self._meta.pk.attname, value) pk = property(_get_pk_val, _set_pk_val) def get_deferred_fields(self): """ Return a set containing names of deferred fields for this instance. """ return { f.attname for f in self._meta.concrete_fields if f.attname not in self.__dict__ } def refresh_from_db(self, using=None, fields=None): """ Reload field values from the database. By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default. Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded. When accessing deferred fields of an instance, the deferred loading of the field will call this method. """ if fields is not None: if len(fields) == 0: return if any(LOOKUP_SEP in f for f in fields): raise ValueError( 'Found "%s" in fields argument. Relations and transforms ' 'are not allowed in fields.' % LOOKUP_SEP) db = using if using is not None else self._state.db db_instance_qs = self.__class__._default_manager.using(db).filter(pk=self.pk) # Use provided fields, if not set then reload all non-deferred fields. deferred_fields = self.get_deferred_fields() if fields is not None: fields = list(fields) db_instance_qs = db_instance_qs.only(*fields) elif deferred_fields: fields = [f.attname for f in self._meta.concrete_fields if f.attname not in deferred_fields] db_instance_qs = db_instance_qs.only(*fields) db_instance = db_instance_qs.get() non_loaded_fields = db_instance.get_deferred_fields() for field in self._meta.concrete_fields: if field.attname in non_loaded_fields: # This field wasn't refreshed - skip ahead. continue setattr(self, field.attname, getattr(db_instance, field.attname)) # Throw away stale foreign key references. if field.is_relation and field.get_cache_name() in self.__dict__: rel_instance = getattr(self, field.get_cache_name()) local_val = getattr(db_instance, field.attname) related_val = None if rel_instance is None else getattr(rel_instance, field.target_field.attname) if local_val != related_val or (local_val is None and related_val is None): del self.__dict__[field.get_cache_name()] self._state.db = db_instance._state.db def serializable_value(self, field_name): """ Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value. Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method. """ try: field = self._meta.get_field(field_name) except FieldDoesNotExist: return getattr(self, field_name) return getattr(self, field.attname) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): """ Save the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set. """ # Ensure that a model instance without a PK hasn't been assigned to # a ForeignKey or OneToOneField on this model. If the field is # nullable, allowing the save() would result in silent data loss. for field in self._meta.concrete_fields: if field.is_relation: # If the related field isn't cached, then an instance hasn't # been assigned and there's no need to worry about this check. try: getattr(self, field.get_cache_name()) except AttributeError: continue obj = getattr(self, field.name, None) # A pk may have been assigned manually to a model instance not # saved to the database (or auto-generated in a case like # UUIDField), but we allow the save to proceed and rely on the # database to raise an IntegrityError if applicable. If # constraints aren't supported by the database, there's the # unavoidable risk of data corruption. if obj and obj.pk is None: # Remove the object from a related instance cache. if not field.remote_field.multiple: delattr(obj, field.remote_field.get_cache_name()) raise ValueError( "save() prohibited to prevent data loss due to " "unsaved related object '%s'." % field.name ) using = using or router.db_for_write(self.__class__, instance=self) if force_insert and (force_update or update_fields): raise ValueError("Cannot force both insert and updating in model saving.") deferred_fields = self.get_deferred_fields() if update_fields is not None: # If update_fields is empty, skip the save. We do also check for # no-op saves later on for inheritance cases. This bailout is # still needed for skipping signal sending. if len(update_fields) == 0: return update_fields = frozenset(update_fields) field_names = set() for field in self._meta.fields: if not field.primary_key: field_names.add(field.name) if field.name != field.attname: field_names.add(field.attname) non_model_fields = update_fields.difference(field_names) if non_model_fields: raise ValueError("The following fields do not exist in this " "model or are m2m fields: %s" % ', '.join(non_model_fields)) # If saving to the same database, and this model is deferred, then # automatically do a "update_fields" save on the loaded fields. elif not force_insert and deferred_fields and using == self._state.db: field_names = set() for field in self._meta.concrete_fields: if not field.primary_key and not hasattr(field, 'through'): field_names.add(field.attname) loaded_fields = field_names.difference(deferred_fields) if loaded_fields: update_fields = frozenset(loaded_fields) self.save_base(using=using, force_insert=force_insert, force_update=force_update, update_fields=update_fields) save.alters_data = True def save_base(self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None): """ Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending. The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading. """ using = using or router.db_for_write(self.__class__, instance=self) assert not (force_insert and (force_update or update_fields)) assert update_fields is None or len(update_fields) > 0 cls = origin = self.__class__ # Skip proxies, but keep the origin as the proxy model. if cls._meta.proxy: cls = cls._meta.concrete_model meta = cls._meta if not meta.auto_created: pre_save.send( sender=origin, instance=self, raw=raw, using=using, update_fields=update_fields, ) with transaction.atomic(using=using, savepoint=False): if not raw: self._save_parents(cls, using, update_fields) updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) # Store the database on which the object was saved self._state.db = using # Once saved, this is no longer a to-be-added instance. self._state.adding = False # Signal that the save is complete if not meta.auto_created: post_save.send( sender=origin, instance=self, created=(not updated), update_fields=update_fields, raw=raw, using=using, ) save_base.alters_data = True def _save_parents(self, cls, using, update_fields): """Save all the parents of cls using values from self.""" meta = cls._meta for parent, field in meta.parents.items(): # Make sure the link fields are synced between parent and self. if (field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None): setattr(self, parent._meta.pk.attname, getattr(self, field.attname)) self._save_parents(cls=parent, using=using, update_fields=update_fields) self._save_table(cls=parent, using=using, update_fields=update_fields) # Set the parent's PK value to self. if field: setattr(self, field.attname, self._get_pk_val(parent._meta)) # Since we didn't have an instance of the parent handy set # attname directly, bypassing the descriptor. Invalidate # the related object cache, in case it's been accidentally # populated. A fresh instance will be re-built from the # database if necessary. cache_name = field.get_cache_name() if hasattr(self, cache_name): delattr(self, cache_name) def _save_table(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None): """ Do the heavy-lifting involved in saving. Update or insert the data for a single table. """ meta = cls._meta non_pks = [f for f in meta.local_concrete_fields if not f.primary_key] if update_fields: non_pks = [f for f in non_pks if f.name in update_fields or f.attname in update_fields] pk_val = self._get_pk_val(meta) if pk_val is None: pk_val = meta.pk.get_pk_value_on_save(self) setattr(self, meta.pk.attname, pk_val) pk_set = pk_val is not None if not pk_set and (force_update or update_fields): raise ValueError("Cannot force an update in save() with no primary key.") updated = False # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. if pk_set and not force_insert: base_qs = cls._base_manager.using(using) values = [(f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False))) for f in non_pks] forced_update = update_fields or force_update updated = self._do_update(base_qs, using, pk_val, values, update_fields, forced_update) if force_update and not updated: raise DatabaseError("Forced update did not affect any rows.") if update_fields and not updated: raise DatabaseError("Save with update_fields did not affect any rows.") if not updated: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the _order field field = meta.order_with_respect_to filter_args = field.get_filter_kwargs_for_object(self) order_value = cls._base_manager.using(using).filter(**filter_args).count() self._order = order_value fields = meta.local_concrete_fields if not pk_set: fields = [f for f in fields if f is not meta.auto_field] update_pk = meta.auto_field and not pk_set result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) if update_pk: setattr(self, meta.pk.attname, result) return updated def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update): """ Try to update the model. Return True if the model was updated (if an update query was done and a matching row was found in the DB). """ filtered = base_qs.filter(pk=pk_val) if not values: # We can end up here when saving a model in inheritance chain where # update_fields doesn't target any field in current model. In that # case we just say the update succeeded. Another case ending up here # is a model with just PK - in that case check that the PK still # exists. return update_fields is not None or filtered.exists() if self._meta.select_on_save and not forced_update: if filtered.exists(): # It may happen that the object is deleted from the DB right after # this check, causing the subsequent UPDATE to return zero matching # rows. The same result can occur in some rare cases when the # database returns zero despite the UPDATE being executed # successfully (a row is matched and updated). In order to # distinguish these two cases, the object's existence in the # database is again checked for if the UPDATE query returns 0. return filtered._update(values) > 0 or filtered.exists() else: return False return filtered._update(values) > 0 def _do_insert(self, manager, using, fields, update_pk, raw): """ Do an INSERT. If update_pk is defined then this method should return the new pk for the model. """ return manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw) def delete(self, using=None, keep_parents=False): using = using or router.db_for_write(self.__class__, instance=self) assert self._get_pk_val() is not None, ( "%s object can't be deleted because its %s attribute is set to None." % (self._meta.object_name, self._meta.pk.attname) ) collector = Collector(using=using) collector.collect([self], keep_parents=keep_parents) return collector.delete() delete.alters_data = True def _get_FIELD_display(self, field): value = getattr(self, field.attname) return force_text(dict(field.flatchoices).get(value, value), strings_only=True) def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): if not self.pk: raise ValueError("get_next/get_previous cannot be used on unsaved objects.") op = 'gt' if is_next else 'lt' order = '' if is_next else '-' param = getattr(self, field.attname) q = Q(**{'%s__%s' % (field.name, op): param}) q = q | Q(**{field.name: param, 'pk__%s' % op: self.pk}) qs = self.__class__._default_manager.using(self._state.db).filter(**kwargs).filter(q).order_by( '%s%s' % (order, field.name), '%spk' % order ) try: return qs[0] except IndexError: raise self.DoesNotExist("%s matching query does not exist." % self.__class__._meta.object_name) def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next if not hasattr(self, cachename): op = 'gt' if is_next else 'lt' order = '_order' if is_next else '-_order' order_field = self._meta.order_with_respect_to filter_args = order_field.get_filter_kwargs_for_object(self) obj = self.__class__._default_manager.filter(**filter_args).filter(**{ '_order__%s' % op: self.__class__._default_manager.values('_order').filter(**{ self._meta.pk.name: self.pk }) }).order_by(order)[:1].get() setattr(self, cachename, obj) return getattr(self, cachename) def prepare_database_save(self, field): if self.pk is None: raise ValueError("Unsaved model instance %r cannot be used in an ORM query." % self) return getattr(self, field.remote_field.get_related_field().attname) def clean(self): """ Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS. """ pass def validate_unique(self, exclude=None): """ Check unique constraints on the model and raise ValidationError if any failed. """ unique_checks, date_checks = self._get_unique_checks(exclude=exclude) errors = self._perform_unique_checks(unique_checks) date_errors = self._perform_date_checks(date_checks) for k, v in date_errors.items(): errors.setdefault(k, []).extend(v) if errors: raise ValidationError(errors) def _get_unique_checks(self, exclude=None): """ Return a list of checks to perform. Since validate_unique() could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that did not validate should also be excluded, but they need to be passed in via the exclude argument. """ if exclude is None: exclude = [] unique_checks = [] unique_togethers = [(self.__class__, self._meta.unique_together)] for parent_class in self._meta.get_parent_list(): if parent_class._meta.unique_together: unique_togethers.append((parent_class, parent_class._meta.unique_together)) for model_class, unique_together in unique_togethers: for check in unique_together: for name in check: # If this is an excluded field, don't add this check. if name in exclude: break else: unique_checks.append((model_class, tuple(check))) # These are checks for the unique_for_<date/year/month>. date_checks = [] # Gather a list of checks for fields declared as unique and add them to # the list of checks. fields_with_class = [(self.__class__, self._meta.local_fields)] for parent_class in self._meta.get_parent_list(): fields_with_class.append((parent_class, parent_class._meta.local_fields)) for model_class, fields in fields_with_class: for f in fields: name = f.name if name in exclude: continue if f.unique: unique_checks.append((model_class, (name,))) if f.unique_for_date and f.unique_for_date not in exclude: date_checks.append((model_class, 'date', name, f.unique_for_date)) if f.unique_for_year and f.unique_for_year not in exclude: date_checks.append((model_class, 'year', name, f.unique_for_year)) if f.unique_for_month and f.unique_for_month not in exclude: date_checks.append((model_class, 'month', name, f.unique_for_month)) return unique_checks, date_checks def _perform_unique_checks(self, unique_checks): errors = {} for model_class, unique_check in unique_checks: # Try to look up an existing object with the same values as this # object's values for all the unique field. lookup_kwargs = {} for field_name in unique_check: f = self._meta.get_field(field_name) lookup_value = getattr(self, f.attname) # TODO: Handle multiple backends with different feature flags. if (lookup_value is None or (lookup_value == '' and connection.features.interprets_empty_strings_as_nulls)): # no value, skip the lookup continue if f.primary_key and not self._state.adding: # no need to check for unique primary key when editing continue lookup_kwargs[str(field_name)] = lookup_value # some fields were skipped, no reason to do the check if len(unique_check) != len(lookup_kwargs): continue qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) # Note that we need to use the pk as defined by model_class, not # self.pk. These can be different fields because model inheritance # allows single model to have effectively multiple primary keys. # Refs #17615. model_class_pk = self._get_pk_val(model_class._meta) if not self._state.adding and model_class_pk is not None: qs = qs.exclude(pk=model_class_pk) if qs.exists(): if len(unique_check) == 1: key = unique_check[0] else: key = NON_FIELD_ERRORS errors.setdefault(key, []).append(self.unique_error_message(model_class, unique_check)) return errors def _perform_date_checks(self, date_checks): errors = {} for model_class, lookup_type, field, unique_for in date_checks: lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == 'date': lookup_kwargs['%s__day' % unique_for] = date.day lookup_kwargs['%s__month' % unique_for] = date.month lookup_kwargs['%s__year' % unique_for] = date.year else: lookup_kwargs['%s__%s' % (unique_for, lookup_type)] = getattr(date, lookup_type) lookup_kwargs[field] = getattr(self, field) qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) if not self._state.adding and self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): errors.setdefault(field, []).append( self.date_error_message(lookup_type, field, unique_for) ) return errors def date_error_message(self, lookup_type, field_name, unique_for): opts = self._meta field = opts.get_field(field_name) return ValidationError( message=field.error_messages['unique_for_date'], code='unique_for_date', params={ 'model': self, 'model_name': capfirst(opts.verbose_name), 'lookup_type': lookup_type, 'field': field_name, 'field_label': capfirst(field.verbose_name), 'date_field': unique_for, 'date_field_label': capfirst(opts.get_field(unique_for).verbose_name), } ) def unique_error_message(self, model_class, unique_check): opts = model_class._meta params = { 'model': self, 'model_class': model_class, 'model_name': capfirst(opts.verbose_name), 'unique_check': unique_check, } # A unique field if len(unique_check) == 1: field = opts.get_field(unique_check[0]) params['field_label'] = capfirst(field.verbose_name) return ValidationError( message=field.error_messages['unique'], code='unique', params=params, ) # unique_together else: field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check] params['field_labels'] = get_text_list(field_labels, _('and')) return ValidationError( message=_("%(model_name)s with this %(field_labels)s already exists."), code='unique_together', params=params, ) def full_clean(self, exclude=None, validate_unique=True): """ Call clean_fields(), clean(), and validate_unique() on the model. Raise a ValidationError for any errors that occur. """ errors = {} if exclude is None: exclude = [] else: exclude = list(exclude) try: self.clean_fields(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. if validate_unique: for name in errors.keys(): if name != NON_FIELD_ERRORS and name not in exclude: exclude.append(name) try: self.validate_unique(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors) def clean_fields(self, exclude=None): """ Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur. """ if exclude is None: exclude = [] errors = {} for f in self._meta.fields: if f.name in exclude: continue # Skip validation for empty fields with blank=True. The developer # is responsible for making sure they have a valid value. raw_value = getattr(self, f.attname) if f.blank and raw_value in f.empty_values: continue try: setattr(self, f.attname, f.clean(raw_value, self)) except ValidationError as e: errors[f.name] = e.error_list if errors: raise ValidationError(errors) @classmethod def check(cls, **kwargs): errors = [] errors.extend(cls._check_swappable()) errors.extend(cls._check_model()) errors.extend(cls._check_managers(**kwargs)) if not cls._meta.swapped: errors.extend(cls._check_fields(**kwargs)) errors.extend(cls._check_m2m_through_same_relationship()) errors.extend(cls._check_long_column_names()) clash_errors = ( cls._check_id_field() + cls._check_field_name_clashes() + cls._check_model_name_db_lookup_clashes() ) errors.extend(clash_errors) # If there are field name clashes, hide consequent column name # clashes. if not clash_errors: errors.extend(cls._check_column_name_clashes()) errors.extend(cls._check_index_together()) errors.extend(cls._check_unique_together()) errors.extend(cls._check_ordering()) return errors @classmethod def _check_swappable(cls): """Check if the swapped model exists.""" errors = [] if cls._meta.swapped: try: apps.get_model(cls._meta.swapped) except ValueError: errors.append( checks.Error( "'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable, id='models.E001', ) ) except LookupError: app_label, model_name = cls._meta.swapped.split('.') errors.append( checks.Error( "'%s' references '%s.%s', which has not been " "installed, or is abstract." % ( cls._meta.swappable, app_label, model_name ), id='models.E002', ) ) return errors @classmethod def _check_model(cls): errors = [] if cls._meta.proxy: if cls._meta.local_fields or cls._meta.local_many_to_many: errors.append( checks.Error( "Proxy model '%s' contains model fields." % cls.__name__, id='models.E017', ) ) return errors @classmethod def _check_managers(cls, **kwargs): """Perform all manager checks.""" errors = [] for manager in cls._meta.managers: errors.extend(manager.check(**kwargs)) return errors @classmethod def _check_fields(cls, **kwargs): """Perform all field checks.""" errors = [] for field in cls._meta.local_fields: errors.extend(field.check(**kwargs)) for field in cls._meta.local_many_to_many: errors.extend(field.check(from_model=cls, **kwargs)) return errors @classmethod def _check_m2m_through_same_relationship(cls): """ Check if no relationship model is used by more than one m2m field. """ errors = [] seen_intermediary_signatures = [] fields = cls._meta.local_many_to_many # Skip when the target model wasn't found. fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase)) # Skip when the relationship model wasn't found. fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase)) for f in fields: signature = (f.remote_field.model, cls, f.remote_field.through) if signature in seen_intermediary_signatures: errors.append( checks.Error( "The model has two many-to-many relations through " "the intermediate model '%s'." % f.remote_field.through._meta.label, obj=cls, id='models.E003', ) ) else: seen_intermediary_signatures.append(signature) return errors @classmethod def _check_id_field(cls): """Check if `id` field is a primary key.""" fields = list(f for f in cls._meta.local_fields if f.name == 'id' and f != cls._meta.pk) # fields is empty or consists of the invalid "id" field if fields and not fields[0].primary_key and cls._meta.pk.name == 'id': return [ checks.Error( "'id' can only be used as a field name if the field also " "sets 'primary_key=True'.", obj=cls, id='models.E004', ) ] else: return [] @classmethod def _check_field_name_clashes(cls): """Forbid field shadowing in multi-table inheritance.""" errors = [] used_fields = {} # name or attname -> field # Check that multi-inheritance doesn't cause field name shadowing. for parent in cls._meta.get_parent_list(): for f in parent._meta.local_fields: clash = used_fields.get(f.name) or used_fields.get(f.attname) or None if clash: errors.append( checks.Error( "The field '%s' from parent model " "'%s' clashes with the field '%s' " "from parent model '%s'." % ( clash.name, clash.model._meta, f.name, f.model._meta ), obj=cls, id='models.E005', ) ) used_fields[f.name] = f used_fields[f.attname] = f # Check that fields defined in the model don't clash with fields from # parents, including auto-generated fields like multi-table inheritance # child accessors. for parent in cls._meta.get_parent_list(): for f in parent._meta.get_fields(): if f not in used_fields: used_fields[f.name] = f for f in cls._meta.local_fields: clash = used_fields.get(f.name) or used_fields.get(f.attname) or None # Note that we may detect clash between user-defined non-unique # field "id" and automatically added unique field "id", both # defined at the same model. This special case is considered in # _check_id_field and here we ignore it. id_conflict = f.name == "id" and clash and clash.name == "id" and clash.model == cls if clash and not id_conflict: errors.append( checks.Error( "The field '%s' clashes with the field '%s' " "from model '%s'." % ( f.name, clash.name, clash.model._meta ), obj=f, id='models.E006', ) ) used_fields[f.name] = f used_fields[f.attname] = f return errors @classmethod def _check_column_name_clashes(cls): # Store a list of column names which have already been used by other fields. used_column_names = [] errors = [] for f in cls._meta.local_fields: _, column_name = f.get_attname_column() # Ensure the column name is not already in use. if column_name and column_name in used_column_names: errors.append( checks.Error( "Field '%s' has column name '%s' that is used by " "another field." % (f.name, column_name), hint="Specify a 'db_column' for the field.", obj=cls, id='models.E007' ) ) else: used_column_names.append(column_name) return errors @classmethod def _check_model_name_db_lookup_clashes(cls): errors = [] model_name = cls.__name__ if model_name.startswith('_') or model_name.endswith('_'): errors.append( checks.Error( "The model name '%s' cannot start or end with an underscore " "as it collides with the query lookup syntax." % model_name, obj=cls, id='models.E023' ) ) elif LOOKUP_SEP in model_name: errors.append( checks.Error( "The model name '%s' cannot contain double underscores as " "it collides with the query lookup syntax." % model_name, obj=cls, id='models.E024' ) ) return errors @classmethod def _check_index_together(cls): """Check the value of "index_together" option.""" if not isinstance(cls._meta.index_together, (tuple, list)): return [ checks.Error( "'index_together' must be a list or tuple.", obj=cls, id='models.E008', ) ] elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together): return [ checks.Error( "All 'index_together' elements must be lists or tuples.", obj=cls, id='models.E009', ) ] else: errors = [] for fields in cls._meta.index_together: errors.extend(cls._check_local_fields(fields, "index_together")) return errors @classmethod def _check_unique_together(cls): """Check the value of "unique_together" option.""" if not isinstance(cls._meta.unique_together, (tuple, list)): return [ checks.Error( "'unique_together' must be a list or tuple.", obj=cls, id='models.E010', ) ] elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together): return [ checks.Error( "All 'unique_together' elements must be lists or tuples.", obj=cls, id='models.E011', ) ] else: errors = [] for fields in cls._meta.unique_together: errors.extend(cls._check_local_fields(fields, "unique_together")) return errors @classmethod def _check_local_fields(cls, fields, option): from django.db import models # In order to avoid hitting the relation tree prematurely, we use our # own fields_map instead of using get_field() forward_fields_map = { field.name: field for field in cls._meta._get_fields(reverse=False) } errors = [] for field_name in fields: try: field = forward_fields_map[field_name] except KeyError: errors.append( checks.Error( "'%s' refers to the nonexistent field '%s'." % ( option, field_name, ), obj=cls, id='models.E012', ) ) else: if isinstance(field.remote_field, models.ManyToManyRel): errors.append( checks.Error( "'%s' refers to a ManyToManyField '%s', but " "ManyToManyFields are not permitted in '%s'." % ( option, field_name, option, ), obj=cls, id='models.E013', ) ) elif field not in cls._meta.local_fields: errors.append( checks.Error( "'%s' refers to field '%s' which is not local to model '%s'." % (option, field_name, cls._meta.object_name), hint="This issue may be caused by multi-table inheritance.", obj=cls, id='models.E016', ) ) return errors @classmethod def _check_ordering(cls): """ Check "ordering" option -- is it a list of strings and do all fields exist? """ if cls._meta._ordering_clash: return [ checks.Error( "'ordering' and 'order_with_respect_to' cannot be used together.", obj=cls, id='models.E021', ), ] if cls._meta.order_with_respect_to or not cls._meta.ordering: return [] if not isinstance(cls._meta.ordering, (list, tuple)): return [ checks.Error( "'ordering' must be a tuple or list (even if you want to order by only one field).", obj=cls, id='models.E014', ) ] errors = [] fields = cls._meta.ordering # Skip '?' fields. fields = (f for f in fields if f != '?') # Convert "-field" to "field". fields = ((f[1:] if f.startswith('-') else f) for f in fields) # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). fields = (f for f in fields if LOOKUP_SEP not in f) # Skip ordering on pk. This is always a valid order_by field # but is an alias and therefore won't be found by opts.get_field. fields = {f for f in fields if f != 'pk'} # Check for invalid or nonexistent fields in ordering. invalid_fields = [] # Any field name that is not present in field_names does not exist. # Also, ordering by m2m fields is not allowed. opts = cls._meta valid_fields = set(chain.from_iterable( (f.name, f.attname) if not (f.auto_created and not f.concrete) else (f.field.related_query_name(),) for f in chain(opts.fields, opts.related_objects) )) invalid_fields.extend(fields - valid_fields) for invalid_field in invalid_fields: errors.append( checks.Error( "'ordering' refers to the nonexistent field '%s'." % invalid_field, obj=cls, id='models.E015', ) ) return errors @classmethod def _check_long_column_names(cls): """ Check that any auto-generated column names are shorter than the limits for each database in which the model will be created. """ errors = [] allowed_len = None db_alias = None # Find the minimum max allowed length among all specified db_aliases. for db in settings.DATABASES.keys(): # skip databases where the model won't be created if not router.allow_migrate_model(db, cls): continue connection = connections[db] max_name_length = connection.ops.max_name_length() if max_name_length is None or connection.features.truncates_names: continue else: if allowed_len is None: allowed_len = max_name_length db_alias = db elif max_name_length < allowed_len: allowed_len = max_name_length db_alias = db if allowed_len is None: return errors for f in cls._meta.local_fields: _, column_name = f.get_attname_column() # Check if auto-generated name for the field is too long # for the database. if f.db_column is None and column_name is not None and len(column_name) > allowed_len: errors.append( checks.Error( 'Autogenerated column name too long for field "%s". ' 'Maximum length is "%s" for database "%s".' % (column_name, allowed_len, db_alias), hint="Set the column name manually using 'db_column'.", obj=cls, id='models.E018', ) ) for f in cls._meta.local_many_to_many: # Skip nonexistent models. if isinstance(f.remote_field.through, str): continue # Check if auto-generated name for the M2M field is too long # for the database. for m2m in f.remote_field.through._meta.local_fields: _, rel_name = m2m.get_attname_column() if m2m.db_column is None and rel_name is not None and len(rel_name) > allowed_len: errors.append( checks.Error( 'Autogenerated column name too long for M2M field ' '"%s". Maximum length is "%s" for database "%s".' % (rel_name, allowed_len, db_alias), hint=( "Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'." ), obj=cls, id='models.E019', ) ) return errors ############################################ # HELPER FUNCTIONS (CURRIED MODEL METHODS) # ############################################ # ORDERING METHODS ######################### def method_set_order(ordered_obj, self, id_list, using=None): if using is None: using = DEFAULT_DB_ALIAS order_wrt = ordered_obj._meta.order_with_respect_to filter_args = order_wrt.get_forward_related_filter(self) # FIXME: It would be nice if there was an "update many" version of update # for situations like this. with transaction.atomic(using=using, savepoint=False): for i, j in enumerate(id_list): ordered_obj.objects.filter(pk=j, **filter_args).update(_order=i) def method_get_order(ordered_obj, self): order_wrt = ordered_obj._meta.order_with_respect_to filter_args = order_wrt.get_forward_related_filter(self) pk_name = ordered_obj._meta.pk.name return ordered_obj.objects.filter(**filter_args).values_list(pk_name, flat=True) def make_foreign_order_accessors(model, related_model): setattr( related_model, 'get_%s_order' % model.__name__.lower(), curry(method_get_order, model) ) setattr( related_model, 'set_%s_order' % model.__name__.lower(), curry(method_set_order, model) ) ######## # MISC # ######## def model_unpickle(model_id): """Used to unpickle Model subclasses with deferred fields.""" if isinstance(model_id, tuple): model = apps.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id return model.__new__(model) model_unpickle.__safe_for_unpickle__ = True def unpickle_inner_exception(klass, exception_name): # Get the exception class from the class it is attached to: exception = getattr(klass, exception_name) return exception.__new__(exception)
bsd-3-clause
kongseokhwan/kulcloud-iitp-neutron
neutron/tests/unit/plugins/cisco/n1kv/test_n1kv_plugin.py
5
64874
# Copyright 2013 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import mock import webob.exc from neutron.api import extensions as neutron_extensions from neutron.api.v2 import attributes from neutron import context import neutron.db.api as db from neutron.extensions import portbindings from neutron import manager from neutron.plugins.cisco.common import cisco_constants as c_const from neutron.plugins.cisco.common import cisco_exceptions as c_exc from neutron.plugins.cisco.common import config as c_conf from neutron.plugins.cisco.db import n1kv_db_v2 from neutron.plugins.cisco.db import n1kv_models_v2 from neutron.plugins.cisco.db import network_db_v2 as cdb from neutron.plugins.cisco import extensions from neutron.plugins.cisco.extensions import n1kv from neutron.plugins.cisco.extensions import network_profile from neutron.plugins.cisco.extensions import policy_profile from neutron.plugins.cisco.n1kv import n1kv_client from neutron.plugins.cisco.n1kv import n1kv_neutron_plugin from neutron.tests.unit import _test_extension_portbindings as test_bindings from neutron.tests.unit.api.v2 import test_base from neutron.tests.unit.db import test_db_base_plugin_v2 as test_plugin from neutron.tests.unit.extensions import test_l3 from neutron.tests.unit.plugins.cisco.n1kv import fake_client from neutron.tests.unit.scheduler import test_l3_agent_scheduler PHYS_NET = 'some-phys-net' VLAN_MIN = 100 VLAN_MAX = 110 TENANT_NOT_ADMIN = 'not_admin' TENANT_TEST = 'test' class FakeResponse(object): """ This object is returned by mocked requests lib instead of normal response. Initialize it with the status code, header and buffer contents you wish to return. """ def __init__(self, status, response_text, headers): self.buffer = response_text self.status_code = status self.headers = headers def json(self, *args, **kwargs): return self.buffer def _fake_setup_vsm(self): """Fake establish Communication with Cisco Nexus1000V VSM.""" self.agent_vsm = True self._populate_policy_profiles() class NetworkProfileTestExtensionManager(object): def get_resources(self): # Add the resources to the global attribute map # This is done here as the setup process won't # initialize the main API router which extends # the global attribute map attributes.RESOURCE_ATTRIBUTE_MAP.update( network_profile.RESOURCE_ATTRIBUTE_MAP) return network_profile.Network_profile.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class PolicyProfileTestExtensionManager(object): def get_resources(self): # Add the resources to the global attribute map # This is done here as the setup process won't # initialize the main API router which extends # the global attribute map attributes.RESOURCE_ATTRIBUTE_MAP.update( policy_profile.RESOURCE_ATTRIBUTE_MAP) return policy_profile.Policy_profile.get_resources() def get_actions(self): return [] def get_request_extensions(self): return [] class N1kvPluginTestCase(test_plugin.NeutronDbPluginV2TestCase): _plugin_name = ('neutron.plugins.cisco.n1kv.' 'n1kv_neutron_plugin.N1kvNeutronPluginV2') tenant_id = "some_tenant" DEFAULT_RESP_BODY = "" DEFAULT_RESP_CODE = 200 DEFAULT_CONTENT_TYPE = "" fmt = "json" def _make_test_policy_profile(self, name='service_profile'): """ Create a policy profile record for testing purpose. :param name: string representing the name of the policy profile to create. Default argument value chosen to correspond to the default name specified in config.py file. """ uuid = test_base._uuid() profile = {'id': uuid, 'name': name} return n1kv_db_v2.create_policy_profile(profile) def _make_test_profile(self, name='default_network_profile', segment_type=c_const.NETWORK_TYPE_VLAN, segment_range='386-400'): """ Create a profile record for testing purposes. :param name: string representing the name of the network profile to create. Default argument value chosen to correspond to the default name specified in config.py file. :param segment_type: string representing the type of network segment. :param segment_range: string representing the segment range for network profile. """ db_session = db.get_session() profile = {'name': name, 'segment_type': segment_type, 'tenant_id': self.tenant_id, 'segment_range': segment_range} if segment_type == c_const.NETWORK_TYPE_OVERLAY: profile['sub_type'] = 'unicast' profile['multicast_ip_range'] = '0.0.0.0' net_p = n1kv_db_v2.create_network_profile(db_session, profile) n1kv_db_v2.sync_vxlan_allocations(db_session, net_p) elif segment_type == c_const.NETWORK_TYPE_VLAN: profile['physical_network'] = PHYS_NET net_p = n1kv_db_v2.create_network_profile(db_session, profile) n1kv_db_v2.sync_vlan_allocations(db_session, net_p) n1kv_db_v2.create_profile_binding(db_session, self.tenant_id, net_p['id'], c_const.NETWORK) n1kv_db_v2.create_profile_binding(db_session, TENANT_NOT_ADMIN, net_p['id'], c_const.NETWORK) n1kv_db_v2.create_profile_binding(db_session, TENANT_TEST, net_p['id'], c_const.NETWORK) return net_p def setUp(self, ext_mgr=NetworkProfileTestExtensionManager()): """ Setup method for n1kv plugin tests. First step is to define an acceptable response from the VSM to our requests. This needs to be done BEFORE the setUp() function of the super-class is called. This default here works for many cases. If you need something extra, please define your own setUp() function in your test class, and set your DEFAULT_RESPONSE value also BEFORE calling the setUp() of the super-function (this one here). If you have set a value already, it will not be overwritten by this code. """ if not self.DEFAULT_RESP_BODY: self.DEFAULT_RESP_BODY = { "icehouse-pp": {"properties": {"name": "icehouse-pp", "id": "some-uuid-1"}}, "havana_pp": {"properties": {"name": "havana_pp", "id": "some-uuid-2"}}, "dhcp_pp": {"properties": {"name": "dhcp_pp", "id": "some-uuid-3"}}, } # Creating a mock HTTP connection object for requests lib. The N1KV # client interacts with the VSM via HTTP. Since we don't have a VSM # running in the unit tests, we need to 'fake' it by patching the HTTP # library itself. We install a patch for a fake HTTP connection class. # Using __name__ to avoid having to enter the full module path. http_patcher = mock.patch(n1kv_client.requests.__name__ + ".request") FakeHttpConnection = http_patcher.start() # Now define the return values for a few functions that may be called # on any instance of the fake HTTP connection class. self.resp_headers = {"content-type": "application/json"} FakeHttpConnection.return_value = (FakeResponse( self.DEFAULT_RESP_CODE, self.DEFAULT_RESP_BODY, self.resp_headers)) # Patch some internal functions in a few other parts of the system. # These help us move along, without having to mock up even more systems # in the background. # Return a dummy VSM IP address mock.patch(n1kv_client.__name__ + ".Client._get_vsm_hosts", new=lambda self: "127.0.0.1").start() # Return dummy user profiles mock.patch(cdb.__name__ + ".get_credential_name", new=lambda self: {"user_name": "admin", "password": "admin_password"}).start() n1kv_neutron_plugin.N1kvNeutronPluginV2._setup_vsm = _fake_setup_vsm neutron_extensions.append_api_extensions_path(extensions.__path__) # Save the original RESOURCE_ATTRIBUTE_MAP self.saved_attr_map = {} for resource, attrs in attributes.RESOURCE_ATTRIBUTE_MAP.items(): self.saved_attr_map[resource] = attrs.copy() # Update the RESOURCE_ATTRIBUTE_MAP with n1kv specific extended attrs. attributes.RESOURCE_ATTRIBUTE_MAP["networks"].update( n1kv.EXTENDED_ATTRIBUTES_2_0["networks"]) attributes.RESOURCE_ATTRIBUTE_MAP["ports"].update( n1kv.EXTENDED_ATTRIBUTES_2_0["ports"]) self.addCleanup(self.restore_resource_attribute_map) super(N1kvPluginTestCase, self).setUp(self._plugin_name, ext_mgr=ext_mgr) # Create some of the database entries that we require. self._make_test_profile() self._make_test_policy_profile() def restore_resource_attribute_map(self): # Restore the original RESOURCE_ATTRIBUTE_MAP attributes.RESOURCE_ATTRIBUTE_MAP = self.saved_attr_map class TestN1kvNetworkProfiles(N1kvPluginTestCase): def _prepare_net_profile_data(self, segment_type, sub_type=None, segment_range=None, mcast_ip_range=None): netp = {'name': 'netp1', 'segment_type': segment_type, 'tenant_id': self.tenant_id} if segment_type == c_const.NETWORK_TYPE_VLAN: netp['segment_range'] = segment_range or '100-110' netp['physical_network'] = PHYS_NET elif segment_type == c_const.NETWORK_TYPE_OVERLAY: netp['segment_range'] = segment_range or '10000-10010' netp['sub_type'] = sub_type or 'enhanced' netp['multicast_ip_range'] = (mcast_ip_range or "224.1.1.1-224.1.1.10") elif segment_type == c_const.NETWORK_TYPE_TRUNK: netp['sub_type'] = c_const.NETWORK_TYPE_VLAN data = {"network_profile": netp} return data def test_create_network_profile_vlan(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_create_network_profile_overlay(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_create_network_profile_overlay_missing_subtype(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) data['network_profile'].pop('sub_type') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_network_profile_trunk(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_create_network_profile_trunk_missing_subtype(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) data['network_profile'].pop('sub_type') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_network_profile_overlay_unreasonable_seg_range(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, segment_range='10000-1000000001') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_network_profile_plugin(self): net_p_dict = (self. _prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY)) net_p_req = self.new_create_request('network_profiles', net_p_dict) net_p = self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) data = {'network_profile': {'name': 'netp2'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 200) def test_update_network_profile_physical_network_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': {'physical_network': PHYS_NET}} net_p_req = self.new_update_request('network_profiles', data, net_p['id']) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_network_profile_segment_type_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': { 'segment_type': c_const.NETWORK_TYPE_OVERLAY}} net_p_req = self.new_update_request('network_profiles', data, net_p['id']) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_network_profile_sub_type_fail(self): net_p_dict = (self. _prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY)) net_p_req = self.new_create_request('network_profiles', net_p_dict) net_p = self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) data = {'network_profile': {'sub_type': c_const.NETWORK_TYPE_VLAN}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_network_profiles_with_networks_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': {'segment_range': '200-210'}} update_req = self.new_update_request('network_profiles', data, net_p['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 200) net_data = {'network': {'name': 'net1', n1kv.PROFILE_ID: net_p['id'], 'tenant_id': 'some_tenant'}} network_req = self.new_create_request('networks', net_data) network_res = network_req.get_response(self.api) self.assertEqual(network_res.status_int, 201) data = {'network_profile': {'segment_range': '300-310'}} update_req = self.new_update_request('network_profiles', data, net_p['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 409) def test_create_overlay_network_profile_invalid_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range='1.1.1.1') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_no_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN)) data['network_profile']['multicast_ip_range'] = '' net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_wrong_split_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '224.1.1.1.224.1.1.3') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_invalid_minip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '10.0.0.1-224.1.1.3') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_invalid_maxip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '224.1.1.1-20.0.0.1') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_create_overlay_network_profile_correct_multicast_pass(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) def test_update_overlay_network_profile_correct_multicast_pass(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'multicast_ip_range': '224.0.1.0-224.0.1.100'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 200) def test_create_overlay_network_profile_reservedip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY, sub_type=(c_const. NETWORK_SUBTYPE_NATIVE_VXLAN), mcast_ip_range= '224.0.0.100-224.0.1.100') net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 400) def test_update_overlay_network_profile_reservedip_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_OVERLAY) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'multicast_ip_range': '224.0.0.11-224.0.0.111'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_vlan_network_profile_multicast_fail(self): net_p = self._make_test_profile(name='netp1') data = {'network_profile': {'multicast_ip_range': '224.0.1.0-224.0.1.100'}} update_req = self.new_update_request('network_profiles', data, net_p['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_trunk_network_profile_segment_range_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'segment_range': '100-200'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_update_trunk_network_profile_multicast_fail(self): data = self._prepare_net_profile_data(c_const.NETWORK_TYPE_TRUNK) net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(res.status_int, 201) net_p = self.deserialize(self.fmt, res) data = {'network_profile': {'multicast_ip_range': '224.0.1.0-224.0.1.100'}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_res = update_req.get_response(self.ext_api) self.assertEqual(update_res.status_int, 400) def test_create_network_profile_populate_vlan_segment_pool(self): db_session = db.get_session() net_p_dict = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) net_p_req = self.new_create_request('network_profiles', net_p_dict) self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) for vlan in range(VLAN_MIN, VLAN_MAX + 1): self.assertIsNotNone(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, vlan)) self.assertFalse(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, vlan).allocated) self.assertRaises(c_exc.VlanIDNotFound, n1kv_db_v2.get_vlan_allocation, db_session, PHYS_NET, VLAN_MIN - 1) self.assertRaises(c_exc.VlanIDNotFound, n1kv_db_v2.get_vlan_allocation, db_session, PHYS_NET, VLAN_MAX + 1) def test_delete_network_profile_with_network_fail(self): net_p = self._make_test_profile(name='netp1') net_data = {'network': {'name': 'net1', n1kv.PROFILE_ID: net_p['id'], 'tenant_id': 'some_tenant'}} network_req = self.new_create_request('networks', net_data) network_res = network_req.get_response(self.api) self.assertEqual(network_res.status_int, 201) self._delete('network_profiles', net_p['id'], expected_code=409) def test_delete_network_profile_deallocate_vlan_segment_pool(self): db_session = db.get_session() net_p_dict = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) net_p_req = self.new_create_request('network_profiles', net_p_dict) net_p = self.deserialize(self.fmt, net_p_req.get_response(self.ext_api)) self.assertIsNotNone(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, VLAN_MIN)) self._delete('network_profiles', net_p['network_profile']['id']) for vlan in range(VLAN_MIN, VLAN_MAX + 1): self.assertRaises(c_exc.VlanIDNotFound, n1kv_db_v2.get_vlan_allocation, db_session, PHYS_NET, vlan) def test_create_network_profile_rollback_profile_binding(self): """Test rollback of profile binding if network profile create fails.""" db_session = db.get_session() client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidResponse) client_patch.start() net_p_dict = self._prepare_net_profile_data(c_const.NETWORK_TYPE_VLAN) self.new_create_request('network_profiles', net_p_dict) bindings = (db_session.query(n1kv_models_v2.ProfileBinding).filter_by( profile_type="network")) self.assertEqual(3, bindings.count()) def test_create_network_profile_with_old_add_tenant_fail(self): data = self._prepare_net_profile_data('vlan') data['network_profile']['add_tenant'] = 'tenant1' net_p_req = self.new_create_request('network_profiles', data) res = net_p_req.get_response(self.ext_api) self.assertEqual(400, res.status_int) def test_create_network_profile_multi_tenants(self): data = self._prepare_net_profile_data('vlan') data['network_profile'][c_const.ADD_TENANTS] = ['tenant1', 'tenant2'] del data['network_profile']['tenant_id'] net_p_req = self.new_create_request('network_profiles', data) net_p_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) res = net_p_req.get_response(self.ext_api) self.assertEqual(201, res.status_int) net_p = self.deserialize(self.fmt, res) db_session = db.get_session() tenant_id = n1kv_db_v2.get_profile_binding(db_session, self.tenant_id, net_p['network_profile']['id']) tenant1 = n1kv_db_v2.get_profile_binding(db_session, 'tenant1', net_p['network_profile']['id']) tenant2 = n1kv_db_v2.get_profile_binding(db_session, 'tenant2', net_p['network_profile']['id']) self.assertIsNotNone(tenant_id) self.assertIsNotNone(tenant1) self.assertIsNotNone(tenant2) return net_p def test_update_network_profile_multi_tenants(self): net_p = self.test_create_network_profile_multi_tenants() data = {'network_profile': {c_const.ADD_TENANTS: ['tenant1', 'tenant3']}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) update_res = update_req.get_response(self.ext_api) self.assertEqual(200, update_res.status_int) db_session = db.get_session() # current tenant_id should always present tenant_id = n1kv_db_v2.get_profile_binding(db_session, self.tenant_id, net_p['network_profile']['id']) tenant1 = n1kv_db_v2.get_profile_binding(db_session, 'tenant1', net_p['network_profile']['id']) self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_profile_binding, db_session, 'tenant4', net_p['network_profile']['id']) tenant3 = n1kv_db_v2.get_profile_binding(db_session, 'tenant3', net_p['network_profile']['id']) self.assertIsNotNone(tenant_id) self.assertIsNotNone(tenant1) self.assertIsNotNone(tenant3) data = {'network_profile': {c_const.REMOVE_TENANTS: [self.tenant_id, 'tenant1']}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) update_res = update_req.get_response(self.ext_api) self.assertEqual(200, update_res.status_int) # current tenant_id should always present tenant_id = n1kv_db_v2.get_profile_binding(db_session, self.tenant_id, net_p['network_profile']['id']) self.assertIsNotNone(tenant_id) self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_profile_binding, db_session, 'tenant1', net_p['network_profile']['id']) self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_profile_binding, db_session, 'tenant4', net_p['network_profile']['id']) tenant3 = n1kv_db_v2.get_profile_binding(db_session, 'tenant3', net_p['network_profile']['id']) self.assertIsNotNone(tenant3) # Add new tenant4 to network profile and make sure existing tenants # are not deleted. data = {'network_profile': {c_const.ADD_TENANTS: ['tenant4']}} update_req = self.new_update_request('network_profiles', data, net_p['network_profile']['id']) update_req.environ['neutron.context'] = context.Context('', self.tenant_id, is_admin=True) update_res = update_req.get_response(self.ext_api) self.assertEqual(200, update_res.status_int) tenant4 = n1kv_db_v2.get_profile_binding(db_session, 'tenant4', net_p['network_profile']['id']) self.assertIsNotNone(tenant4) def test_get_network_profile_restricted(self): c_conf.CONF.set_override('restrict_network_profiles', True, 'CISCO_N1K') ctx1 = context.Context(user_id='admin', tenant_id='tenant1', is_admin=True) sess1 = db.get_session() net_p = self._make_test_profile(name='netp1') n1kv_db_v2.create_profile_binding(sess1, ctx1.tenant_id, net_p['id'], c_const.NETWORK) #network profile binding with creator tenant should always exist profile = n1kv_db_v2.get_network_profile(sess1, net_p['id'], ctx1.tenant_id) self.assertIsNotNone(profile) ctx2 = context.Context(user_id='non_admin', tenant_id='tenant2', is_admin=False) sess2 = db.get_session() self.assertRaises(c_exc.ProfileTenantBindingNotFound, n1kv_db_v2.get_network_profile, sess2, net_p['id'], ctx2.tenant_id) def test_get_network_profile_unrestricted(self): c_conf.CONF.set_override('restrict_network_profiles', False, 'CISCO_N1K') ctx1 = context.Context(user_id='admin', tenant_id='tenant1', is_admin=True) sess1 = db.get_session() net_p = self._make_test_profile(name='netp1') n1kv_db_v2.create_profile_binding(sess1, ctx1.tenant_id, net_p['id'], c_const.NETWORK) # network profile binding with creator tenant should always exist profile = n1kv_db_v2.get_network_profile(sess1, net_p['id'], ctx1.tenant_id) self.assertIsNotNone(profile) ctx2 = context.Context(user_id='non_admin', tenant_id='tenant2', is_admin=False) sess2 = db.get_session() profile = n1kv_db_v2.get_network_profile(sess2, net_p['id'], ctx2.tenant_id) #network profile will be returned even though the profile is #not bound to tenant of sess2 self.assertIsNotNone(profile) class TestN1kvBasicGet(test_plugin.TestBasicGet, N1kvPluginTestCase): pass class TestN1kvHTTPResponse(test_plugin.TestV2HTTPResponse, N1kvPluginTestCase): pass class TestN1kvPorts(test_plugin.TestPortsV2, N1kvPluginTestCase, test_bindings.PortBindingsTestCase): VIF_TYPE = portbindings.VIF_TYPE_OVS HAS_PORT_FILTER = False _unsupported = ('test_delete_network_if_port_exists', 'test_requested_subnet_id_v4_and_v6') def setUp(self): if self._testMethodName in self._unsupported: self.skipTest("Unsupported test case") super(TestN1kvPorts, self).setUp() def test_create_port_with_default_n1kv_policy_profile_id(self): """Test port create without passing policy profile id.""" with self.port() as port: db_session = db.get_session() pp = n1kv_db_v2.get_policy_profile( db_session, port['port'][n1kv.PROFILE_ID]) self.assertEqual(pp['name'], 'service_profile') def test_create_port_with_n1kv_policy_profile_id(self): """Test port create with policy profile id.""" profile_obj = self._make_test_policy_profile(name='test_profile') with self.network() as network: data = {'port': {n1kv.PROFILE_ID: profile_obj.id, 'tenant_id': self.tenant_id, 'network_id': network['network']['id']}} port_req = self.new_create_request('ports', data) port = self.deserialize(self.fmt, port_req.get_response(self.api)) self.assertEqual(port['port'][n1kv.PROFILE_ID], profile_obj.id) self._delete('ports', port['port']['id']) def test_update_port_with_n1kv_policy_profile_id(self): """Test port update failure while updating policy profile id.""" with self.port() as port: data = {'port': {n1kv.PROFILE_ID: 'some-profile-uuid'}} port_req = self.new_update_request('ports', data, port['port']['id']) res = port_req.get_response(self.api) # Port update should fail to update policy profile id. self.assertEqual(res.status_int, 400) def test_create_first_port_invalid_parameters_fail(self): """Test parameters for first port create sent to the VSM.""" profile_obj = self._make_test_policy_profile(name='test_profile') with self.network() as network: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidRequest) client_patch.start() data = {'port': {n1kv.PROFILE_ID: profile_obj.id, 'tenant_id': self.tenant_id, 'network_id': network['network']['id'], }} port_req = self.new_create_request('ports', data) res = port_req.get_response(self.api) self.assertEqual(res.status_int, 500) client_patch.stop() def test_create_next_port_invalid_parameters_fail(self): """Test parameters for subsequent port create sent to the VSM.""" with self.port() as port: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidRequest) client_patch.start() data = {'port': {n1kv.PROFILE_ID: port['port']['n1kv:profile_id'], 'tenant_id': port['port']['tenant_id'], 'network_id': port['port']['network_id']}} port_req = self.new_create_request('ports', data) res = port_req.get_response(self.api) self.assertEqual(res.status_int, 500) client_patch.stop() def test_create_first_port_rollback_vmnetwork(self): """Test whether VMNetwork is cleaned up if port create fails on VSM.""" db_session = db.get_session() profile_obj = self._make_test_policy_profile(name='test_profile') with self.network() as network: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client. TestClientInvalidResponse) client_patch.start() data = {'port': {n1kv.PROFILE_ID: profile_obj.id, 'tenant_id': self.tenant_id, 'network_id': network['network']['id'], }} self.new_create_request('ports', data) self.assertRaises(c_exc.VMNetworkNotFound, n1kv_db_v2.get_vm_network, db_session, profile_obj.id, network['network']['id']) # Explicit stop of failure response mock from controller required # for network object clean up to succeed. client_patch.stop() def test_create_next_port_rollback_vmnetwork_count(self): """Test whether VMNetwork count if port create fails on VSM.""" db_session = db.get_session() with self.port() as port: pt = port['port'] old_vmn = n1kv_db_v2.get_vm_network(db_session, pt['n1kv:profile_id'], pt['network_id']) client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client. TestClientInvalidResponse) client_patch.start() data = {'port': {n1kv.PROFILE_ID: pt['n1kv:profile_id'], 'tenant_id': pt['tenant_id'], 'network_id': pt['network_id']}} self.new_create_request('ports', data) new_vmn = n1kv_db_v2.get_vm_network(db_session, pt['n1kv:profile_id'], pt['network_id']) self.assertEqual(old_vmn.port_count, new_vmn.port_count) # Explicit stop of failure response mock from controller required # for network object clean up to succeed. client_patch.stop() def test_delete_last_port_vmnetwork_cleanup(self): """Test whether VMNetwork is cleaned up from db on last port delete.""" db_session = db.get_session() with self.port() as port: pt = port['port'] self.assertIsNotNone(n1kv_db_v2. get_vm_network(db_session, pt['n1kv:profile_id'], pt['network_id'])) req = self.new_delete_request('ports', port['port']['id']) req.get_response(self.api) # Verify VMNetwork is cleaned up from the database on port delete. self.assertRaises(c_exc.VMNetworkNotFound, n1kv_db_v2.get_vm_network, db_session, pt['n1kv:profile_id'], pt['network_id']) class TestN1kvPolicyProfiles(N1kvPluginTestCase): def setUp(self): """ Setup function for policy profile tests. We need to use the policy profile extension manager for these test cases, so call the super class setup, but pass in the policy profile extension manager. """ super(TestN1kvPolicyProfiles, self).setUp( ext_mgr=PolicyProfileTestExtensionManager()) def test_populate_policy_profile(self): client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient) client_patch.start() instance = n1kv_neutron_plugin.N1kvNeutronPluginV2() instance._populate_policy_profiles() db_session = db.get_session() profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001') self.assertEqual('pp-1', profile['name']) client_patch.stop() def test_populate_policy_profile_delete(self): # Patch the Client class with the TestClient class with mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient): # Patch the _get_total_profiles() method to return a custom value with mock.patch(fake_client.__name__ + '.TestClient._get_total_profiles') as obj_inst: # Return 3 policy profiles obj_inst.return_value = 3 plugin = manager.NeutronManager.get_plugin() plugin._populate_policy_profiles() db_session = db.get_session() profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001') # Verify that DB contains only 3 policy profiles self.assertEqual('pp-1', profile['name']) profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000002') self.assertEqual('pp-2', profile['name']) profile = n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000003') self.assertEqual('pp-3', profile['name']) self.assertRaises(c_exc.PolicyProfileIdNotFound, n1kv_db_v2.get_policy_profile, db_session, '00000000-0000-0000-0000-000000000004') # Return 2 policy profiles obj_inst.return_value = 2 plugin._populate_policy_profiles() # Verify that the third policy profile is deleted self.assertRaises(c_exc.PolicyProfileIdNotFound, n1kv_db_v2.get_policy_profile, db_session, '00000000-0000-0000-0000-000000000003') def _init_get_policy_profiles(self): # Get the profiles mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient).start() instance = n1kv_neutron_plugin.N1kvNeutronPluginV2() instance._populate_policy_profiles() db_session = db.get_session() return [ n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000001'), n1kv_db_v2.get_policy_profile( db_session, '00000000-0000-0000-0000-000000000002') ] def _test_get_policy_profiles(self, expected_profiles, admin): resource = 'policy_profiles' if admin: ctx = context.Context(user_id='admin', tenant_id='tenant1', is_admin=True) else: ctx = context.Context(user_id='non_admin', tenant_id='tenant1', is_admin=False) res = self._list(resource, neutron_context=ctx) self.assertEqual(len(expected_profiles), len(res[resource])) profiles = sorted(res[resource]) for i in range(len(profiles)): self.assertEqual(expected_profiles[i].id, profiles[i]['id']) self.assertEqual(expected_profiles[i].name, profiles[i]['name']) def test_get_profiles_unrestricted(self): """ Test unrestricted policy profile retrieval. Test getting policy profiles using the normal unrestricted behavior. We set the flag and attempt to retrieve the port profiles. It should work for both admin and non-admin. """ # Get the profiles profiles = self._init_get_policy_profiles() # Set the restriction flag c_conf.CONF.set_override('restrict_policy_profiles', False, 'CISCO_N1K') # Request the list using non-admin and verify it returns self._test_get_policy_profiles(expected_profiles=profiles, admin=False) # Request the list using admin and verify it returns self._test_get_policy_profiles(expected_profiles=profiles, admin=True) def test_get_profiles_restricted(self): """ Test restricted policy profile retrieval. Test getting policy profiles using the restricted behavior. We set the flag and attempt to retrieve the port profiles. It should work for admin and fail for non-admin. """ # Get the profiles profiles = self._init_get_policy_profiles() # Set the restriction flag c_conf.CONF.set_override('restrict_policy_profiles', True, 'CISCO_N1K') # Request the list using non-admin and verify it returns no data self._test_get_policy_profiles(expected_profiles=[], admin=False) # Request the list using admin and verify it returns self._test_get_policy_profiles(expected_profiles=profiles, admin=True) def test_get_policy_profiles_by_name(self): with mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClient): instance = n1kv_neutron_plugin.N1kvNeutronPluginV2() profile = instance._get_policy_profile_by_name('pp-1') self.assertEqual('pp-1', profile['name']) self.assertEqual('00000000-0000-0000-0000-000000000001', profile['id']) self.assertRaises(c_exc.PolicyProfileNameNotFound, instance._get_policy_profile_by_name, "name") class TestN1kvNetworks(test_plugin.TestNetworksV2, N1kvPluginTestCase): def test_plugin(self): self._make_network('json', 'some_net', True, tenant_id=self.tenant_id, set_context=True) req = self.new_list_request('networks', params="fields=tenant_id") req.environ['neutron.context'] = context.Context('', self.tenant_id) res = req.get_response(self.api) self.assertEqual(res.status_int, 200) body = self.deserialize('json', res) self.assertIn('tenant_id', body['networks'][0]) def _prepare_net_data(self, net_profile_id): return {'network': {'name': 'net1', n1kv.PROFILE_ID: net_profile_id, 'tenant_id': self.tenant_id}} def test_create_network_with_default_n1kv_network_profile_id(self): """Test network create without passing network profile id.""" with self.network() as network: db_session = db.get_session() np = n1kv_db_v2.get_network_profile( db_session, network['network'][n1kv.PROFILE_ID]) self.assertEqual(np['name'], 'default_network_profile') def test_create_network_with_n1kv_network_profile_id(self): """Test network create with network profile id.""" profile_obj = self._make_test_profile(name='test_profile') data = self._prepare_net_data(profile_obj.id) network_req = self.new_create_request('networks', data) network = self.deserialize(self.fmt, network_req.get_response(self.api)) self.assertEqual(network['network'][n1kv.PROFILE_ID], profile_obj.id) def test_update_network_with_n1kv_network_profile_id(self): """Test network update failure while updating network profile id.""" with self.network() as network: data = {'network': {n1kv.PROFILE_ID: 'some-profile-uuid'}} network_req = self.new_update_request('networks', data, network['network']['id']) res = network_req.get_response(self.api) # Network update should fail to update network profile id. self.assertEqual(res.status_int, 400) def test_create_network_rollback_deallocate_vlan_segment(self): """Test vlan segment deallocation on network create failure.""" profile_obj = self._make_test_profile(name='test_profile', segment_range='20-23') data = self._prepare_net_data(profile_obj.id) client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidResponse) client_patch.start() self.new_create_request('networks', data) db_session = db.get_session() self.assertFalse(n1kv_db_v2.get_vlan_allocation(db_session, PHYS_NET, 20).allocated) def test_create_network_rollback_deallocate_overlay_segment(self): """Test overlay segment deallocation on network create failure.""" profile_obj = self._make_test_profile('test_np', c_const.NETWORK_TYPE_OVERLAY, '10000-10001') data = self._prepare_net_data(profile_obj.id) client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidResponse) client_patch.start() self.new_create_request('networks', data) db_session = db.get_session() self.assertFalse(n1kv_db_v2.get_vxlan_allocation(db_session, 10000).allocated) def test_delete_network(self): """Regular test case of network deletion. Should return successful.""" res = self._create_network(self.fmt, name='net', admin_state_up=True) network = self.deserialize(self.fmt, res) req = self.new_delete_request('networks', network['network']['id']) res = req.get_response(self.api) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) def test_delete_network_with_subnet(self): """Network deletion fails when a subnet is present on the network.""" with self.subnet() as subnet: net_id = subnet['subnet']['network_id'] req = self.new_delete_request('networks', net_id) res = req.get_response(self.api) self.assertEqual(res.status_int, webob.exc.HTTPBadRequest.code) def test_update_network_set_not_shared_multi_tenants2_returns_409(self): """ Verifies that updating a network which cannot be shared, returns a conflict error. """ with self.network(shared=True) as network: res = self._create_port(self.fmt, network['network']['id'], webob.exc.HTTPCreated.code, tenant_id='somebody_else', set_context=True) data = {'network': {'shared': False}} req = self.new_update_request('networks', data, network['network']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPConflict.code) port = self.deserialize(self.fmt, res) self._delete('ports', port['port']['id']) def test_delete_network_if_port_exists(self): """Verify that a network with a port attached cannot be removed.""" res = self._create_network(self.fmt, name='net1', admin_state_up=True) network = self.deserialize(self.fmt, res) net_id = network['network']['id'] res = self._create_port(self.fmt, net_id, webob.exc.HTTPCreated.code) req = self.new_delete_request('networks', net_id) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPConflict.code) class TestN1kvSubnets(test_plugin.TestSubnetsV2, N1kvPluginTestCase): _unsupported = ( 'test_delete_network', 'test_create_subnets_bulk_emulated', 'test_create_subnets_bulk_emulated_plugin_failure') def setUp(self): if self._testMethodName in self._unsupported: self.skipTest("Unsupported test") super(TestN1kvSubnets, self).setUp() def test_port_prevents_network_deletion(self): self.skipTest("plugin does not return standard conflict code") def test_create_subnet_with_invalid_parameters(self): """Test subnet creation with invalid parameters sent to the VSM""" with self.network() as network: client_patch = mock.patch(n1kv_client.__name__ + ".Client", new=fake_client.TestClientInvalidRequest) client_patch.start() data = {'subnet': {'network_id': network['network']['id'], 'cidr': "10.0.0.0/24"}} subnet_req = self.new_create_request('subnets', data) subnet_resp = subnet_req.get_response(self.api) # Subnet creation should fail due to invalid network name self.assertEqual(subnet_resp.status_int, 400) def test_update_subnet_adding_additional_host_routes_and_dns(self): host_routes = [{'destination': '172.16.0.0/24', 'nexthop': '10.0.2.2'}] with self.network() as network: data = {'subnet': {'network_id': network['network']['id'], 'cidr': '10.0.2.0/24', 'ip_version': 4, 'dns_nameservers': ['192.168.0.1'], 'host_routes': host_routes, 'tenant_id': network['network']['tenant_id']}} req = self.new_create_request('subnets', data) subnet = self.deserialize(self.fmt, req.get_response(self.api)) host_routes = [{'destination': '172.16.0.0/24', 'nexthop': '10.0.2.2'}, {'destination': '192.168.0.0/24', 'nexthop': '10.0.2.3'}] dns_nameservers = ['192.168.0.1', '192.168.0.2'] data = {'subnet': {'host_routes': host_routes, 'dns_nameservers': dns_nameservers}} req = self.new_update_request('subnets', data, subnet['subnet']['id']) subnet = self.deserialize(self.fmt, req.get_response(self.api)) self.assertEqual(sorted(subnet['subnet']['host_routes']), sorted(host_routes)) self.assertEqual(sorted(subnet['subnet']['dns_nameservers']), sorted(dns_nameservers)) # In N1K we need to delete the subnet before the network req = self.new_delete_request('subnets', subnet['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) def test_subnet_with_allocation_range(self): with self.network() as network: net_id = network['network']['id'] data = {'subnet': {'network_id': net_id, 'cidr': '10.0.0.0/24', 'ip_version': 4, 'gateway_ip': '10.0.0.1', 'tenant_id': network['network']['tenant_id'], 'allocation_pools': [{'start': '10.0.0.100', 'end': '10.0.0.120'}]}} req = self.new_create_request('subnets', data) subnet = self.deserialize(self.fmt, req.get_response(self.api)) # Check fixed IP not in allocation range kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'], 'ip_address': '10.0.0.10'}]} res = self._create_port(self.fmt, net_id=net_id, **kwargs) self.assertEqual(res.status_int, webob.exc.HTTPCreated.code) port = self.deserialize(self.fmt, res) # delete the port self._delete('ports', port['port']['id']) # Check when fixed IP is gateway kwargs = {"fixed_ips": [{'subnet_id': subnet['subnet']['id'], 'ip_address': '10.0.0.1'}]} res = self._create_port(self.fmt, net_id=net_id, **kwargs) self.assertEqual(res.status_int, webob.exc.HTTPCreated.code) port = self.deserialize(self.fmt, res) # delete the port self._delete('ports', port['port']['id']) req = self.new_delete_request('subnets', subnet['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) def test_requested_subnet_id_v4_and_v6(self): with self.network() as network: net_id = network['network']['id'] res = self._create_subnet(self.fmt, tenant_id='tenant1', net_id=net_id, cidr='10.0.0.0/24', ip_version=4, gateway_ip=attributes.ATTR_NOT_SPECIFIED) subnet1 = self.deserialize(self.fmt, res) res = self._create_subnet(self.fmt, tenant_id='tenant1', net_id=net_id, cidr='2607:f0d0:1002:51::/124', ip_version=6, gateway_ip=attributes.ATTR_NOT_SPECIFIED) subnet2 = self.deserialize(self.fmt, res) kwargs = {"fixed_ips": [{'subnet_id': subnet1['subnet']['id']}, {'subnet_id': subnet2['subnet']['id']}]} res = self._create_port(self.fmt, net_id=net_id, **kwargs) port3 = self.deserialize(self.fmt, res) ips = port3['port']['fixed_ips'] self.assertEqual(len(ips), 2) self.assertIn({'ip_address': '10.0.0.2', 'subnet_id': subnet1['subnet']['id']}, ips) self.assertIn({'ip_address': '2607:f0d0:1002:51::2', 'subnet_id': subnet2['subnet']['id']}, ips) res = self._create_port(self.fmt, net_id=net_id) port4 = self.deserialize(self.fmt, res) # Check that a v4 and a v6 address are allocated ips = port4['port']['fixed_ips'] self.assertEqual(len(ips), 2) self.assertIn({'ip_address': '10.0.0.3', 'subnet_id': subnet1['subnet']['id']}, ips) self.assertIn({'ip_address': '2607:f0d0:1002:51::3', 'subnet_id': subnet2['subnet']['id']}, ips) self._delete('ports', port3['port']['id']) self._delete('ports', port4['port']['id']) req = self.new_delete_request('subnets', subnet1['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) req = self.new_delete_request('subnets', subnet2['subnet']['id']) self.assertEqual(req.get_response(self.api).status_int, webob.exc.HTTPNoContent.code) def test_schedule_network_with_subnet_create(self): """Test invocation of explicit scheduling for networks.""" with mock.patch.object(n1kv_neutron_plugin.N1kvNeutronPluginV2, 'schedule_network') as mock_method: # Test with network auto-scheduling disabled c_conf.CONF.set_override('network_auto_schedule', False) # Subnet creation should trigger scheduling for networks with self.subnet(): pass self.assertEqual(1, mock_method.call_count) class TestN1kvL3Test(test_l3.L3NatExtensionTestCase): pass class TestN1kvL3SchedulersTest(test_l3_agent_scheduler.L3SchedulerTestCase): pass
apache-2.0
sunqb/oa_qian
flask/Lib/site-packages/sqlalchemy/orm/evaluator.py
33
5032
# orm/evaluator.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php import operator from ..sql import operators from .. import util class UnevaluatableError(Exception): pass _straight_ops = set(getattr(operators, op) for op in ('add', 'mul', 'sub', 'div', 'mod', 'truediv', 'lt', 'le', 'ne', 'gt', 'ge', 'eq')) _notimplemented_ops = set(getattr(operators, op) for op in ('like_op', 'notlike_op', 'ilike_op', 'notilike_op', 'between_op', 'in_op', 'notin_op', 'endswith_op', 'concat_op')) class EvaluatorCompiler(object): def __init__(self, target_cls=None): self.target_cls = target_cls def process(self, clause): meth = getattr(self, "visit_%s" % clause.__visit_name__, None) if not meth: raise UnevaluatableError( "Cannot evaluate %s" % type(clause).__name__) return meth(clause) def visit_grouping(self, clause): return self.process(clause.element) def visit_null(self, clause): return lambda obj: None def visit_false(self, clause): return lambda obj: False def visit_true(self, clause): return lambda obj: True def visit_column(self, clause): if 'parentmapper' in clause._annotations: parentmapper = clause._annotations['parentmapper'] if self.target_cls and not issubclass( self.target_cls, parentmapper.class_): util.warn( "Can't do in-Python evaluation of criteria against " "alternate class %s; " "expiration of objects will not be accurate " "and/or may fail. synchronize_session should be set to " "False or 'fetch'. " "This warning will be an exception " "in 1.0." % parentmapper.class_ ) key = parentmapper._columntoproperty[clause].key else: key = clause.key get_corresponding_attr = operator.attrgetter(key) return lambda obj: get_corresponding_attr(obj) def visit_clauselist(self, clause): evaluators = list(map(self.process, clause.clauses)) if clause.operator is operators.or_: def evaluate(obj): has_null = False for sub_evaluate in evaluators: value = sub_evaluate(obj) if value: return True has_null = has_null or value is None if has_null: return None return False elif clause.operator is operators.and_: def evaluate(obj): for sub_evaluate in evaluators: value = sub_evaluate(obj) if not value: if value is None: return None return False return True else: raise UnevaluatableError( "Cannot evaluate clauselist with operator %s" % clause.operator) return evaluate def visit_binary(self, clause): eval_left, eval_right = list(map(self.process, [clause.left, clause.right])) operator = clause.operator if operator is operators.is_: def evaluate(obj): return eval_left(obj) == eval_right(obj) elif operator is operators.isnot: def evaluate(obj): return eval_left(obj) != eval_right(obj) elif operator in _straight_ops: def evaluate(obj): left_val = eval_left(obj) right_val = eval_right(obj) if left_val is None or right_val is None: return None return operator(eval_left(obj), eval_right(obj)) else: raise UnevaluatableError( "Cannot evaluate %s with operator %s" % (type(clause).__name__, clause.operator)) return evaluate def visit_unary(self, clause): eval_inner = self.process(clause.element) if clause.operator is operators.inv: def evaluate(obj): value = eval_inner(obj) if value is None: return None return not value return evaluate raise UnevaluatableError( "Cannot evaluate %s with operator %s" % (type(clause).__name__, clause.operator)) def visit_bindparam(self, clause): val = clause.value return lambda obj: val
apache-2.0
AndreaCrotti/ansible
lib/ansible/plugins/callback/timer.py
141
1030
import os import datetime from datetime import datetime, timedelta from ansible.plugins.callback import CallbackBase class CallbackModule(CallbackBase): """ This callback module tells you how long your plays ran for. """ CALLBACK_VERSION = 2.0 CALLBACK_TYPE = 'aggregate' CALLBACK_NAME = 'timer' def __init__(self, display): super(CallbackModule, self).__init__(display) self.start_time = datetime.now() def days_hours_minutes_seconds(self, timedelta): minutes = (timedelta.seconds//60)%60 r_seconds = timedelta.seconds - (minutes * 60) return timedelta.days, timedelta.seconds//3600, minutes, r_seconds def playbook_on_stats(self, stats): self.v2_playbook_on_stats(stats) def v2_playbook_on_stats(self, stats): end_time = datetime.now() timedelta = end_time - self.start_time self._display.display("Playbook run took %s days, %s hours, %s minutes, %s seconds" % (self.days_hours_minutes_seconds(timedelta)))
gpl-3.0
neocogent/electrum
electrum/tests/test_mnemonic.py
2
11878
from typing import NamedTuple, Optional from electrum import keystore from electrum import mnemonic from electrum import old_mnemonic from electrum.util import bh2u, bfh from electrum.mnemonic import is_new_seed, is_old_seed, seed_type from electrum.version import SEED_PREFIX_SW, SEED_PREFIX from . import SequentialTestCase from .test_wallet_vertical import UNICODE_HORROR, UNICODE_HORROR_HEX class SeedTestCase(NamedTuple): words: str bip32_seed: str lang: Optional[str] = 'en' words_hex: Optional[str] = None entropy: Optional[int] = None passphrase: Optional[str] = None passphrase_hex: Optional[str] = None seed_version: str = SEED_PREFIX SEED_TEST_CASES = { 'english': SeedTestCase( words='wild father tree among universe such mobile favorite target dynamic credit identify', seed_version=SEED_PREFIX_SW, bip32_seed='aac2a6302e48577ab4b46f23dbae0774e2e62c796f797d0a1b5faeb528301e3064342dafb79069e7c4c6b8c38ae11d7a973bec0d4f70626f8cc5184a8d0b0756'), 'english_with_passphrase': SeedTestCase( words='wild father tree among universe such mobile favorite target dynamic credit identify', seed_version=SEED_PREFIX_SW, passphrase='Did you ever hear the tragedy of Darth Plagueis the Wise?', bip32_seed='4aa29f2aeb0127efb55138ab9e7be83b36750358751906f86c662b21a1ea1370f949e6d1a12fa56d3d93cadda93038c76ac8118597364e46f5156fde6183c82f'), 'japanese': SeedTestCase( lang='ja', words='なのか ひろい しなん まなぶ つぶす さがす おしゃれ かわく おいかける けさき かいとう さたん', words_hex='e381aae381aee3818b20e381b2e3828de3818420e38197e381aae3829320e381bee381aae381b5e3829920e381a4e381b5e38299e3819920e38195e3818be38299e3819920e3818ae38197e38283e3828c20e3818be3828fe3818f20e3818ae38184e3818be38191e3828b20e38191e38195e3818d20e3818be38184e381a8e3818620e38195e3819fe38293', entropy=1938439226660562861250521787963972783469, bip32_seed='d3eaf0e44ddae3a5769cb08a26918e8b308258bcb057bb704c6f69713245c0b35cb92c03df9c9ece5eff826091b4e74041e010b701d44d610976ce8bfb66a8ad'), 'japanese_with_passphrase': SeedTestCase( lang='ja', words='なのか ひろい しなん まなぶ つぶす さがす おしゃれ かわく おいかける けさき かいとう さたん', words_hex='e381aae381aee3818b20e381b2e3828de3818420e38197e381aae3829320e381bee381aae381b5e3829920e381a4e381b5e38299e3819920e38195e3818be38299e3819920e3818ae38197e38283e3828c20e3818be3828fe3818f20e3818ae38184e3818be38191e3828b20e38191e38195e3818d20e3818be38184e381a8e3818620e38195e3819fe38293', entropy=1938439226660562861250521787963972783469, passphrase=UNICODE_HORROR, passphrase_hex=UNICODE_HORROR_HEX, bip32_seed='251ee6b45b38ba0849e8f40794540f7e2c6d9d604c31d68d3ac50c034f8b64e4bc037c5e1e985a2fed8aad23560e690b03b120daf2e84dceb1d7857dda042457'), 'chinese': SeedTestCase( lang='zh', words='眼 悲 叛 改 节 跃 衡 响 疆 股 遂 冬', words_hex='e79cbc20e682b220e58f9b20e694b920e88a8220e8b78320e8a1a120e5938d20e7968620e882a120e9818220e586ac', seed_version=SEED_PREFIX_SW, entropy=3083737086352778425940060465574397809099, bip32_seed='0b9077db7b5a50dbb6f61821e2d35e255068a5847e221138048a20e12d80b673ce306b6fe7ac174ebc6751e11b7037be6ee9f17db8040bb44f8466d519ce2abf'), 'chinese_with_passphrase': SeedTestCase( lang='zh', words='眼 悲 叛 改 节 跃 衡 响 疆 股 遂 冬', words_hex='e79cbc20e682b220e58f9b20e694b920e88a8220e8b78320e8a1a120e5938d20e7968620e882a120e9818220e586ac', seed_version=SEED_PREFIX_SW, entropy=3083737086352778425940060465574397809099, passphrase='给我一些测试向量谷歌', passphrase_hex='e7bb99e68891e4b880e4ba9be6b58be8af95e59091e9878fe8b0b7e6ad8c', bip32_seed='6c03dd0615cf59963620c0af6840b52e867468cc64f20a1f4c8155705738e87b8edb0fc8a6cee4085776cb3a629ff88bb1a38f37085efdbf11ce9ec5a7fa5f71'), 'spanish': SeedTestCase( lang='es', words='almíbar tibio superar vencer hacha peatón príncipe matar consejo polen vehículo odisea', words_hex='616c6d69cc8162617220746962696f20737570657261722076656e63657220686163686120706561746fcc816e20707269cc816e63697065206d6174617220636f6e73656a6f20706f6c656e2076656869cc8163756c6f206f6469736561', entropy=3423992296655289706780599506247192518735, bip32_seed='18bffd573a960cc775bbd80ed60b7dc00bc8796a186edebe7fc7cf1f316da0fe937852a969c5c79ded8255cdf54409537a16339fbe33fb9161af793ea47faa7a'), 'spanish_with_passphrase': SeedTestCase( lang='es', words='almíbar tibio superar vencer hacha peatón príncipe matar consejo polen vehículo odisea', words_hex='616c6d69cc8162617220746962696f20737570657261722076656e63657220686163686120706561746fcc816e20707269cc816e63697065206d6174617220636f6e73656a6f20706f6c656e2076656869cc8163756c6f206f6469736561', entropy=3423992296655289706780599506247192518735, passphrase='araña difícil solución término cárcel', passphrase_hex='6172616ecc83612064696669cc8163696c20736f6c7563696fcc816e207465cc81726d696e6f206361cc817263656c', bip32_seed='363dec0e575b887cfccebee4c84fca5a3a6bed9d0e099c061fa6b85020b031f8fe3636d9af187bf432d451273c625e20f24f651ada41aae2c4ea62d87e9fa44c'), 'spanish2': SeedTestCase( lang='es', words='equipo fiar auge langosta hacha calor trance cubrir carro pulmón oro áspero', words_hex='65717569706f20666961722061756765206c616e676f7374612068616368612063616c6f72207472616e63652063756272697220636172726f2070756c6d6fcc816e206f726f2061cc81737065726f', seed_version=SEED_PREFIX_SW, entropy=448346710104003081119421156750490206837, bip32_seed='001ebce6bfde5851f28a0d44aae5ae0c762b600daf3b33fc8fc630aee0d207646b6f98b18e17dfe3be0a5efe2753c7cdad95860adbbb62cecad4dedb88e02a64'), 'spanish3': SeedTestCase( lang='es', words='vidrio jabón muestra pájaro capucha eludir feliz rotar fogata pez rezar oír', words_hex='76696472696f206a61626fcc816e206d756573747261207061cc816a61726f206361707563686120656c756469722066656c697a20726f74617220666f676174612070657a2072657a6172206f69cc8172', seed_version=SEED_PREFIX_SW, entropy=3444792611339130545499611089352232093648, passphrase='¡Viva España! repiten veinte pueblos y al hablar dan fe del ánimo español... ¡Marquen arado martillo y clarín', passphrase_hex='c2a1566976612045737061c3b16121207265706974656e207665696e746520707565626c6f73207920616c206861626c61722064616e2066652064656c20c3a16e696d6f2065737061c3b16f6c2e2e2e20c2a14d61727175656e20617261646f206d617274696c6c6f207920636c6172c3ad6e', bip32_seed='c274665e5453c72f82b8444e293e048d700c59bf000cacfba597629d202dcf3aab1cf9c00ba8d3456b7943428541fed714d01d8a0a4028fc3a9bb33d981cb49f'), } class Test_NewMnemonic(SequentialTestCase): def test_mnemonic_to_seed_basic(self): # note: not a valid electrum seed seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic='foobar', passphrase='none') self.assertEqual('741b72fd15effece6bfe5a26a52184f66811bd2be363190e07a42cca442b1a5bb22b3ad0eb338197287e6d314866c7fba863ac65d3f156087a5052ebc7157fce', bh2u(seed)) def test_mnemonic_to_seed(self): for test_name, test in SEED_TEST_CASES.items(): if test.words_hex is not None: self.assertEqual(test.words_hex, bh2u(test.words.encode('utf8')), msg=test_name) self.assertTrue(is_new_seed(test.words, prefix=test.seed_version), msg=test_name) m = mnemonic.Mnemonic(lang=test.lang) if test.entropy is not None: self.assertEqual(test.entropy, m.mnemonic_decode(test.words), msg=test_name) if test.passphrase_hex is not None: self.assertEqual(test.passphrase_hex, bh2u(test.passphrase.encode('utf8')), msg=test_name) seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic=test.words, passphrase=test.passphrase) self.assertEqual(test.bip32_seed, bh2u(seed), msg=test_name) def test_random_seeds(self): iters = 10 m = mnemonic.Mnemonic(lang='en') for _ in range(iters): seed = m.make_seed() i = m.mnemonic_decode(seed) self.assertEqual(m.mnemonic_encode(i), seed) class Test_OldMnemonic(SequentialTestCase): def test(self): seed = '8edad31a95e7d59f8837667510d75a4d' result = old_mnemonic.mn_encode(seed) words = 'hardly point goal hallway patience key stone difference ready caught listen fact' self.assertEqual(result, words.split()) self.assertEqual(old_mnemonic.mn_decode(result), seed) class Test_BIP39Checksum(SequentialTestCase): def test(self): mnemonic = u'gravity machine north sort system female filter attitude volume fold club stay feature office ecology stable narrow fog' is_checksum_valid, is_wordlist_valid = keystore.bip39_is_checksum_valid(mnemonic) self.assertTrue(is_wordlist_valid) self.assertTrue(is_checksum_valid) class Test_seeds(SequentialTestCase): """ Test old and new seeds. """ mnemonics = { ('cell dumb heartbeat north boom tease ship baby bright kingdom rare squeeze', 'old'), ('cell dumb heartbeat north boom tease ' * 4, 'old'), ('cell dumb heartbeat north boom tease ship baby bright kingdom rare badword', ''), ('cElL DuMb hEaRtBeAt nOrTh bOoM TeAsE ShIp bAbY BrIgHt kInGdOm rArE SqUeEzE', 'old'), (' cElL DuMb hEaRtBeAt nOrTh bOoM TeAsE ShIp bAbY BrIgHt kInGdOm rArE SqUeEzE ', 'old'), # below seed is actually 'invalid old' as it maps to 33 hex chars ('hurry idiot prefer sunset mention mist jaw inhale impossible kingdom rare squeeze', 'old'), ('cram swing cover prefer miss modify ritual silly deliver chunk behind inform able', 'standard'), ('cram swing cover prefer miss modify ritual silly deliver chunk behind inform', ''), ('ostrich security deer aunt climb inner alpha arm mutual marble solid task', 'standard'), ('OSTRICH SECURITY DEER AUNT CLIMB INNER ALPHA ARM MUTUAL MARBLE SOLID TASK', 'standard'), (' oStRiCh sEcUrItY DeEr aUnT ClImB InNeR AlPhA ArM MuTuAl mArBlE SoLiD TaSk ', 'standard'), ('x8', 'standard'), ('science dawn member doll dutch real can brick knife deny drive list', '2fa'), ('science dawn member doll dutch real ca brick knife deny drive list', ''), (' sCience dawn member doll Dutch rEAl can brick knife deny drive lisT', '2fa'), ('frost pig brisk excite novel report camera enlist axis nation novel desert', 'segwit'), (' fRoSt pig brisk excIte novel rePort CamEra enlist axis nation nOVeL dEsert ', 'segwit'), ('9dk', 'segwit'), } def test_new_seed(self): seed = "cram swing cover prefer miss modify ritual silly deliver chunk behind inform able" self.assertTrue(is_new_seed(seed)) seed = "cram swing cover prefer miss modify ritual silly deliver chunk behind inform" self.assertFalse(is_new_seed(seed)) def test_old_seed(self): self.assertTrue(is_old_seed(" ".join(["like"] * 12))) self.assertFalse(is_old_seed(" ".join(["like"] * 18))) self.assertTrue(is_old_seed(" ".join(["like"] * 24))) self.assertFalse(is_old_seed("not a seed")) self.assertTrue(is_old_seed("0123456789ABCDEF" * 2)) self.assertTrue(is_old_seed("0123456789ABCDEF" * 4)) def test_seed_type(self): for seed_words, _type in self.mnemonics: self.assertEqual(_type, seed_type(seed_words), msg=seed_words)
mit
jason-weirather/IDP-fusion-release-1
bin/generate_isoforms_fusion.py
1
53109
#!/usr/bin/python import sys import re import string #from constants import * import re valid_cigar = set("0123456789MNID") read_len_margin = 0 ### ########## def compute_min_ljust(str_value): return max(20, (len(str_value)/10 + 1) * 10) ### Due to redundancy, isoforms might not be generated for a fusion segment, ### Need to find the super/master LR ########### def find_super_fusion_id(fusion_name, read_mapping_dict, valid_readname_ls): key_2 = fusion_name key_1 = "invalid" while (key_1 != key_2): key_1 = key_2 if (read_mapping_dict.has_key(key_1)): key_2 = read_mapping_dict[key_1] else: break if (key_1 in valid_readname_ls): return key_1 else: return -1 ### ########### def parse_fusion_genenames(fusion_compatible_filename, fusion_gpd_filename, readmapping_filename): fusion_isofroms_pair_ls = [] MLE_input_dict = {} file = open(readmapping_filename, 'r') read_mapping_dict = dict() for line in file: fields = line.split() read_mapping_dict[fields[0]] = fields[1] file.close() file = open(fusion_gpd_filename, 'r') read_mate_dict = dict() readnames_ls = [] while True: line_1_ls = file.readline().strip().split() line_2_ls = file.readline().strip().split() if line_1_ls == []: break read_mate_dict[line_2_ls[0]] = line_1_ls[0] read_mate_dict[line_1_ls[0]] = line_2_ls[0] readnames_ls += [line_1_ls[0], line_2_ls[0]] file.close() fusion_gpd_dict = dict() fusion_gpd_file = open(fusion_compatible_filename, 'r') for line in fusion_gpd_file: fields = line.split() fusion_gpd_dict[fields[0]] = line fields = line.split() if (not read_mapping_dict.has_key(fields[0])): read_mapping_dict[fields[0]] = fields[0] fusion_gpd_file.close() processed_reads_ls = [] # To avoid duplicates valid_readname_ls = fusion_gpd_dict.keys() compreadname2readname_mapping = {} for readname_origin in readnames_ls: readname = find_super_fusion_id(readname_origin, read_mapping_dict, valid_readname_ls) if readname == -1: continue fields = fusion_gpd_dict[readname].split() [fusion_id, fusion_dir, fusion_pos]= re.split(r"(\+|\-)", (fields[0].split("|"))[1]) if (fusion_dir == '+'): # Change it to 1-based fusion_pos = str(1 + int(fusion_pos)) MLE_input_dict[fields[1]] = [] paired_readname = find_super_fusion_id(read_mate_dict[readname_origin], read_mapping_dict, valid_readname_ls) # Keep mapping of original readnames to uniqueue ones (for reference/debugging) if (paired_readname != -1): if (not compreadname2readname_mapping.has_key(readname)): compreadname2readname_mapping[readname] = {} if (not compreadname2readname_mapping[readname].has_key(paired_readname)): compreadname2readname_mapping[readname][paired_readname] = set() compreadname2readname_mapping[readname][paired_readname].add(re.split(r"(\+|\-)", (readname_origin.split("|"))[1])[0]) if (not compreadname2readname_mapping.has_key(paired_readname)): compreadname2readname_mapping[paired_readname] = {} if (not compreadname2readname_mapping[paired_readname].has_key(readname)): compreadname2readname_mapping[paired_readname][readname] = set() compreadname2readname_mapping[paired_readname][readname].add(re.split(r"(\+|\-)", (readname_origin.split("|"))[1])[0]) if (((str(paired_readname)+'_'+readname) not in processed_reads_ls) and ((readname+'_'+str(paired_readname)) not in processed_reads_ls)): # gene-names and isoform-points will be added append_ls = [[fields[0], fusion_dir, fusion_pos, fields[1], 0, 0]] if (fusion_dir == '+'): points_temp = fields[9].split(',')[:-1] append_ls[0][4] = [(int(i)+1) for i in points_temp] points_temp = fields[10].split(',')[:-1] append_ls[0][5] = [int(i) for i in points_temp] elif (fusion_dir == '-'): points_temp = fields[9].split(',')[:-1] append_ls[0][5] = list(reversed([(int(i)+1) for i in points_temp])) points_temp = fields[10].split(',')[:-1] append_ls[0][4] = list(reversed([int(i) for i in points_temp])) append_ls[0][4][0] = int(fusion_pos) if (paired_readname != -1): processed_reads_ls.append(readname+'_'+str(paired_readname)) paired_fields = fusion_gpd_dict[paired_readname].split() MLE_input_dict[paired_fields[1]] = [] [paired_fusion_id, paired_fusion_dir, paired_fusion_pos]= re.split(r"(\+|\-)", (paired_fields[0].split("|"))[1]) if (paired_fusion_dir == '+'): # Change it to 1-based paired_fusion_pos = str(1 + int(paired_fusion_pos)) append_ls.append([paired_fields[0], paired_fusion_dir, paired_fusion_pos, paired_fields[1], 0, 0]) if (paired_fusion_dir == '+'): points_temp = paired_fields[9].split(',')[:-1] append_ls[1][4] = [(int(i)+1) for i in points_temp] points_temp = paired_fields[10].split(',')[:-1] append_ls[1][5] = [int(i) for i in points_temp] elif (paired_fusion_dir == '-'): points_temp = paired_fields[9].split(',')[:-1] append_ls[1][5] = list(reversed([(int(i)+1) for i in points_temp])) points_temp = paired_fields[10].split(',')[:-1] append_ls[1][4] = list(reversed([int(i) for i in points_temp])) append_ls[1][4][0] = int(paired_fusion_pos) else: pass #append_ls.append([0, 0, 0, 0, 0, 0]) fusion_isofroms_pair_ls.append(append_ls) return [fusion_isofroms_pair_ls, MLE_input_dict, compreadname2readname_mapping] ### Store fusion gene information from MLE input file ######### def get_fusion_genomes(input_filename, MLE_input_dict): input_file = open(input_filename, 'r') line_index = 0; input_file.readline() # Pass the top line wr_flag = False for line in input_file: fields = line.split() if (line_index == 0): gname = fields[0] num_isoforms = int(fields[1]) rname = fields[2] if (gname in MLE_input_dict.keys()): wr_flag = True line_index += 1 if (wr_flag): MLE_input_dict[gname].append(line.strip()) if (line_index == (9 + num_isoforms)): line_index = 0 wr_flag = False input_file.close() for gname in MLE_input_dict.keys(): if MLE_input_dict[gname] == []: del MLE_input_dict[gname] return MLE_input_dict """ ### ### Note: fusion_isofroms_pair_ls elements that have '0' gnames, do not have generated isoforms! ########### def map_id2genome(fusion_compatible_filename, fusion_isofroms_pair_ls, MLE_input_dict): # Remove gene-names that are not generated in isoform_construction step for gname in MLE_input_dict.keys(): if (len( MLE_input_dict[gname]) < 5): del MLE_input_dict[gname] continue file = open(fusion_compatible_filename, 'r') for line in file: fields = line.split() [fusion_id, fusion_dir, fusion_pos]= re.split(r"(\+|\-)", (fields[0].split("|"))[1]) if (fusion_isofroms_pair_ls.has_key(fusion_id)): if (fusion_isofroms_pair_ls[fusion_id][0][0] == fields[0]): read_idx = 0 elif (fusion_isofroms_pair_ls[fusion_id][1][0] == fields[0]): read_idx = 1 fusion_isofroms_pair_ls[fusion_id][read_idx][3] = fields[1] #gene-name if (fusion_isofroms_pair_ls[fusion_id][read_idx][1] == '+'): points_temp = fields[9].split(',')[:-1] fusion_isofroms_pair_ls[fusion_id][read_idx][4] = [(int(i)+1) for i in points_temp] points_temp = fields[10].split(',')[:-1] fusion_isofroms_pair_ls[fusion_id][read_idx][5] = [int(i) for i in points_temp] elif (fusion_isofroms_pair_ls[fusion_id][read_idx][1] == '-'): points_temp = fields[9].split(',')[:-1] fusion_isofroms_pair_ls[fusion_id][read_idx][5] = list(reversed([(int(i)+1) for i in points_temp])) points_temp = fields[10].split(',')[:-1] fusion_isofroms_pair_ls[fusion_id][read_idx][4] = list(reversed([int(i) for i in points_temp])) fusion_isofroms_pair_ls[fusion_id][read_idx][4][0] = int(fusion_isofroms_pair_ls[fusion_id][read_idx][2]) read_mapping_dict[fields[0]] = fields[0] file.close() file = open(readmapping_filename, 'r') for line in file: fields = line.split() read_mapping_dict[fields[0]] = fields[1] file.close() for fusion_id in fusion_isofroms_pair_ls.keys(): for read_idx in [0, 1]: if fusion_isofroms_pair_ls[fusion_id][read_idx][3] == 0: # gene-name is not assigned super_fusion = find_super_fusion_id(fusion_isofroms_pair_ls[fusion_id][read_idx][0], read_mapping_dict) if (super_fusion == -1): break # Could not find associated gname super_fusion_id = re.split(r"(\+|\-)", (super_fusion.split("|"))[1])[0] if (fusion_isofroms_pair_ls[super_fusion_id][0][0] == super_fusion): super_read_idx = 0 elif (fusion_isofroms_pair_ls[super_fusion_id][1][0] == super_fusion): super_read_idx = 1 fusion_isofroms_pair_ls[fusion_id][read_idx][3] = fusion_isofroms_pair_ls[super_fusion_id][super_read_idx][3] fusion_isofroms_pair_ls[fusion_id][read_idx][4] = fusion_isofroms_pair_ls[super_fusion_id][super_read_idx][4] fusion_isofroms_pair_ls[fusion_id][read_idx][5] = fusion_isofroms_pair_ls[super_fusion_id][super_read_idx][5] valid_genenames = MLE_input_dict.keys() for fusion_id in fusion_isofroms_pair_ls.keys(): valid_flag = True if (fusion_isofroms_pair_ls[fusion_id][0][3] not in valid_genenames): valid_flag = False elif (fusion_isofroms_pair_ls[fusion_id][1][3] not in valid_genenames): valid_flag = False if (not valid_flag): del fusion_isofroms_pair_ls[fusion_id] return fusion_isofroms_pair_ls """ ### Merge genes data which are part of a fusion gene ########### def merge_fusion_genes(MLE_input_dict, fusion_isofroms_pair_ls): fusion_MLE_input_dict = dict() fusion_gnames_map = dict() for gname in MLE_input_dict.keys(): fusion_gnames_map[gname] = gname # Merge genomes part of fusion genes for fusion_isofroms_pair in fusion_isofroms_pair_ls: if (not fusion_gnames_map.has_key(fusion_isofroms_pair[0][3])): gname_1 = '' else: gname_1 = fusion_gnames_map[fusion_isofroms_pair[0][3]] if len(fusion_isofroms_pair) == 1: # not paired gname_2 = '' else: if (not fusion_gnames_map.has_key(fusion_isofroms_pair[1][3])): gname_2 = '' else: gname_2 = fusion_gnames_map[fusion_isofroms_pair[1][3]] if (gname_1 == gname_2): continue # They are already merged # Check if gname is generated as part of isoform construction (e.g. not skipped because num isoforms > limit) fusion_gname = '' if ((not fusion_MLE_input_dict.has_key(gname_1)) and (not MLE_input_dict.has_key(gname_1))): gname_1 = '' else: fusion_gname += gname_1 + '/' if ((not fusion_MLE_input_dict.has_key(gname_2)) and (not MLE_input_dict.has_key(gname_2))): gname_2 = '' else: fusion_gname += gname_2 + '/' if (fusion_gname == ''): continue else: fusion_gname = fusion_gname[:-1] gname_ls = list(set(fusion_gname.split('/'))) # Remove redundancy fusion_gname = '/'.join(gname_ls) for gname in gname_ls: fusion_gnames_map[gname] = fusion_gname # Reconstructs the joint genome if (fusion_MLE_input_dict.has_key(gname_1)): del fusion_MLE_input_dict[gname_1] if (fusion_MLE_input_dict.has_key(gname_2)): del fusion_MLE_input_dict[gname_2] num_isoforms = 0 num_isoforms_ls = [] chr_name = '' for gname in gname_ls: num_isoforms += int(MLE_input_dict[gname][0].split()[1]) num_isoforms_ls.append(int(MLE_input_dict[gname][0].split()[1])) chr_name += MLE_input_dict[gname][0].split()[2] + ',' chr_name = chr_name[:-1] # Exclude last ',' # gname, num_isoforms, chr line = '\t'.join([fusion_gname, ','.join([str(num_isoform) for num_isoform in num_isoforms_ls]), chr_name]) fusion_MLE_input_dict[fusion_gname] = [line] for i in range(1, 4): line = '' for gname in gname_ls: line += MLE_input_dict[gname][i] + '\t' fusion_MLE_input_dict[fusion_gname].append(line.strip()) line = '' i = 0 for gname in gname_ls: line += MLE_input_dict[gname][4].replace('P', string.uppercase[i]) + '\t' i += 1 fusion_MLE_input_dict[fusion_gname].append(line.strip()) for i in [5]: line = '' for gname in gname_ls: line += MLE_input_dict[gname][i] + '\t' fusion_MLE_input_dict[fusion_gname].append(line.strip()) line = '' i = 0 for gname in gname_ls: line += MLE_input_dict[gname][6].replace('P', string.uppercase[i]) + '\t' i += 1 fusion_MLE_input_dict[fusion_gname].append(line.strip()) accum_num_regions = 0 total_num_regions = len(line.split()) for idx_1 in range(len(gname_ls)): num_regions = len(MLE_input_dict[gname_ls[idx_1]][6].split()) for idx_2 in range(num_isoforms_ls[idx_1]): line = '\t'.join([str(0)] * accum_num_regions) + '\t' line += MLE_input_dict[gname_ls[idx_1]][7 + idx_2] + '\t' line += '\t'.join([str(0)] * (total_num_regions - accum_num_regions - num_regions)) fusion_MLE_input_dict[fusion_gname].append(line.strip()) accum_num_regions += num_regions for i in [-2, -1]: line = '' for gname in gname_ls: line += MLE_input_dict[gname][i] + '\t' fusion_MLE_input_dict[fusion_gname].append(line.strip()) # Remove fusion_gnames_map that are not in fusion_MLE_input_dict for gname in fusion_gnames_map.keys(): fusion_gname = fusion_gnames_map[gname] if (not fusion_MLE_input_dict.has_key(fusion_gname)): del fusion_gnames_map[gname] return [fusion_MLE_input_dict, fusion_gnames_map] ### Output valid regions around fusion points ### Input: start position index of each within fusion gene, ### fusion genes information ### MLE-format information for fusion gene ########## def get_fusion_regions(genes_start_point_idx, fusion_id_info, fusion_genename_info): # Keep points in order to avoid duplicate regions if (genes_start_point_idx[0][0] < genes_start_point_idx[1][0]): read_idx_ls = [0, 1] else: read_idx_ls = [1, 0] fusion_points_start = [0, 0] fusion_points_end = [0, 0] # Get exon boundaries of fusion genes for read_idx in read_idx_ls: fusion_points_start[read_idx] = fusion_id_info[read_idx][4] fusion_points_end[read_idx] = fusion_id_info[read_idx][5] fusion_regions_ls = [] fusion_regions_length_ls = [] point_ls = [int(i) for i in fusion_genename_info[5].split()] point_names_ls = fusion_genename_info[4].split() region_dict = {} segment_len = [(READ_LEN - READ_JUNC_MIN_MAP_LEN), READ_JUNC_MIN_MAP_LEN] while (True): subregion = [[], []] for read_idx in read_idx_ls: is_valid_region = True # First extend left gene by READ_LEN - READ_JUNC_MIN_MAP_LEN idx = -1 len_temp = 0 while (len_temp < segment_len[read_idx]): idx += 1 prev_len_temp = len_temp len_temp += abs(fusion_points_start[read_idx][idx] - fusion_points_end[read_idx][idx]) + 1 # start and end points are inclusive if ((idx + 1) == len(fusion_points_start[read_idx])): break # Update seg-length (in case, initially it is less than (READ_LEN - READ_JUNC_MIN_MAP_LEN)) segment_len[read_idx] = min(len_temp, segment_len[read_idx]) # Last exon segment should have minimum READ_JUNC_MIN_MAP_LEN length to have reliable read mapping if ((segment_len[read_idx] - prev_len_temp) < READ_JUNC_MIN_MAP_LEN): is_valid_region = False break if (fusion_id_info[read_idx][1] == '+'): end_point = fusion_points_start[read_idx][idx] + (segment_len[read_idx] - prev_len_temp) - 1 else: end_point = fusion_points_start[read_idx][idx] - (segment_len[read_idx] - prev_len_temp) + 1 start_point = fusion_points_start[read_idx][0] idx = 0 # Return empty dictionary if isorom for this fusio gene is not generated if (fusion_points_start[read_idx][0] not in point_ls[genes_start_point_idx[read_idx][0]: genes_start_point_idx[read_idx][1]]): return dict() point_idx = point_ls[genes_start_point_idx[read_idx][0]: genes_start_point_idx[read_idx][1]].index(start_point) + genes_start_point_idx[read_idx][0] subregion[read_idx].append(point_names_ls[point_idx]) if (fusion_id_info[read_idx][1] == '+'): point_idx += 1 else: point_idx -= 1 start_point = point_ls[point_idx] if (fusion_id_info[read_idx][1] == '+'): while (start_point <= end_point): if (point_ls[point_idx] >= fusion_points_start[read_idx][idx]): if (point_ls[point_idx] <= fusion_points_end[read_idx][idx]): subregion[read_idx].append(point_names_ls[point_idx]) point_idx += 1 start_point = point_ls[point_idx] else: idx += 1 else: point_idx += 1 start_point = point_ls[point_idx] elif (fusion_id_info[read_idx][1] == '-'): while (start_point >= end_point): if (point_ls[point_idx] >= fusion_points_end[read_idx][idx]): if (point_ls[point_idx] <= fusion_points_start[read_idx][idx]): subregion[read_idx].append(point_names_ls[point_idx]) point_idx -= 1 start_point = point_ls[point_idx] else: idx += 1 else: point_idx -= 1 start_point = point_ls[point_idx] if (is_valid_region): region = '-'.join(subregion[read_idx_ls[0]][::-1]) + '-' + '-'.join(subregion[read_idx_ls[1]]) if (region_dict.has_key(region)): region_dict[region] += 1 else: region_dict[region] = 1 segment_len[0] -= 1 segment_len[1] += 1 if (segment_len[0] < READ_JUNC_MIN_MAP_LEN): break return region_dict ### ########### def add_fusion_regions(fusion_MLE_input_dict, fusion_gnames_map, fusion_isofroms_pair_ls): for fusion_isofroms_pair in fusion_isofroms_pair_ls: if (len(fusion_isofroms_pair) == 1): #Not paired continue try: gname_1 = fusion_isofroms_pair[0][3] gname_2 = fusion_isofroms_pair[1][3] fusion_gene_name_1 = fusion_gnames_map[gname_1] fusion_gene_name_2 = fusion_gnames_map[gname_2] except KeyError: continue if ( fusion_gene_name_1 != fusion_gene_name_2): print "Err: expected to have same fusion gene-name" exit(1) fusion_gene_name = fusion_gene_name_1 gene_names_ls = (fusion_MLE_input_dict[fusion_gene_name][0].split())[0].split('/') point_names_ls = fusion_MLE_input_dict[fusion_gene_name][4].split() genes_start_point_names = [0] # point_name starting index for each gene alpha = point_names_ls[0][0] for idx in range(len(point_names_ls)): if (point_names_ls[idx][0] != alpha): # Note: we might not have P0 if exon is of length 1 (only odd point is present then) genes_start_point_names.append(idx) alpha = point_names_ls[idx][0] if (len(genes_start_point_names) != len(gene_names_ls)): print "Err: Unmatched list lengths" exit(1) genes_start_point_names.append(len(point_names_ls)) # Add this info to the fusion gene dict to be used later (if not already) if (len(fusion_MLE_input_dict[fusion_gene_name][0].split()) < 4): fusion_MLE_input_dict[fusion_gene_name][0] += '\t' + ','.join([str(i) for i in genes_start_point_names]) genes_start_point_idx = [gene_names_ls.index(gname_1), gene_names_ls.index(gname_2)] genes_start_point_names = [[genes_start_point_names[genes_start_point_idx[0]], genes_start_point_names[genes_start_point_idx[0] +1]], [genes_start_point_names[genes_start_point_idx[1]], genes_start_point_names[genes_start_point_idx[1] +1]]] # Get list of fusion regions region_dict = get_fusion_regions(genes_start_point_names, fusion_isofroms_pair, fusion_MLE_input_dict[fusion_gene_name]) num_isoforms = [int(i) for i in ((fusion_MLE_input_dict[fusion_gene_name][0].split())[1]).split(',')] num_isoforms = sum(num_isoforms) regions_ls = fusion_MLE_input_dict[fusion_gene_name][6].split() regions_len_ls = fusion_MLE_input_dict[fusion_gene_name][7 + num_isoforms].split() fusion_regions = region_dict.keys() for fusion_region in fusion_regions: if (fusion_region in regions_ls): del region_dict[fusion_region] else: regions_ls.append(fusion_region) regions_len_ls.append(str(region_dict[fusion_region])) fusion_MLE_input_dict[fusion_gene_name][6] = '\t'.join(regions_ls) fusion_MLE_input_dict[fusion_gene_name][7 + num_isoforms] = '\t'.join(regions_len_ls) # Add this info to fusion pairs fusion_isofroms_pair.append(fusion_regions) return fusion_MLE_input_dict ### ### Removes isoforms used as part of fusion isoforms ### Fill up isoform matrix for missing entries in fusion region for normal isoforms ########## def finalize_fusion_genes(fusion_MLE_input_dict): fusion_gname_ls = fusion_MLE_input_dict.keys() for fusion_gname in fusion_gname_ls: line_ls = fusion_MLE_input_dict[fusion_gname][0].split() num_isforms = sum([int(i) for i in line_ls[1].split(',')]) isoform_names_ls = fusion_MLE_input_dict[fusion_gname][1].strip().split() num_regions = len(fusion_MLE_input_dict[fusion_gname][6].split()) # Remove isoforms ending in .f iso_idx = 0 isoform_idx_to_remove = [] for isoform_name in isoform_names_ls: if (isoform_name[-2:] == ".f"): isoform_idx_to_remove.append(iso_idx) iso_idx += 1 isoform_idx_to_remove = list(reversed(isoform_idx_to_remove)) isoform_names_ls = fusion_MLE_input_dict[fusion_gname][1].split() isoform_mark_ls = fusion_MLE_input_dict[fusion_gname][2].split() isoform_len_ls = fusion_MLE_input_dict[fusion_gname][3].split() for isoform_idx in isoform_idx_to_remove: del fusion_MLE_input_dict[fusion_gname][7 + isoform_idx] del isoform_names_ls[isoform_idx] del isoform_len_ls[isoform_idx] del isoform_mark_ls[isoform_idx] num_isforms -= 1 fusion_MLE_input_dict[fusion_gname][1] = '\t'.join(isoform_names_ls) fusion_MLE_input_dict[fusion_gname][2] = '\t'.join(isoform_len_ls) # Mark fusion isoforms as known fusion_MLE_input_dict[fusion_gname][3] = '\t'.join(isoform_mark_ls + ['1'] * (num_isforms - len(isoform_mark_ls))) for isoform_idx in range(num_isforms): # Add 0 for normal isforms in fusion-region indices isoform_ls = fusion_MLE_input_dict[fusion_gname][7 + isoform_idx].split() if (len(isoform_ls) < num_regions): isoform_ls += ['0'] * (num_regions - len(isoform_ls)) fusion_MLE_input_dict[fusion_gname][7 + isoform_idx] = '\t'.join(isoform_ls) # Add 0 readcount for fusion regions read_count_ls = fusion_MLE_input_dict[fusion_gname][-1].strip().split() fusion_MLE_input_dict[fusion_gname][-1] = '\t'.join(read_count_ls + ['0'] * (num_regions - len(read_count_ls))) line_ls[1] = str(num_isforms) fusion_MLE_input_dict[fusion_gname][0] = '\t'.join(line_ls + [str(len(read_count_ls))]) #Inlude the start point for fusion regions return fusion_MLE_input_dict ### ########### def add_fusion_isoforms(fusion_MLE_input_dict, fusion_gnames_map, fusion_isofroms_pair_ls, isoforms_readnames_filename): isoforms_readnames_file = open(isoforms_readnames_filename, 'r') fusion_isoforms_map = dict() for line in isoforms_readnames_file: fields = line.strip().split() if (fusion_isoforms_map.has_key(fields[1])): fusion_isoforms_map[fields[1]].append(fields[0]) else: fusion_isoforms_map[fields[1]] = [fields[0]] isoforms_readnames_file.close() processed_fusion_isoforms = [] for fusion_isofroms_pair in fusion_isofroms_pair_ls: gname = [] gname_1 = fusion_isofroms_pair[0][3] if (fusion_gnames_map.has_key(gname_1)): fusion_gene_name_1 = fusion_gnames_map[gname_1] gname.append(gname_1) else: fusion_gene_name_1 = '' fusion_gene_name_2 = '' if (len(fusion_isofroms_pair) > 1): gname_2 = fusion_isofroms_pair[1][3] if (fusion_gnames_map.has_key(gname_2)): fusion_gene_name_2 = fusion_gnames_map[gname_2] gname.append(gname_2) if ((fusion_gene_name_1 == fusion_gene_name_2) and (fusion_gene_name_1 != '')): fusion_gene_name = fusion_gene_name_1 read_idx_ls = [0, 1] else: continue gene_names_ls = (fusion_MLE_input_dict[fusion_gene_name][0].split())[0].split('/') isoforms_names_ls = fusion_MLE_input_dict[fusion_gene_name][1].split() point_names_ls = fusion_MLE_input_dict[fusion_gene_name][4].split() points_ls = [int(i) for i in fusion_MLE_input_dict[fusion_gene_name][5].split()] gene_regions_ls = fusion_MLE_input_dict[fusion_gene_name][6].split() num_gene_points = len(points_ls) num_gene_regions = len(gene_regions_ls) gene_point_name_mapping = dict() for idx in range(num_gene_points): gene_point_name_mapping[point_names_ls[idx]] = points_ls[idx] num_isoforms_ls = ((fusion_MLE_input_dict[fusion_gene_name][0].split())[1]).split(',') num_isoforms_ls = [int(i) for i in num_isoforms_ls] num_isoforms = sum(num_isoforms_ls) split_ls = fusion_MLE_input_dict[fusion_gene_name][0].split() if (len(split_ls) >= 4): start_points_indices = [int(i) for i in ((split_ls)[3]).split(',')] else: # This not realy merged gene start_points_indices = [0, num_gene_regions] fusion_isoforms_indices = [[], []] for read_idx in read_idx_ls: gname_idx = gene_names_ls.index(gname[read_idx]) readname = fusion_isofroms_pair[read_idx][0] #start_isoform_idx = sum(num_isoforms_ls[:gname_idx]) #end_isoform_idx = sum(num_isoforms_ls[:(gname_idx+1)]) if (fusion_isoforms_map.has_key(readname)): fusion_isoforms_indices[read_idx] = [isoforms_names_ls.index(iso_name) for iso_name in fusion_isoforms_map[readname]] else: fusion_isoforms_indices[read_idx] = [] num_fusion_isoforms = 0 isoform_names_ls = fusion_MLE_input_dict[fusion_gene_name][1].split() isoform_len_ls = fusion_MLE_input_dict[fusion_gene_name][3].split() for isoform_idx_1 in fusion_isoforms_indices[0]: for isoform_idx_2 in fusion_isoforms_indices[1]: fusion_isoform_name = isoform_names_ls[isoform_idx_2][:-2] + '/' + isoform_names_ls[isoform_idx_1][:-2] # Remove .f from end if (fusion_isoform_name in processed_fusion_isoforms): # Check both order continue fusion_isoform_name = isoform_names_ls[isoform_idx_1][:-2] + '/' + isoform_names_ls[isoform_idx_2][:-2] # Remove .f from end if (fusion_isoform_name in processed_fusion_isoforms): continue processed_fusion_isoforms.append(fusion_isoform_name) fusion_isoform_ls = [0] * num_gene_regions isoform_1 = [int(i) for i in fusion_MLE_input_dict[fusion_gene_name][7 + isoform_idx_1].split()] isoform_2 = [int(i) for i in fusion_MLE_input_dict[fusion_gene_name][7 + isoform_idx_2].split()] for i in range(len(isoform_1)): fusion_isoform_ls[i] = max(isoform_1[i], isoform_2[i]) for region in fusion_isofroms_pair[2]: region_idx = gene_regions_ls.index(region) fusion_isoform_ls[region_idx] = 1 fusion_isoform_line = '\t'.join([str(i) for i in fusion_isoform_ls]) fusion_MLE_input_dict[fusion_gene_name].insert(7 + num_isoforms + num_fusion_isoforms, fusion_isoform_line) # Add new isoform name isoform_names_ls.append(fusion_isoform_name) isoform_len_ls.append(str(int(isoform_len_ls[isoform_idx_1]) + int(isoform_len_ls[isoform_idx_2]))) num_fusion_isoforms += 1 fusion_MLE_input_dict[fusion_gene_name][1] = '\t'.join(isoform_names_ls) fusion_MLE_input_dict[fusion_gene_name][3] = '\t'.join(isoform_len_ls) # Update number of isoforms item line_ls = fusion_MLE_input_dict[fusion_gene_name][0].split() line_ls[1] += ','+str(num_fusion_isoforms) fusion_MLE_input_dict[fusion_gene_name][0] = '\t'.join(line_ls) fusion_MLE_input_dict = finalize_fusion_genes(fusion_MLE_input_dict) return fusion_MLE_input_dict ### ######## def parse_sam_file(sam_filename, valid_pseudorefnames): print valid_pseudorefnames sam_filenames_dict = {} # skip ref_000 ref_id = 1 for ref_id in valid_pseudorefnames: sam_filenames_dict[ref_id] = open(sam_filename + '.' + str(ref_id), 'w') sam_file = open(sam_filename, 'r') for line in sam_file: if (line[0] == '@'): continue line_ls = line.split('\t') cigar_field = line_ls[5] if (len(set(cigar_field) - valid_cigar) > 0): continue ref_id = int(line_ls[2][4:]) # skip ref_ if (ref_id in valid_pseudorefnames): sam_filenames_dict[ref_id].write(line) sam_file.close() for ref_id in valid_pseudorefnames: sam_filenames_dict[ref_id].close() return sam_filenames_dict ### ######### def parse_cigar(line_ls): cigar_field = line_ls[5] cigar_list = re.split(r'(M|N|I|D)', cigar_field) # Note: this code is copied from parseSAM script! read_len_list = [] seg_len = 0 read_len = 0 M = 1 for idx in range(len(cigar_list)/2): if (cigar_list[2 * idx + 1] == 'M'): if (M == 0): # Mode is changed read_len_list.append(seg_len) seg_len = 0 seg_len += int(cigar_list[2 * idx]) read_len += int(cigar_list[2 * idx]) M = 1 elif (cigar_list[2 * idx + 1] == 'N'): if (M == 1): # Mode is changed read_len_list.append(seg_len) seg_len = 0 seg_len += int(cigar_list[2 * idx]) M = 0 elif (cigar_list[2 * idx + 1] == 'D'): # Deletion from reference if (M == 0): # Mode is changed read_len_list.append(seg_len) seg_len = 0 seg_len += int(cigar_list[2 * idx]) elif (cigar_list[2 * idx + 1] == 'I'): # Insertion in reference if (M == 0): # Mode is changed read_len_list.append(seg_len) seg_len = 0 read_len += int(cigar_list[2 * idx]) read_len_list.append(seg_len) if (abs(read_len - READ_LEN) > read_len_margin): read_len_list = [] if ((read_len_list[0] < READ_JUNC_MIN_MAP_LEN) or (read_len_list[-1] < READ_JUNC_MIN_MAP_LEN)): read_len_list = [] return read_len_list ### ######### def add_fusion_reads(fusion_MLE_input_dict, fusion_isofroms_pair_ls, fusion_gnames_map, pseudo_ref_filename, sam_filename, compreadname2readname_mapping): num_aligned_fusion_reads = 0 # This would be added to header line of MLE_input.txt file pseudo_refname_dict = {} # ref_000 does not exits readid_2_refname_dict = {} pseudo_ref_file = open(pseudo_ref_filename, 'r') ref_id = 1 while (True): line = pseudo_ref_file.readline().strip() if not line: break pseudo_ref_file.readline() pseudo_refname_dict[line[1:]] = ref_id ref_id += 1 pseudo_ref_file.close() readid_2_refname_dict = {} pseudo_ref_file = open(pseudo_ref_filename + '.info', 'r') for line in pseudo_ref_file: fields = line.strip().split() readid_2_refname_dict[fields[0]] = fields[1:] pseudo_ref_file.close() valid_refnames = set() valid_pseudorefnames = set() for fusion_isofroms_pair in fusion_isofroms_pair_ls: if (len(fusion_isofroms_pair) < 2): continue # Not valid fusion gene # Note: because of removing redundancy, refnames might not match. That is the reason we check original rednames origin_readnames = compreadname2readname_mapping[fusion_isofroms_pair[0][0]][fusion_isofroms_pair[1][0]] refname = set() for origin_readid in origin_readnames: refname.add(readid_2_refname_dict[origin_readid][0]) if (len(refname) != 1): print "Err: Unexpected to have different refnames for fusion gene segments (expression level result could be invalid)" print "\t" + str(fusion_isofroms_pair) print "\t" + str(refname) else: gname_1 = fusion_isofroms_pair[0][3] if (not fusion_gnames_map.has_key(gname_1)): continue valid_refnames.add(list(refname)[0]) valid_pseudorefnames.add(pseudo_refname_dict[list(refname)[0]]) sam_filenames_dict = parse_sam_file(sam_filename, valid_pseudorefnames) # fusion_isofroms_pair s could refer so same processed pair of genes, need to skip those processed_fusion_paires = [] for fusion_isofroms_pair in fusion_isofroms_pair_ls: #print fusion_isofroms_pair if (len(fusion_isofroms_pair) < 2): continue # Not valid fusion gene [readname_1, fusion_1_pos] = re.split(r"\+|\-", (fusion_isofroms_pair[0][0].split("|"))[1]) [readname_2, fusion_2_pos] = re.split(r"\+|\-", (fusion_isofroms_pair[1][0].split("|"))[1]) gname_1 = fusion_isofroms_pair[0][3] gname_2 = fusion_isofroms_pair[1][3] if ((gname_1 + '/' + gname_2 in processed_fusion_paires) or (gname_2 + '/' + gname_1 in processed_fusion_paires)): pass else: processed_fusion_paires.append(gname_1 + '/' + gname_2) if (not fusion_gnames_map.has_key(gname_1)): continue if (not fusion_gnames_map.has_key(gname_2)): continue fusion_gene_name = fusion_gnames_map[gname_1] if (not fusion_MLE_input_dict.has_key(fusion_gene_name)): continue # Extract gene information gene_header_ls = fusion_MLE_input_dict[fusion_gene_name][0].split() gene_names_ls = gene_header_ls[0].split('/') chr_ls = gene_header_ls[2].split(',') point_names_ls = fusion_MLE_input_dict[fusion_gene_name][4].split() points_ls = [int(i) for i in fusion_MLE_input_dict[fusion_gene_name][5].split()] points_start_ls = [int(i) for i in gene_header_ls[3].split(',')] gene_regions_ls = fusion_MLE_input_dict[fusion_gene_name][6].split() regions_read_count_ls = fusion_MLE_input_dict[fusion_gene_name][-1].split() gname_1_idx = gene_names_ls.index(gname_1) gname_2_idx = gene_names_ls.index(gname_2) #Initialize the dict regions_count_dict = dict() for region_idx in range(int(gene_header_ls[4]), len(regions_read_count_ls)): regions_count_dict[gene_regions_ls[region_idx]] = 0 #[LEFT, RIGHT] segment orig_id = list(compreadname2readname_mapping[fusion_isofroms_pair[0][0]][fusion_isofroms_pair[1][0]])[0] # Get one of them refname = readid_2_refname_dict[orig_id][0] #print pseudo_refname_dict[refname] if (pseudo_refname_dict[refname] not in valid_pseudorefnames): continue #if (pseudo_refname_dict[refname] != 10): # """""""""DEBUGGING""""""""" # continue #print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" #print fusion_isofroms_pair print fusion_isofroms_pair #print pseudo_refname_dict[refname] ref_name_ls = [refame_spl.split('_') for refame_spl in refname.split('/')] pseudo_ref_genome_points = [[int(ref_name_ls[0][1]), int(ref_name_ls[0][2])], [int(ref_name_ls[1][1]), int(ref_name_ls[1][2])]] pseudo_ref_offset = [0, pseudo_ref_genome_points[0][1] - pseudo_ref_genome_points[0][0]] pseudo_ref_dir = [ref_name_ls[0][3], ref_name_ls[1][3]] # Need to detect first segment refers to which gene if ((ref_name_ls[0][0] == chr_ls[gname_1_idx]) and (int(fusion_1_pos) > pseudo_ref_genome_points[0][0]) and (int(fusion_1_pos) < pseudo_ref_genome_points[0][1])): gname_idx_ls = [gname_1_idx, gname_2_idx] fusion_idx_ls = [int(fusion_1_pos), int(fusion_2_pos)] else: gname_idx_ls = [gname_2_idx, gname_1_idx] fusion_idx_ls = [int(fusion_2_pos), int(fusion_1_pos)] sam_file = open(sam_filename + '.' + str(pseudo_refname_dict[refname]),'r') for read_line in sam_file: read_line_ls = read_line.split() #if (read_line_ls[0] != "SRR1107833.2819532"): # """""""""DEBUGGING""""""""" # continue #print read_line read_start_pos = int(read_line_ls[3]) read_len_ls = parse_cigar(read_line_ls) if (len(read_len_ls) == 0) : continue region_str_ls = [[], []] read_len_idx = 0 read_genome_pos = read_start_pos read_genome_pos_offset = 0 # offset for second segment valid_read = True for seg_idx in [0, 1]: #print region_str_ls if (seg_idx == 1): if (read_len_idx > len(read_len_ls)): valid_read = False break #print read_len_idx #print read_len_ls #print read_start_pos + sum(read_len_ls[:read_len_idx]) #print pseudo_ref_offset[1] # For second segment we should have proceeded to second part of reference seq if ((read_start_pos + sum(read_len_ls[:read_len_idx])) < pseudo_ref_offset[1]): valid_read = False break read_genome_pos = read_start_pos + sum(read_len_ls[:read_len_idx]) - pseudo_ref_offset[1] if (valid_read == False): break if (pseudo_ref_dir[seg_idx] == "+"): read_genome_pos += pseudo_ref_genome_points[seg_idx][0] point_idx_ls = range(points_start_ls[gname_idx_ls[seg_idx]], points_start_ls[gname_idx_ls[seg_idx]+1]) # List of point indices for this gene # Note: the resulter region might not be valid which in case it wont be mapped to any gene region for point_idx in point_idx_ls: #print points_ls[point_idx], read_genome_pos if (points_ls[point_idx] > pseudo_ref_genome_points[seg_idx][1]): break if (points_ls[point_idx] < read_genome_pos): continue elif (points_ls[point_idx] == read_genome_pos): region_str_ls[seg_idx].append(point_names_ls[point_idx]) else: if ((read_genome_pos + read_len_ls[read_len_idx] - 1) > points_ls[point_idx]): region_str_ls[seg_idx].append(point_names_ls[point_idx]) elif ((read_genome_pos + read_len_ls[read_len_idx] - 1) == points_ls[point_idx]): region_str_ls[seg_idx].append(point_names_ls[point_idx]) read_genome_pos += read_len_ls[read_len_idx] - 1 #do not include gap point read_len_idx += 2 if (read_len_idx > len(read_len_ls)): break # Add previous gap read_genome_pos += read_len_ls[read_len_idx - 1] + 1 if (seg_idx == 0): if (read_genome_pos > fusion_idx_ls[0]): break else: if (seg_idx == 1): # Last block partialy extened within exon block if ((read_len_idx + 1) == len(read_len_ls)): if ((int(point_names_ls[point_idx][1:]) % 2) == 1): break elif ((point_idx > points_start_ls[gname_idx_ls[seg_idx]]) and ((points_ls[point_idx] - points_ls[point_idx-1]) == 1)): break else: valid_read = False break else: valid_read = False break else: read_genome_pos = pseudo_ref_genome_points[seg_idx][1] + 1 - read_genome_pos point_idx_ls = list(reversed(range(points_start_ls[gname_idx_ls[seg_idx]], points_start_ls[gname_idx_ls[seg_idx]+1]))) #print point_idx_ls for point_idx in point_idx_ls: #print points_ls[point_idx], read_genome_pos if (points_ls[point_idx] < pseudo_ref_genome_points[seg_idx][0]): break if (points_ls[point_idx] > read_genome_pos): continue elif (points_ls[point_idx] == read_genome_pos): region_str_ls[seg_idx].append(point_names_ls[point_idx]) else: if ((read_genome_pos - (read_len_ls[read_len_idx] - 1)) < points_ls[point_idx]): region_str_ls[seg_idx].append(point_names_ls[point_idx]) elif ((read_genome_pos - (read_len_ls[read_len_idx] - 1)) == points_ls[point_idx]): region_str_ls[seg_idx].append(point_names_ls[point_idx]) read_genome_pos -= read_len_ls[read_len_idx] - 1 read_len_idx += 2 if (read_len_idx > len(read_len_ls)): break read_genome_pos -= read_len_ls[read_len_idx - 1] + 1 # Compensate for above -1 if (seg_idx == 0): if (read_genome_pos < fusion_idx_ls[0]): break else: if (seg_idx == 1): # Last seg partialy overlap with exon if ((read_len_idx + 1) == len(read_len_ls)): if ((int(point_names_ls[point_idx][1:]) % 2) == 0): break elif (((point_idx + 1) < points_start_ls[gname_idx_ls[seg_idx] + 1]) and ((points_ls[point_idx+1] - points_ls[point_idx]) == 1)): break else: valid_read = False break valid_read = False break ##print valid_read if (valid_read == False): continue region_str_ls = region_str_ls[0] + region_str_ls[1] if (gname_idx_ls[0] < gname_idx_ls[1]): region_str = '-'.join(region_str_ls) else: region_str = '-'.join(list(reversed(region_str_ls))) if (regions_count_dict.has_key(region_str)): regions_count_dict[region_str] += 1 #Update the read-count #print regions_count_dict for region_idx in range(int(gene_header_ls[4]), len(regions_read_count_ls)): if (int(regions_read_count_ls[region_idx]) == 0): # To avoid replicates, it should be parse only once regions_read_count_ls[region_idx] = regions_count_dict[gene_regions_ls[region_idx]] num_aligned_fusion_reads += regions_count_dict[gene_regions_ls[region_idx]] fusion_MLE_input_dict[fusion_gene_name][-1] = '\t'.join([str(i) for i in regions_read_count_ls]) print regions_count_dict return [fusion_MLE_input_dict, num_aligned_fusion_reads] def print_MLE_input_file(fusion_MLE_input_dict, fusion_gnames_map, num_aligned_fusion_reads, input_filename, output_filename): input_file = open(input_filename, 'r') output_file = open(output_filename, 'w') output_file_ = open(output_filename+'_', 'w') # Keep a seperate copy of fusion isoforms fusion_gene_names_ls = fusion_MLE_input_dict.keys() line_index = 0; num_aligned_reads = int(input_file.readline()) + num_aligned_fusion_reads output_file.write(str(num_aligned_reads) + '\n') wr_flag = True print fusion_gene_names_ls for line in input_file: fields = line.split() if (line_index == 0): gname = fields[0] num_isoforms = int(fields[1]) rname = fields[2] if (fusion_gnames_map.has_key(gname)): fusion_gname = fusion_gnames_map[gname] if (fusion_gname in fusion_gene_names_ls): wr_flag = False line_index += 1 if (wr_flag): output_file.write(line) if (line_index == (9 + num_isoforms)): line_index = 0 wr_flag = True for fusion_gname in fusion_gene_names_ls: for fusion_line in fusion_MLE_input_dict[fusion_gname]: output_file.write(fusion_line.strip() + '\n') output_file_.write(fusion_line.strip() + '\n') input_file.close() output_file.close() output_file_.close() ### Main ########## def main(): fusion_compatible_filename = sys.argv[1] fusion_gpd_filename = sys.argv[2] readmapping_filename = sys.argv[3] isoforms_readnames_filename = sys.argv[4] input_filename = sys.argv[5] sam_filename = sys.argv[6] pseudo_ref_filename = sys.argv[7] output_filename = sys.argv[8] global READ_LEN, READ_JUNC_MIN_MAP_LEN READ_LEN = int(sys.argv[9]) READ_JUNC_MIN_MAP_LEN = int(sys.argv[10]) [fusion_isofroms_pair_ls, MLE_input_dict, compreadname2readname_mapping] = parse_fusion_genenames(fusion_compatible_filename, fusion_gpd_filename, readmapping_filename) MLE_input_dict = get_fusion_genomes(input_filename, MLE_input_dict) #fusion_isofroms_pair_ls = map_id2genome(readmapping_filename, fusion_compatible_filename, # fusion_isofroms_pair_ls, MLE_input_dict) print ">>>fusion_isofroms_pair_ls" for i in fusion_isofroms_pair_ls: print i [fusion_MLE_input_dict, fusion_gnames_map] = merge_fusion_genes(MLE_input_dict, fusion_isofroms_pair_ls) print ">>>fusion_gnames_map" for key in fusion_gnames_map.keys(): print key +": " + fusion_gnames_map[key] fusion_MLE_input_dict = add_fusion_regions(fusion_MLE_input_dict, fusion_gnames_map, fusion_isofroms_pair_ls) fusion_MLE_input_dict = add_fusion_isoforms(fusion_MLE_input_dict, fusion_gnames_map, fusion_isofroms_pair_ls, isoforms_readnames_filename) [fusion_MLE_input_dict, num_aligned_fusion_reads] = add_fusion_reads(fusion_MLE_input_dict, fusion_isofroms_pair_ls, fusion_gnames_map, pseudo_ref_filename, sam_filename, compreadname2readname_mapping) print_MLE_input_file(fusion_MLE_input_dict, fusion_gnames_map, num_aligned_fusion_reads, input_filename, output_filename) """ for i in compreadname2readname_mapping.keys(): for j in compreadname2readname_mapping[i].keys(): print i + " " + j print compreadname2readname_mapping[i][j] """ """ print ">>>Original genes" for i in MLE_input_dict.keys(): for j in MLE_input_dict[i]: print j print "-----" print ">>>Fusion genes" for i in fusion_MLE_input_dict.keys(): for j in fusion_MLE_input_dict[i]: print j print "-----" """ if __name__ == '__main__': main()
apache-2.0
PyMamba/mamba-storm
storm/variables.py
1
27457
# # Copyright (c) 2006, 2007 Canonical # # Written by Gustavo Niemeyer <gustavo@niemeyer.net> # # This file is part of Storm Object Relational Mapper. # # Storm is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of # the License, or (at your option) any later version. # # Storm is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from datetime import datetime, date, time, timedelta from decimal import Decimal import cPickle as pickle import locale import re try: import uuid except ImportError: uuid = None from storm.compat import json from storm.exceptions import NoneError from storm import Undef, has_cextensions __all__ = [ "VariableFactory", "Variable", "LazyValue", "BoolVariable", "IntVariable", "FloatVariable", "DecimalVariable", "RawStrVariable", "UnicodeVariable", "DateTimeVariable", "DateVariable", "TimeVariable", "TimeDeltaVariable", "EnumVariable", "UUIDVariable", "PickleVariable", "JSONVariable", "ListVariable", ] class LazyValue(object): """Marker to be used as a base class on lazily evaluated values.""" __slots__ = () def raise_none_error(column): if not column: raise NoneError("None isn't acceptable as a value") else: from storm.expr import compile, CompileError name = column.name if column.table is not Undef: try: table = compile(column.table) name = "%s.%s" % (table, name) except CompileError: pass raise NoneError("None isn't acceptable as a value for %s" % name) def VariableFactory(cls, **old_kwargs): """Build cls with kwargs of constructor updated by kwargs of call. This is really an implementation of partial/curry functions, and is replaced by 'partial' when 2.5+ is in use. """ def variable_factory(**new_kwargs): kwargs = old_kwargs.copy() kwargs.update(new_kwargs) return cls(**kwargs) return variable_factory try: from functools import partial as VariableFactory except ImportError: pass class Variable(object): """Basic representation of a database value in Python. @type column: L{storm.expr.Column} @ivar column: The column this variable represents. @type event: L{storm.event.EventSystem} @ivar event: The event system on which to broadcast events. If None, no events will be emitted. """ _value = Undef _lazy_value = Undef _checkpoint_state = Undef _allow_none = True _validator = None _validator_object_factory = None _validator_attribute = None column = None event = None def __init__(self, value=Undef, value_factory=Undef, from_db=False, allow_none=True, column=None, event=None, validator=None, validator_object_factory=None, validator_attribute=None): """ @param value: The initial value of this variable. The default behavior is for the value to stay undefined until it is set with L{set}. @param value_factory: If specified, this will immediately be called to get the initial value. @param from_db: A boolean value indicating where the initial value comes from, if C{value} or C{value_factory} are specified. @param allow_none: A boolean indicating whether None should be allowed to be set as the value of this variable. @param validator: Validation function called whenever trying to set the variable to a non-db value. The function should look like validator(object, attr, value), where the first and second arguments are the result of validator_object_factory() (or None, if this parameter isn't provided) and the value of validator_attribute, respectively. When called, the function should raise an error if the value is unacceptable, or return the value to be used in place of the original value otherwise. @type column: L{storm.expr.Column} @param column: The column that this variable represents. It's used for reporting better error messages. @type event: L{EventSystem} @param event: The event system to broadcast messages with. If not specified, then no events will be broadcast. """ if not allow_none: self._allow_none = False if value is not Undef: self.set(value, from_db) elif value_factory is not Undef: self.set(value_factory(), from_db) if validator is not None: self._validator = validator self._validator_object_factory = validator_object_factory self._validator_attribute = validator_attribute self.column = column self.event = event def get_lazy(self, default=None): """Get the current L{LazyValue} without resolving its value. @param default: If no L{LazyValue} was previously specified, return this value. Defaults to None. """ if self._lazy_value is Undef: return default return self._lazy_value def get(self, default=None, to_db=False): """Get the value, resolving it from a L{LazyValue} if necessary. If the current value is an instance of L{LazyValue}, then the C{resolve-lazy-value} event will be emitted, to give third parties the chance to resolve the lazy value to a real value. @param default: Returned if no value has been set. @param to_db: A boolean flag indicating whether this value is destined for the database. """ if self._lazy_value is not Undef and self.event is not None: self.event.emit("resolve-lazy-value", self, self._lazy_value) value = self._value if value is Undef: return default if value is None: return None return self.parse_get(value, to_db) def set(self, value, from_db=False): """Set a new value. Generally this will be called when an attribute was set in Python, or data is being loaded from the database. If the value is different from the previous value (or it is a L{LazyValue}), then the C{changed} event will be emitted. @param value: The value to set. If this is an instance of L{LazyValue}, then later calls to L{get} will try to resolve the value. @param from_db: A boolean indicating whether this value has come from the database. """ # FASTPATH This method is part of the fast path. Be careful when # changing it (try to profile any changes). if isinstance(value, LazyValue): self._lazy_value = value self._checkpoint_state = new_value = Undef else: if not from_db and self._validator is not None: # We use a factory rather than the object itself to prevent # the cycle object => obj_info => variable => object value = self._validator(self._validator_object_factory and self._validator_object_factory(), self._validator_attribute, value) self._lazy_value = Undef if value is None: if self._allow_none is False: raise_none_error(self.column) new_value = None else: new_value = self.parse_set(value, from_db) if from_db: # Prepare it for being used by the hook below. value = self.parse_get(new_value, False) old_value = self._value self._value = new_value if (self.event is not None and (self._lazy_value is not Undef or new_value != old_value)): if old_value is not None and old_value is not Undef: old_value = self.parse_get(old_value, False) self.event.emit("changed", self, old_value, value, from_db) def delete(self): """Delete the internal value. If there was a value set, then emit the C{changed} event. """ old_value = self._value if old_value is not Undef: self._value = Undef if self.event is not None: if old_value is not None and old_value is not Undef: old_value = self.parse_get(old_value, False) self.event.emit("changed", self, old_value, Undef, False) def is_defined(self): """Check whether there is currently a value. @return: boolean indicating whether there is currently a value for this variable. Note that if a L{LazyValue} was previously set, this returns False; it only returns True if there is currently a real value set. """ return self._value is not Undef def has_changed(self): """Check whether the value has changed. @return: boolean indicating whether the value has changed since the last call to L{checkpoint}. """ return (self._lazy_value is not Undef or self.get_state() != self._checkpoint_state) def get_state(self): """Get the internal state of this object. @return: A value which can later be passed to L{set_state}. """ return (self._lazy_value, self._value) def set_state(self, state): """Set the internal state of this object. @param state: A result from a previous call to L{get_state}. The internal state of this variable will be set to the state of the variable which get_state was called on. """ self._lazy_value, self._value = state def checkpoint(self): """"Checkpoint" the internal state. See L{has_changed}. """ self._checkpoint_state = self.get_state() def copy(self): """Make a new copy of this Variable with the same internal state.""" variable = self.__class__.__new__(self.__class__) variable.set_state(self.get_state()) return variable def parse_get(self, value, to_db): """Convert the internal value to an external value. Get a representation of this value either for Python or for the database. This method is only intended to be overridden in subclasses, not called from external code. @param value: The value to be converted. @param to_db: Whether or not this value is destined for the database. """ return value def parse_set(self, value, from_db): """Convert an external value to an internal value. A value is being set either from Python code or from the database. Parse it into its internal representation. This method is only intended to be overridden in subclasses, not called from external code. @param value: The value, either from Python code setting an attribute or from a column in a database. @param from_db: A boolean flag indicating whether this value is from the database. """ return value if has_cextensions: from storm.cextensions import Variable class BoolVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if not isinstance(value, (int, long, float, Decimal)): raise TypeError("Expected bool, found %r: %r" % (type(value), value)) return bool(value) class IntVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if not isinstance(value, (int, long, float, Decimal)): raise TypeError("Expected int, found %r: %r" % (type(value), value)) return int(value) class FloatVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if not isinstance(value, (int, long, float, Decimal)): raise TypeError("Expected float, found %r: %r" % (type(value), value)) return float(value) class DecimalVariable(Variable): __slots__ = () @staticmethod def parse_set(value, from_db): if (from_db and isinstance(value, basestring) or isinstance(value, (int, long))): value = Decimal(value) elif not isinstance(value, Decimal): raise TypeError("Expected Decimal, found %r: %r" % (type(value), value)) return value @staticmethod def parse_get(value, to_db): if to_db: return unicode(value) return value class RawStrVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if isinstance(value, buffer): value = str(value) elif not isinstance(value, str): raise TypeError("Expected str, found %r: %r" % (type(value), value)) return value class UnicodeVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if not isinstance(value, unicode): raise TypeError("Expected unicode, found %r: %r" % (type(value), value)) return value class DateTimeVariable(Variable): __slots__ = ("_tzinfo",) def __init__(self, *args, **kwargs): self._tzinfo = kwargs.pop("tzinfo", None) super(DateTimeVariable, self).__init__(*args, **kwargs) def parse_set(self, value, from_db): if from_db: if isinstance(value, datetime): pass elif isinstance(value, (str, unicode)): value = _parse_datetime(value) else: raise TypeError("Expected datetime, found %s" % repr(value)) if self._tzinfo is not None: if value.tzinfo is None: value = value.replace(tzinfo=self._tzinfo) else: value = value.astimezone(self._tzinfo) else: if type(value) in (int, long, float): value = datetime.utcfromtimestamp(value) elif isinstance(value, basestring): value = _parse_localized_datetime(value) elif not isinstance(value, datetime): raise TypeError("Expected datetime, found %s" % repr(value)) if self._tzinfo is not None: value = value.astimezone(self._tzinfo) return value class DateVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if from_db: if value is None: return None if isinstance(value, datetime): return value.date() if isinstance(value, date): return value if not isinstance(value, (str, unicode)): raise TypeError("Expected date, found %s" % repr(value)) return date(*_parse_date(value)) else: if isinstance(value, datetime): value = value.date() elif isinstance(value, (str, unicode)): value = date(*_parse_localized_date(value)) elif not isinstance(value, date): raise TypeError("Expected date, found %s" % repr(value)) return value class TimeVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if from_db: # XXX Can None ever get here, considering that set() checks for it? if value is None: return None if isinstance(value, time): return value if not isinstance(value, (str, unicode)): raise TypeError("Expected time, found %s" % repr(value)) if " " in value: date_str, value = value.split(" ") return time(*_parse_time(value)) else: if isinstance(value, datetime): return value.time() if not isinstance(value, time): raise TypeError("Expected time, found %s" % repr(value)) return value class TimeDeltaVariable(Variable): __slots__ = () def parse_set(self, value, from_db): if from_db: # XXX Can None ever get here, considering that set() checks for it? if value is None: return None if isinstance(value, timedelta): return value if not isinstance(value, (str, unicode)): raise TypeError("Expected timedelta, found %s" % repr(value)) return _parse_interval(value) else: if not isinstance(value, timedelta): raise TypeError("Expected timedelta, found %s" % repr(value)) return value class UUIDVariable(Variable): __slots__ = () def parse_set(self, value, from_db): assert uuid is not None, "The uuid module was not found." if from_db and isinstance(value, basestring): value = uuid.UUID(value) elif not isinstance(value, uuid.UUID): raise TypeError("Expected UUID, found %r: %r" % (type(value), value)) return value def parse_get(self, value, to_db): if to_db: return unicode(value) return value class EnumVariable(Variable): __slots__ = ("_get_map", "_set_map") def __init__(self, get_map, set_map, *args, **kwargs): self._get_map = get_map self._set_map = set_map Variable.__init__(self, *args, **kwargs) def parse_set(self, value, from_db): if from_db: return value try: return self._set_map[value] except KeyError: raise ValueError("Invalid enum value: %s" % repr(value)) def parse_get(self, value, to_db): if to_db: return value try: return self._get_map[value] except KeyError: raise ValueError("Invalid enum value: %s" % repr(value)) class MutableValueVariable(Variable): """ A variable which contains a reference to mutable content. For this kind of variable, we can't simply detect when a modification has been made, so we have to synchronize the content of the variable when the store is flushing current objects, to check if the state has changed. """ __slots__ = ("_event_system") def __init__(self, *args, **kwargs): self._event_system = None Variable.__init__(self, *args, **kwargs) if self.event is not None: self.event.hook("start-tracking-changes", self._start_tracking) self.event.hook("object-deleted", self._detect_changes_and_stop) def _start_tracking(self, obj_info, event_system): self._event_system = event_system self.event.hook("stop-tracking-changes", self._stop_tracking) def _stop_tracking(self, obj_info, event_system): event_system.unhook("flush", self._detect_changes) self._event_system = None def _detect_changes(self, obj_info): if (self._checkpoint_state is not Undef and self.get_state() != self._checkpoint_state): self.event.emit("changed", self, None, self._value, False) def _detect_changes_and_stop(self, obj_info): self._detect_changes(obj_info) if self._event_system is not None: self._stop_tracking(obj_info, self._event_system) def get(self, default=None, to_db=False): if self._event_system is not None: self._event_system.hook("flush", self._detect_changes) return super(MutableValueVariable, self).get(default, to_db) def set(self, value, from_db=False): if self._event_system is not None: if isinstance(value, LazyValue): self._event_system.unhook("flush", self._detect_changes) else: self._event_system.hook("flush", self._detect_changes) super(MutableValueVariable, self).set(value, from_db) class EncodedValueVariable(MutableValueVariable): __slots__ = () def parse_set(self, value, from_db): if from_db: if isinstance(value, buffer): value = str(value) return self._loads(value) else: return value def parse_get(self, value, to_db): if to_db: return self._dumps(value) else: return value def get_state(self): return (self._lazy_value, self._dumps(self._value)) def set_state(self, state): self._lazy_value = state[0] self._value = self._loads(state[1]) class PickleVariable(EncodedValueVariable): def _loads(self, value): return pickle.loads(value) def _dumps(self, value): return pickle.dumps(value, -1) class JSONVariable(EncodedValueVariable): __slots__ = () def __init__(self, *args, **kwargs): assert json is not None, ( "Neither the json nor the simplejson module was found.") super(JSONVariable, self).__init__(*args, **kwargs) def _loads(self, value): if not isinstance(value, unicode): raise TypeError( "Cannot safely assume encoding of byte string %r." % value) return json.loads(value) def _dumps(self, value): # http://www.ietf.org/rfc/rfc4627.txt states that JSON is text-based # and so we treat it as such here. In other words, this method returns # unicode and never str. dump = json.dumps(value, ensure_ascii=False) if not isinstance(dump, unicode): # json.dumps() does not always return unicode. See # http://code.google.com/p/simplejson/issues/detail?id=40 for one # of many discussions of str/unicode handling in simplejson. dump = dump.decode("utf-8") return dump class ListVariable(MutableValueVariable): __slots__ = ("_item_factory",) def __init__(self, item_factory, *args, **kwargs): self._item_factory = item_factory MutableValueVariable.__init__(self, *args, **kwargs) def parse_set(self, value, from_db): if from_db: item_factory = self._item_factory return [item_factory(value=val, from_db=from_db).get() for val in value] else: return value def parse_get(self, value, to_db): if to_db: item_factory = self._item_factory return [item_factory(value=val, from_db=False) for val in value] else: return value def get_state(self): return (self._lazy_value, pickle.dumps(self._value, -1)) def set_state(self, state): self._lazy_value = state[0] self._value = pickle.loads(state[1]) def _parse_time(time_str): # TODO Add support for timezones. colons = time_str.count(":") if not 1 <= colons <= 2: raise ValueError("Unknown time format: %r" % time_str) if colons == 2: hour, minute, second = time_str.split(":") else: hour, minute = time_str.split(":") second = "0" if "." in second: second, microsecond = second.split(".") second = int(second) microsecond = int(int(microsecond) * 10 ** (6 - len(microsecond))) return int(hour), int(minute), second, microsecond return int(hour), int(minute), int(second), 0 def _parse_date(date_str): """ parse dates as formated by databases (YYYY-MM-DD) """ date_str = date_str.split(" ")[0] # discards time if "-" not in date_str: raise ValueError("Unknown date format: %r" % date_str) year, month, day = date_str.split("-") return int(year), int(month), int(day) def _parse_datetime(datetime_str): """ parse dates as formated by databases (YYYY-MM-DD) """ if " " not in datetime_str: raise ValueError("Unknown date/time format: %r" % datetime_str) date_str, time_str = datetime_str.split(" ") return datetime(*(_parse_date(date_str) + _parse_time(time_str))) def _parse_localized_date(date_str): """ parse date in the locale format """ loc, _ = locale.getlocale() if loc is None: locale.setlocale(locale.LC_ALL, locale.getdefaultlocale()) date_str = date_str.split(" ")[0] # discards time date_fmt = locale.nl_langinfo(locale.D_FMT) dt = datetime.strptime(date_str, date_fmt) return dt.year, dt.month, dt.day def _parse_localized_datetime(datetime_str): """ parse date in the locale format """ if " " not in datetime_str: raise ValueError("Unknown date/time format: %r" % datetime_str) date_str, time_str = datetime_str.split(" ") return datetime(*(_parse_localized_date(date_str) + _parse_time(time_str))) def _parse_interval_table(): table = {} for units, delta in ( ("d day days", timedelta), ("h hour hours", lambda x: timedelta(hours=x)), ("m min minute minutes", lambda x: timedelta(minutes=x)), ("s sec second seconds", lambda x: timedelta(seconds=x)), ("ms millisecond milliseconds", lambda x: timedelta(milliseconds=x)), ("microsecond microseconds", lambda x: timedelta(microseconds=x)) ): for unit in units.split(): table[unit] = delta return table _parse_interval_table = _parse_interval_table() _parse_interval_re = re.compile(r"[\s,]*" r"([-+]?(?:\d\d?:\d\d?(?::\d\d?)?(?:\.\d+)?" r"|\d+(?:\.\d+)?))" r"[\s,]*") def _parse_interval(interval): result = timedelta(0) value = None for token in _parse_interval_re.split(interval): if not token: pass elif ":" in token: if value is not None: result += timedelta(days=value) value = None h, m, s, ms = _parse_time(token) result += timedelta(hours=h, minutes=m, seconds=s, microseconds=ms) elif value is None: try: value = float(token) except ValueError: raise ValueError("Expected an interval value rather than " "%r in interval %r" % (token, interval)) else: unit = _parse_interval_table.get(token) if unit is None: raise ValueError("Unsupported interval unit %r in interval %r" % (token, interval)) result += unit(value) value = None if value is not None: result += timedelta(seconds=value) return result
lgpl-2.1
40223143/2015_0505
static/Brython3.1.1-20150328-091302/Lib/external_import.py
742
2985
import os from browser import doc import urllib.request ## this module is able to download modules that are external to ## localhost/src ## so we could download from any URL class ModuleFinder: def __init__(self, path_entry): print("external_import here..") #print(path_entry) self._module=None if path_entry.startswith('http://'): self.path_entry=path_entry else: raise ImportError() def __str__(self): return '<%s for "%s">' % (self.__class__.__name__, self.path_entry) def find_module(self, fullname, path=None): path = path or self.path_entry #print('looking for "%s" in %s ...' % (fullname, path)) for _ext in ['js', 'pyj', 'py']: _fp,_url,_headers=urllib.request.urlopen(path + '/' + '%s.%s' % (fullname, _ext)) self._module=_fp.read() _fp.close() if self._module is not None: print("module found at %s:%s" % (path, fullname)) return ModuleLoader(path, fullname, self._module) print('module %s not found' % fullname) raise ImportError() return None class ModuleLoader: """Load source for modules""" def __init__(self, filepath, name, module_source): self._filepath=filepath self._name=name self._module_source=module_source def get_source(self): return self._module_source def is_package(self): return '.' in self._name def load_module(self): if self._name in sys.modules: #print('reusing existing module from previous import of "%s"' % fullname) mod = sys.modules[self._name] return mod _src=self.get_source() if self._filepath.endswith('.js'): mod=JSObject(import_js_module(_src, self._filepath, self._name)) elif self._filepath.endswith('.py'): mod=JSObject(import_py_module(_src, self._filepath, self._name)) elif self._filepath.endswith('.pyj'): mod=JSObject(import_pyj_module(_src, self._filepath, self._name)) else: raise ImportError('Invalid Module: %s' % self._filepath) # Set a few properties required by PEP 302 mod.__file__ = self._filepath mod.__name__ = self._name mod.__path__ = os.path.abspath(self._filepath) mod.__loader__ = self mod.__package__ = '.'.join(self._name.split('.')[:-1]) if self.is_package(): print('adding path for package') # Set __path__ for packages # so we can find the sub-modules. mod.__path__ = [ self._filepath ] else: print('imported as regular module') print('creating a new module object for "%s"' % self._name) sys.modules.setdefault(self._name, mod) JSObject(__BRYTHON__.imported)[self._name]=mod return mod
agpl-3.0
facelessuser/sublime-markdown-popups
st3/mdpopups/markdown/extensions/admonition.py
5
3124
""" Admonition extension for Python-Markdown ======================================== Adds rST-style admonitions. Inspired by [rST][] feature with the same name. [rST]: http://docutils.sourceforge.net/docs/ref/rst/directives.html#specific-admonitions # noqa See <https://Python-Markdown.github.io/extensions/admonition> for documentation. Original code Copyright [Tiago Serafim](https://www.tiagoserafim.com/). All changes Copyright The Python Markdown Project License: [BSD](https://opensource.org/licenses/bsd-license.php) """ from . import Extension from ..blockprocessors import BlockProcessor import xml.etree.ElementTree as etree import re class AdmonitionExtension(Extension): """ Admonition extension for Python-Markdown. """ def extendMarkdown(self, md): """ Add Admonition to Markdown instance. """ md.registerExtension(self) md.parser.blockprocessors.register(AdmonitionProcessor(md.parser), 'admonition', 105) class AdmonitionProcessor(BlockProcessor): CLASSNAME = 'admonition' CLASSNAME_TITLE = 'admonition-title' RE = re.compile(r'(?:^|\n)!!! ?([\w\-]+(?: +[\w\-]+)*)(?: +"(.*?)")? *(?:\n|$)') RE_SPACES = re.compile(' +') def test(self, parent, block): sibling = self.lastChild(parent) return self.RE.search(block) or \ (block.startswith(' ' * self.tab_length) and sibling is not None and sibling.get('class', '').find(self.CLASSNAME) != -1) def run(self, parent, blocks): sibling = self.lastChild(parent) block = blocks.pop(0) m = self.RE.search(block) if m: block = block[m.end():] # removes the first line block, theRest = self.detab(block) if m: klass, title = self.get_class_and_title(m) div = etree.SubElement(parent, 'div') div.set('class', '{} {}'.format(self.CLASSNAME, klass)) if title: p = etree.SubElement(div, 'p') p.text = title p.set('class', self.CLASSNAME_TITLE) else: div = sibling self.parser.parseChunk(div, block) if theRest: # This block contained unindented line(s) after the first indented # line. Insert these lines as the first block of the master blocks # list for future processing. blocks.insert(0, theRest) def get_class_and_title(self, match): klass, title = match.group(1).lower(), match.group(2) klass = self.RE_SPACES.sub(' ', klass) if title is None: # no title was provided, use the capitalized classname as title # e.g.: `!!! note` will render # `<p class="admonition-title">Note</p>` title = klass.split(' ', 1)[0].capitalize() elif title == '': # an explicit blank title should not be rendered # e.g.: `!!! warning ""` will *not* render `p` with a title title = None return klass, title def makeExtension(**kwargs): # pragma: no cover return AdmonitionExtension(**kwargs)
mit
cmdunkers/DeeperMind
PythonEnv/lib/python2.7/site-packages/pip/commands/list.py
269
7251
from __future__ import absolute_import import logging from pip._vendor import pkg_resources from pip.basecommand import Command from pip.exceptions import DistributionNotFound from pip.index import FormatControl, fmt_ctl_formats, PackageFinder, Search from pip.req import InstallRequirement from pip.utils import get_installed_distributions, dist_is_editable from pip.wheel import WheelCache from pip.cmdoptions import make_option_group, index_group logger = logging.getLogger(__name__) class ListCommand(Command): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ name = 'list' usage = """ %prog [options]""" summary = 'List installed packages.' def __init__(self, *args, **kw): super(ListCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages (excluding editables)') cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages (excluding editables)') cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) index_opts = make_option_group(index_group, self.parser) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_external=options.allow_external, allow_unverified=options.allow_unverified, allow_all_external=options.allow_all_external, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, process_dependency_links=options.process_dependency_links, session=session, ) def run(self, options, args): if options.outdated: self.run_outdated(options) elif options.uptodate: self.run_uptodate(options) elif options.editable: self.run_editables(options) else: self.run_listing(options) def run_outdated(self, options): for dist, version, typ in self.find_packages_latest_versions(options): if version > dist.parsed_version: logger.info( '%s (Current: %s Latest: %s [%s])', dist.project_name, dist.version, version, typ, ) def find_packages_latest_versions(self, options): index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.info('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] dependency_links = [] for dist in get_installed_distributions(local_only=options.local, user_only=options.user): if dist.has_metadata('dependency_links.txt'): dependency_links.extend( dist.get_metadata_lines('dependency_links.txt'), ) with self._build_session(options) as session: finder = self._build_package_finder(options, index_urls, session) finder.add_dependency_links(dependency_links) installed_packages = get_installed_distributions( local_only=options.local, user_only=options.user, include_editables=False, ) format_control = FormatControl(set(), set()) wheel_cache = WheelCache(options.cache_dir, format_control) for dist in installed_packages: req = InstallRequirement.from_line( dist.key, None, isolated=options.isolated_mode, wheel_cache=wheel_cache ) typ = 'unknown' try: link = finder.find_requirement(req, True) # If link is None, means installed version is most # up-to-date if link is None: continue except DistributionNotFound: continue else: canonical_name = pkg_resources.safe_name(req.name).lower() formats = fmt_ctl_formats(format_control, canonical_name) search = Search( req.name, canonical_name, formats) remote_version = finder._link_package_versions( link, search).version if link.is_wheel: typ = 'wheel' else: typ = 'sdist' yield dist, remote_version, typ def run_listing(self, options): installed_packages = get_installed_distributions( local_only=options.local, user_only=options.user, ) self.output_package_listing(installed_packages) def run_editables(self, options): installed_packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=True, ) self.output_package_listing(installed_packages) def output_package_listing(self, installed_packages): installed_packages = sorted( installed_packages, key=lambda dist: dist.project_name.lower(), ) for dist in installed_packages: if dist_is_editable(dist): line = '%s (%s, %s)' % ( dist.project_name, dist.version, dist.location, ) else: line = '%s (%s)' % (dist.project_name, dist.version) logger.info(line) def run_uptodate(self, options): uptodate = [] for dist, version, typ in self.find_packages_latest_versions(options): if dist.parsed_version == version: uptodate.append(dist) self.output_package_listing(uptodate)
bsd-3-clause
nya282828/nyagarage
node_modules/gulp-pleeease/node_modules/pleeease/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/flock_tool.py
1835
1748
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """These functions are executed via gyp-flock-tool when using the Makefile generator. Used on systems that don't have a built-in flock.""" import fcntl import os import struct import subprocess import sys def main(args): executor = FlockTool() executor.Dispatch(args) class FlockTool(object): """This class emulates the 'flock' command.""" def Dispatch(self, args): """Dispatches a string command to a method.""" if len(args) < 1: raise Exception("Not enough arguments") method = "Exec%s" % self._CommandifyName(args[0]) getattr(self, method)(*args[1:]) def _CommandifyName(self, name_string): """Transforms a tool name like copy-info-plist to CopyInfoPlist""" return name_string.title().replace('-', '') def ExecFlock(self, lockfile, *cmd_list): """Emulates the most basic behavior of Linux's flock(1).""" # Rely on exception handling to report errors. # Note that the stock python on SunOS has a bug # where fcntl.flock(fd, LOCK_EX) always fails # with EBADF, that's why we use this F_SETLK # hack instead. fd = os.open(lockfile, os.O_WRONLY|os.O_NOCTTY|os.O_CREAT, 0666) if sys.platform.startswith('aix'): # Python on AIX is compiled with LARGEFILE support, which changes the # struct size. op = struct.pack('hhIllqq', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0) else: op = struct.pack('hhllhhl', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0) fcntl.fcntl(fd, fcntl.F_SETLK, op) return subprocess.call(cmd_list) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
mit
HyperBaton/ansible
packaging/release/changelogs/changelog.py
28
28455
#!/usr/bin/env python # PYTHON_ARGCOMPLETE_OK """Changelog generator and linter.""" from __future__ import (absolute_import, division, print_function) __metaclass__ = type import argparse import collections import datetime import docutils.utils import json import logging import os import packaging.version import re import rstcheck import subprocess import sys import yaml try: import argcomplete except ImportError: argcomplete = None from ansible import constants as C from ansible.module_utils.six import string_types from ansible.module_utils._text import to_bytes, to_text BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..')) CHANGELOG_DIR = os.path.join(BASE_DIR, 'changelogs') CONFIG_PATH = os.path.join(CHANGELOG_DIR, 'config.yaml') CHANGES_PATH = os.path.join(CHANGELOG_DIR, '.changes.yaml') LOGGER = logging.getLogger('changelog') def main(): """Main program entry point.""" parser = argparse.ArgumentParser(description='Changelog generator and linter.') common = argparse.ArgumentParser(add_help=False) common.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of output') subparsers = parser.add_subparsers(metavar='COMMAND') lint_parser = subparsers.add_parser('lint', parents=[common], help='check changelog fragments for syntax errors') lint_parser.set_defaults(func=command_lint) lint_parser.add_argument('fragments', metavar='FRAGMENT', nargs='*', help='path to fragment to test') release_parser = subparsers.add_parser('release', parents=[common], help='add a new release to the change metadata') release_parser.set_defaults(func=command_release) release_parser.add_argument('--version', help='override release version') release_parser.add_argument('--codename', help='override release codename') release_parser.add_argument('--date', default=str(datetime.date.today()), help='override release date') release_parser.add_argument('--reload-plugins', action='store_true', help='force reload of plugin cache') generate_parser = subparsers.add_parser('generate', parents=[common], help='generate the changelog') generate_parser.set_defaults(func=command_generate) generate_parser.add_argument('--reload-plugins', action='store_true', help='force reload of plugin cache') if argcomplete: argcomplete.autocomplete(parser) formatter = logging.Formatter('%(levelname)s %(message)s') handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) LOGGER.addHandler(handler) LOGGER.setLevel(logging.WARN) args = parser.parse_args() if args.verbose > 2: LOGGER.setLevel(logging.DEBUG) elif args.verbose > 1: LOGGER.setLevel(logging.INFO) elif args.verbose > 0: LOGGER.setLevel(logging.WARN) args.func(args) def command_lint(args): """ :type args: any """ paths = args.fragments # type: list exceptions = [] fragments = load_fragments(paths, exceptions) lint_fragments(fragments, exceptions) def command_release(args): """ :type args: any """ version = args.version # type: str codename = args.codename # type: str date = datetime.datetime.strptime(args.date, "%Y-%m-%d").date() reload_plugins = args.reload_plugins # type: bool if not version or not codename: import ansible.release version = version or ansible.release.__version__ codename = codename or ansible.release.__codename__ changes = load_changes() plugins = load_plugins(version=version, force_reload=reload_plugins) fragments = load_fragments() add_release(changes, plugins, fragments, version, codename, date) generate_changelog(changes, plugins, fragments) def command_generate(args): """ :type args: any """ reload_plugins = args.reload_plugins # type: bool changes = load_changes() plugins = load_plugins(version=changes.latest_version, force_reload=reload_plugins) fragments = load_fragments() generate_changelog(changes, plugins, fragments) def load_changes(): """Load changes metadata. :rtype: ChangesMetadata """ changes = ChangesMetadata(CHANGES_PATH) return changes def load_plugins(version, force_reload): """Load plugins from ansible-doc. :type version: str :type force_reload: bool :rtype: list[PluginDescription] """ plugin_cache_path = os.path.join(CHANGELOG_DIR, '.plugin-cache.yaml') plugins_data = {} if not force_reload and os.path.exists(plugin_cache_path): with open(plugin_cache_path, 'r') as plugin_cache_fd: plugins_data = yaml.safe_load(plugin_cache_fd) if version != plugins_data['version']: LOGGER.info('version %s does not match plugin cache version %s', version, plugins_data['version']) plugins_data = {} if not plugins_data: LOGGER.info('refreshing plugin cache') plugins_data['version'] = version plugins_data['plugins'] = {} for plugin_type in C.DOCUMENTABLE_PLUGINS: output = subprocess.check_output([os.path.join(BASE_DIR, 'bin', 'ansible-doc'), '--json', '--metadata-dump', '-t', plugin_type]) plugins_data['plugins'][plugin_type] = json.loads(to_text(output)) # remove empty namespaces from plugins for section in plugins_data['plugins'].values(): for plugin in section.values(): if plugin['namespace'] is None: del plugin['namespace'] with open(plugin_cache_path, 'w') as plugin_cache_fd: yaml.safe_dump(plugins_data, plugin_cache_fd, default_flow_style=False) plugins = PluginDescription.from_dict(plugins_data['plugins']) return plugins def load_fragments(paths=None, exceptions=None): """ :type paths: list[str] | None :type exceptions: list[tuple[str, Exception]] | None """ if not paths: config = ChangelogConfig(CONFIG_PATH) fragments_dir = os.path.join(CHANGELOG_DIR, config.notes_dir) paths = [os.path.join(fragments_dir, path) for path in os.listdir(fragments_dir)] fragments = [] for path in paths: try: fragments.append(ChangelogFragment.load(path)) except Exception as ex: if exceptions is not None: exceptions.append((path, ex)) else: raise return fragments def lint_fragments(fragments, exceptions): """ :type fragments: list[ChangelogFragment] :type exceptions: list[tuple[str, Exception]] """ config = ChangelogConfig(CONFIG_PATH) linter = ChangelogFragmentLinter(config) errors = [(ex[0], 0, 0, 'yaml parsing error') for ex in exceptions] for fragment in fragments: errors += linter.lint(fragment) messages = sorted(set('%s:%d:%d: %s' % (error[0], error[1], error[2], error[3]) for error in errors)) for message in messages: print(message) def add_release(changes, plugins, fragments, version, codename, date): """Add a release to the change metadata. :type changes: ChangesMetadata :type plugins: list[PluginDescription] :type fragments: list[ChangelogFragment] :type version: str :type codename: str :type date: datetime.date """ # make sure the version parses packaging.version.Version(version) LOGGER.info('release version %s is a %s version', version, 'release' if is_release_version(version) else 'pre-release') # filter out plugins which were not added in this release plugins = list(filter(lambda p: version.startswith('%s.' % p.version_added), plugins)) changes.add_release(version, codename, date) for plugin in plugins: changes.add_plugin(plugin.type, plugin.name, version) for fragment in fragments: changes.add_fragment(fragment.name, version) changes.save() def generate_changelog(changes, plugins, fragments): """Generate the changelog. :type changes: ChangesMetadata :type plugins: list[PluginDescription] :type fragments: list[ChangelogFragment] """ config = ChangelogConfig(CONFIG_PATH) changes.prune_plugins(plugins) changes.prune_fragments(fragments) changes.save() major_minor_version = '.'.join(changes.latest_version.split('.')[:2]) changelog_path = os.path.join(CHANGELOG_DIR, 'CHANGELOG-v%s.rst' % major_minor_version) generator = ChangelogGenerator(config, changes, plugins, fragments) rst = generator.generate() with open(changelog_path, 'wb') as changelog_fd: changelog_fd.write(to_bytes(rst)) class ChangelogFragmentLinter(object): """Linter for ChangelogFragments.""" def __init__(self, config): """ :type config: ChangelogConfig """ self.config = config def lint(self, fragment): """Lint a ChangelogFragment. :type fragment: ChangelogFragment :rtype: list[(str, int, int, str)] """ errors = [] for section, lines in fragment.content.items(): if section == self.config.prelude_name: if not isinstance(lines, string_types): errors.append((fragment.path, 0, 0, 'section "%s" must be type str not %s' % (section, type(lines).__name__))) else: # doesn't account for prelude but only the RM should be adding those if not isinstance(lines, list): errors.append((fragment.path, 0, 0, 'section "%s" must be type list not %s' % (section, type(lines).__name__))) if section not in self.config.sections: errors.append((fragment.path, 0, 0, 'invalid section: %s' % section)) if isinstance(lines, list): for line in lines: if not isinstance(line, string_types): errors.append((fragment.path, 0, 0, 'section "%s" list items must be type str not %s' % (section, type(line).__name__))) continue results = rstcheck.check(line, filename=fragment.path, report_level=docutils.utils.Reporter.WARNING_LEVEL) errors += [(fragment.path, 0, 0, result[1]) for result in results] elif isinstance(lines, string_types): results = rstcheck.check(lines, filename=fragment.path, report_level=docutils.utils.Reporter.WARNING_LEVEL) errors += [(fragment.path, 0, 0, result[1]) for result in results] return errors def is_release_version(version): """Deterine the type of release from the given version. :type version: str :rtype: bool """ config = ChangelogConfig(CONFIG_PATH) tag_format = 'v%s' % version if re.search(config.pre_release_tag_re, tag_format): return False if re.search(config.release_tag_re, tag_format): return True raise Exception('unsupported version format: %s' % version) class PluginDescription(object): """Plugin description.""" def __init__(self, plugin_type, name, namespace, description, version_added): self.type = plugin_type self.name = name self.namespace = namespace self.description = description self.version_added = version_added @staticmethod def from_dict(data): """Return a list of PluginDescription objects from the given data. :type data: dict[str, dict[str, dict[str, any]]] :rtype: list[PluginDescription] """ plugins = [] for plugin_type, plugin_data in data.items(): for plugin_name, plugin_details in plugin_data.items(): plugins.append(PluginDescription( plugin_type=plugin_type, name=plugin_name, namespace=plugin_details.get('namespace'), description=plugin_details['description'], version_added=plugin_details['version_added'], )) return plugins class ChangelogGenerator(object): """Changelog generator.""" def __init__(self, config, changes, plugins, fragments): """ :type config: ChangelogConfig :type changes: ChangesMetadata :type plugins: list[PluginDescription] :type fragments: list[ChangelogFragment] """ self.config = config self.changes = changes self.plugins = {} self.modules = [] for plugin in plugins: if plugin.type == 'module': self.modules.append(plugin) else: if plugin.type not in self.plugins: self.plugins[plugin.type] = [] self.plugins[plugin.type].append(plugin) self.fragments = dict((fragment.name, fragment) for fragment in fragments) def generate(self): """Generate the changelog. :rtype: str """ latest_version = self.changes.latest_version codename = self.changes.releases[latest_version]['codename'] major_minor_version = '.'.join(latest_version.split('.')[:2]) release_entries = collections.OrderedDict() entry_version = latest_version entry_fragment = None for version in sorted(self.changes.releases, reverse=True, key=packaging.version.Version): release = self.changes.releases[version] if is_release_version(version): entry_version = version # next version is a release, it needs its own entry entry_fragment = None elif not is_release_version(entry_version): entry_version = version # current version is a pre-release, next version needs its own entry entry_fragment = None if entry_version not in release_entries: release_entries[entry_version] = dict( fragments=[], modules=[], plugins={}, ) entry_config = release_entries[entry_version] fragment_names = [] # only keep the latest prelude fragment for an entry for fragment_name in release.get('fragments', []): fragment = self.fragments[fragment_name] if self.config.prelude_name in fragment.content: if entry_fragment: LOGGER.info('skipping fragment %s in version %s due to newer fragment %s in version %s', fragment_name, version, entry_fragment, entry_version) continue entry_fragment = fragment_name fragment_names.append(fragment_name) entry_config['fragments'] += fragment_names entry_config['modules'] += release.get('modules', []) for plugin_type, plugin_names in release.get('plugins', {}).items(): if plugin_type not in entry_config['plugins']: entry_config['plugins'][plugin_type] = [] entry_config['plugins'][plugin_type] += plugin_names builder = RstBuilder() builder.set_title('Ansible %s "%s" Release Notes' % (major_minor_version, codename)) builder.add_raw_rst('.. contents:: Topics\n\n') for version, release in release_entries.items(): builder.add_section('v%s' % version) combined_fragments = ChangelogFragment.combine([self.fragments[fragment] for fragment in release['fragments']]) for section_name in self.config.sections: self._add_section(builder, combined_fragments, section_name) self._add_plugins(builder, release['plugins']) self._add_modules(builder, release['modules']) return builder.generate() def _add_section(self, builder, combined_fragments, section_name): if section_name not in combined_fragments: return section_title = self.config.sections[section_name] builder.add_section(section_title, 1) content = combined_fragments[section_name] if isinstance(content, list): for rst in sorted(content): builder.add_raw_rst('- %s' % rst) else: builder.add_raw_rst(content) builder.add_raw_rst('') def _add_plugins(self, builder, plugin_types_and_names): if not plugin_types_and_names: return have_section = False for plugin_type in sorted(self.plugins): plugins = dict((plugin.name, plugin) for plugin in self.plugins[plugin_type] if plugin.name in plugin_types_and_names.get(plugin_type, [])) if not plugins: continue if not have_section: have_section = True builder.add_section('New Plugins', 1) builder.add_section(plugin_type.title(), 2) for plugin_name in sorted(plugins): plugin = plugins[plugin_name] builder.add_raw_rst('- %s - %s' % (plugin.name, plugin.description)) builder.add_raw_rst('') def _add_modules(self, builder, module_names): if not module_names: return modules = dict((module.name, module) for module in self.modules if module.name in module_names) previous_section = None modules_by_namespace = collections.defaultdict(list) for module_name in sorted(modules): module = modules[module_name] modules_by_namespace[module.namespace].append(module.name) for namespace in sorted(modules_by_namespace): parts = namespace.split('.') section = parts.pop(0).replace('_', ' ').title() if not previous_section: builder.add_section('New Modules', 1) if section != previous_section: builder.add_section(section, 2) previous_section = section subsection = '.'.join(parts) if subsection: builder.add_section(subsection, 3) for module_name in modules_by_namespace[namespace]: module = modules[module_name] builder.add_raw_rst('- %s - %s' % (module.name, module.description)) builder.add_raw_rst('') class ChangelogFragment(object): """Changelog fragment loader.""" def __init__(self, content, path): """ :type content: dict[str, list[str]] :type path: str """ self.content = content self.path = path self.name = os.path.basename(path) @staticmethod def load(path): """Load a ChangelogFragment from a file. :type path: str """ with open(path, 'r') as fragment_fd: content = yaml.safe_load(fragment_fd) return ChangelogFragment(content, path) @staticmethod def combine(fragments): """Combine fragments into a new fragment. :type fragments: list[ChangelogFragment] :rtype: dict[str, list[str] | str] """ result = {} for fragment in fragments: for section, content in fragment.content.items(): if isinstance(content, list): if section not in result: result[section] = [] result[section] += content else: result[section] = content return result class ChangelogConfig(object): """Configuration for changelogs.""" def __init__(self, path): """ :type path: str """ with open(path, 'r') as config_fd: self.config = yaml.safe_load(config_fd) self.notes_dir = self.config.get('notesdir', 'fragments') self.prelude_name = self.config.get('prelude_section_name', 'release_summary') self.prelude_title = self.config.get('prelude_section_title', 'Release Summary') self.new_plugins_after_name = self.config.get('new_plugins_after_name', '') self.release_tag_re = self.config.get('release_tag_re', r'((?:[\d.ab]|rc)+)') self.pre_release_tag_re = self.config.get('pre_release_tag_re', r'(?P<pre_release>\.\d+(?:[ab]|rc)+\d*)$') self.sections = collections.OrderedDict([(self.prelude_name, self.prelude_title)]) for section_name, section_title in self.config['sections']: self.sections[section_name] = section_title class RstBuilder(object): """Simple RST builder.""" def __init__(self): self.lines = [] self.section_underlines = '''=-~^.*+:`'"_#''' def set_title(self, title): """Set the title. :type title: str """ self.lines.append(self.section_underlines[0] * len(title)) self.lines.append(title) self.lines.append(self.section_underlines[0] * len(title)) self.lines.append('') def add_section(self, name, depth=0): """Add a section. :type name: str :type depth: int """ self.lines.append(name) self.lines.append(self.section_underlines[depth] * len(name)) self.lines.append('') def add_raw_rst(self, content): """Add a raw RST. :type content: str """ self.lines.append(content) def generate(self): """Generate RST content. :rtype: str """ return '\n'.join(self.lines) class ChangesMetadata(object): """Read, write and manage change metadata.""" def __init__(self, path): self.path = path self.data = self.empty() self.known_fragments = set() self.known_plugins = set() self.load() @staticmethod def empty(): """Empty change metadata.""" return dict( releases=dict( ), ) @property def latest_version(self): """Latest version in the changes. :rtype: str """ return sorted(self.releases, reverse=True, key=packaging.version.Version)[0] @property def releases(self): """Dictionary of releases. :rtype: dict[str, dict[str, any]] """ return self.data['releases'] def load(self): """Load the change metadata from disk.""" if os.path.exists(self.path): with open(self.path, 'r') as meta_fd: self.data = yaml.safe_load(meta_fd) else: self.data = self.empty() for version, config in self.releases.items(): self.known_fragments |= set(config.get('fragments', [])) for plugin_type, plugin_names in config.get('plugins', {}).items(): self.known_plugins |= set('%s/%s' % (plugin_type, plugin_name) for plugin_name in plugin_names) module_names = config.get('modules', []) self.known_plugins |= set('module/%s' % module_name for module_name in module_names) def prune_plugins(self, plugins): """Remove plugins which are not in the provided list of plugins. :type plugins: list[PluginDescription] """ valid_plugins = collections.defaultdict(set) for plugin in plugins: valid_plugins[plugin.type].add(plugin.name) for version, config in self.releases.items(): if 'modules' in config: invalid_modules = set(module for module in config['modules'] if module not in valid_plugins['module']) config['modules'] = [module for module in config['modules'] if module not in invalid_modules] self.known_plugins -= set('module/%s' % module for module in invalid_modules) if 'plugins' in config: for plugin_type in config['plugins']: invalid_plugins = set(plugin for plugin in config['plugins'][plugin_type] if plugin not in valid_plugins[plugin_type]) config['plugins'][plugin_type] = [plugin for plugin in config['plugins'][plugin_type] if plugin not in invalid_plugins] self.known_plugins -= set('%s/%s' % (plugin_type, plugin) for plugin in invalid_plugins) def prune_fragments(self, fragments): """Remove fragments which are not in the provided list of fragments. :type fragments: list[ChangelogFragment] """ valid_fragments = set(fragment.name for fragment in fragments) for version, config in self.releases.items(): if 'fragments' not in config: continue invalid_fragments = set(fragment for fragment in config['fragments'] if fragment not in valid_fragments) config['fragments'] = [fragment for fragment in config['fragments'] if fragment not in invalid_fragments] self.known_fragments -= set(config['fragments']) def sort(self): """Sort change metadata in place.""" for release, config in self.data['releases'].items(): if 'fragments' in config: config['fragments'] = sorted(config['fragments']) if 'modules' in config: config['modules'] = sorted(config['modules']) if 'plugins' in config: for plugin_type in config['plugins']: config['plugins'][plugin_type] = sorted(config['plugins'][plugin_type]) def save(self): """Save the change metadata to disk.""" self.sort() with open(self.path, 'w') as config_fd: yaml.safe_dump(self.data, config_fd, default_flow_style=False) def add_release(self, version, codename, release_date): """Add a new releases to the changes metadata. :type version: str :type codename: str :type release_date: datetime.date """ if version not in self.releases: self.releases[version] = dict( codename=codename, release_date=str(release_date), ) else: LOGGER.warning('release %s already exists', version) def add_fragment(self, fragment_name, version): """Add a changelog fragment to the change metadata. :type fragment_name: str :type version: str """ if fragment_name in self.known_fragments: return False self.known_fragments.add(fragment_name) if 'fragments' not in self.releases[version]: self.releases[version]['fragments'] = [] fragments = self.releases[version]['fragments'] fragments.append(fragment_name) return True def add_plugin(self, plugin_type, plugin_name, version): """Add a plugin to the change metadata. :type plugin_type: str :type plugin_name: str :type version: str """ composite_name = '%s/%s' % (plugin_type, plugin_name) if composite_name in self.known_plugins: return False self.known_plugins.add(composite_name) if plugin_type == 'module': if 'modules' not in self.releases[version]: self.releases[version]['modules'] = [] modules = self.releases[version]['modules'] modules.append(plugin_name) else: if 'plugins' not in self.releases[version]: self.releases[version]['plugins'] = {} plugins = self.releases[version]['plugins'] if plugin_type not in plugins: plugins[plugin_type] = [] plugins[plugin_type].append(plugin_name) return True if __name__ == '__main__': main()
gpl-3.0
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/pyscreenshot/plugins/imagemagick.py
2
1081
from easyprocess import EasyProcess from easyprocess import extract_version from PIL import Image import tempfile PROGRAM = 'import' # http://www.imagemagick.org/ class ImagemagickWrapper(object): name = 'imagemagick' childprocess = True def __init__(self): EasyProcess([PROGRAM, '-version']).check_installed() def grab(self, bbox=None): f = tempfile.NamedTemporaryFile( suffix='.png', prefix='pyscreenshot_imagemagick_') filename = f.name self.grab_to_file(filename, bbox=bbox) im = Image.open(filename) # if bbox: # im = im.crop(bbox) return im def grab_to_file(self, filename, bbox=None): command = 'import -silent -window root ' if bbox: command += " -crop '%sx%s+%s+%s' " % ( bbox[2] - bbox[0], bbox[3] - bbox[1], bbox[0], bbox[1]) command += filename EasyProcess(command).call() def backend_version(self): return extract_version(EasyProcess([PROGRAM, '-version']).call().stdout.replace('-', ' '))
gpl-3.0
Belgabor/django
django/middleware/cache.py
35
6947
""" Cache middleware. If enabled, each Django-powered page will be cached based on URL. The canonical way to enable cache middleware is to set ``UpdateCacheMiddleware`` as your first piece of middleware, and ``FetchFromCacheMiddleware`` as the last:: MIDDLEWARE_CLASSES = [ 'django.middleware.cache.UpdateCacheMiddleware', ... 'django.middleware.cache.FetchFromCacheMiddleware' ] This is counter-intuitive, but correct: ``UpdateCacheMiddleware`` needs to run last during the response phase, which processes middleware bottom-up; ``FetchFromCacheMiddleware`` needs to run last during the request phase, which processes middleware top-down. The single-class ``CacheMiddleware`` can be used for some simple sites. However, if any other piece of middleware needs to affect the cache key, you'll need to use the two-part ``UpdateCacheMiddleware`` and ``FetchFromCacheMiddleware``. This'll most often happen when you're using Django's ``LocaleMiddleware``. More details about how the caching works: * Only parameter-less GET or HEAD-requests with status code 200 are cached. * The number of seconds each page is stored for is set by the "max-age" section of the response's "Cache-Control" header, falling back to the CACHE_MIDDLEWARE_SECONDS setting if the section was not found. * If CACHE_MIDDLEWARE_ANONYMOUS_ONLY is set to True, only anonymous requests (i.e., those not made by a logged-in user) will be cached. This is a simple and effective way of avoiding the caching of the Django admin (and any other user-specific content). * This middleware expects that a HEAD request is answered with a response exactly like the corresponding GET request. * When a hit occurs, a shallow copy of the original response object is returned from process_request. * Pages will be cached based on the contents of the request headers listed in the response's "Vary" header. * This middleware also sets ETag, Last-Modified, Expires and Cache-Control headers on the response object. """ from django.conf import settings from django.core.cache import cache from django.utils.cache import get_cache_key, learn_cache_key, patch_response_headers, get_max_age class UpdateCacheMiddleware(object): """ Response-phase cache middleware that updates the cache if the response is cacheable. Must be used as part of the two-part update/fetch cache middleware. UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE_CLASSES so that it'll get called last during the response phase. """ def __init__(self): self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) def process_response(self, request, response): """Sets the cache, if needed.""" if not hasattr(request, '_cache_update_cache') or not request._cache_update_cache: # We don't need to update the cache, just return. return response if request.method != 'GET': # This is a stronger requirement than above. It is needed # because of interactions between this middleware and the # HTTPMiddleware, which throws the body of a HEAD-request # away before this middleware gets a chance to cache it. return response if not response.status_code == 200: return response # Try to get the timeout from the "max-age" section of the "Cache- # Control" header before reverting to using the default cache_timeout # length. timeout = get_max_age(response) if timeout == None: timeout = self.cache_timeout elif timeout == 0: # max-age was set to 0, don't bother caching. return response patch_response_headers(response, timeout) if timeout: cache_key = learn_cache_key(request, response, timeout, self.key_prefix) cache.set(cache_key, response, timeout) return response class FetchFromCacheMiddleware(object): """ Request-phase cache middleware that fetches a page from the cache. Must be used as part of the two-part update/fetch cache middleware. FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE_CLASSES so that it'll get called last during the request phase. """ def __init__(self): self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ if self.cache_anonymous_only: assert hasattr(request, 'user'), "The Django cache middleware with CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True requires authentication middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.auth.middleware.AuthenticationMiddleware' before the CacheMiddleware." if not request.method in ('GET', 'HEAD') or request.GET: request._cache_update_cache = False return None # Don't bother checking the cache. if self.cache_anonymous_only and request.user.is_authenticated(): request._cache_update_cache = False return None # Don't cache requests from authenticated users. cache_key = get_cache_key(request, self.key_prefix) if cache_key is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. response = cache.get(cache_key, None) if response is None: request._cache_update_cache = True return None # No cache information available, need to rebuild. request._cache_update_cache = False return response class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware): """ Cache middleware that provides basic behavior for many simple sites. Also used as the hook point for the cache decorator, which is generated using the decorator-from-middleware utility. """ def __init__(self, cache_timeout=None, key_prefix=None, cache_anonymous_only=None): self.cache_timeout = cache_timeout if cache_timeout is None: self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS self.key_prefix = key_prefix if key_prefix is None: self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_anonymous_only is None: self.cache_anonymous_only = getattr(settings, 'CACHE_MIDDLEWARE_ANONYMOUS_ONLY', False) else: self.cache_anonymous_only = cache_anonymous_only
bsd-3-clause
kevin-coder/tensorflow-fork
tensorflow/python/util/decorator_utils.py
32
4132
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility functions for writing decorators (which modify docstrings).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys def get_qualified_name(function): # Python 3 if hasattr(function, '__qualname__'): return function.__qualname__ # Python 2 if hasattr(function, 'im_class'): return function.im_class.__name__ + '.' + function.__name__ return function.__name__ def _normalize_docstring(docstring): """Normalizes the docstring. Replaces tabs with spaces, removes leading and trailing blanks lines, and removes any indentation. Copied from PEP-257: https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation Args: docstring: the docstring to normalize Returns: The normalized docstring """ if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): # (we use sys.maxsize because sys.maxint doesn't exist in Python 3) indent = sys.maxsize for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxsize: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed) def add_notice_to_docstring( doc, instructions, no_doc_str, suffix_str, notice): """Adds a deprecation notice to a docstring. Args: doc: The original docstring. instructions: A string, describing how to fix the problem. no_doc_str: The default value to use for `doc` if `doc` is empty. suffix_str: Is added to the end of the first line. notice: A list of strings. The main notice warning body. Returns: A new docstring, with the notice attached. Raises: ValueError: If `notice` is empty. """ if not doc: lines = [no_doc_str] else: lines = _normalize_docstring(doc).splitlines() lines[0] += ' ' + suffix_str if not notice: raise ValueError('The `notice` arg must not be empty.') notice[0] = 'Warning: ' + notice[0] notice = [''] + notice + ([instructions] if instructions else []) if len(lines) > 1: # Make sure that we keep our distance from the main body if lines[1].strip(): notice.append('') lines[1:1] = notice else: lines += notice return '\n'.join(lines) def validate_callable(func, decorator_name): if not hasattr(func, '__call__'): raise ValueError( '%s is not a function. If this is a property, make sure' ' @property appears before @%s in your source code:' '\n\n@property\n@%s\ndef method(...)' % ( func, decorator_name, decorator_name)) class classproperty(object): # pylint: disable=invalid-name """Class property decorator. Example usage: class MyClass(object): @classproperty def value(cls): return '123' > print MyClass.value 123 """ def __init__(self, func): self._func = func def __get__(self, owner_self, owner_cls): return self._func(owner_cls)
apache-2.0
pjquirk/pjquirk-dotnetnames
doc_src/build_autodoc_files.py
16
2513
"Build up the sphinx autodoc file for the python code" import os import sys docs_folder = os.path.dirname(__file__) pywin_folder = os.path.dirname(docs_folder) sys.path.append(pywin_folder) pywin_folder = os.path.join(pywin_folder, "pywinauto") excluded_dirs = ["unittests"] excluded_files = [ "_menux.py", "__init__.py", "win32defines.py", "win32structures.py", "win32functions.py"] output_folder = os.path.join(docs_folder, "code") try: os.mkdir(output_folder) except WindowsError: pass module_docs = [] for root, dirs, files in os.walk(pywin_folder): # Skip over directories we don't want to document for i, d in enumerate(dirs): if d in excluded_dirs: del dirs[i] py_files = [f for f in files if f.endswith(".py")] for py_filename in py_files: # skip over py files we don't want to document if py_filename in excluded_files: continue py_filepath = os.path.join(root, py_filename) # find the last instance of 'pywinauto' to make a module name from # the path modulename = 'pywinauto' + py_filepath.rsplit("pywinauto", 1)[1] modulename = os.path.splitext(modulename)[0] modulename = modulename.replace('\\', '.') # the final doc name is the modulename + .txt doc_source_filename = os.path.join(output_folder, modulename + ".txt") # skip files that are already generated if os.path.exists(doc_source_filename): continue print py_filename out = open(doc_source_filename, "w") out.write(modulename + "\n") out.write("-" * len(modulename) + "\n") out.write(" .. automodule:: %s\n"% modulename) out.write(" :members:\n") out.write(" :undoc-members:\n\n") #out.write(" :inherited-members:\n") #out.write(" .. autoattribute:: %s\n"% modulename) out.close() module_docs.append(doc_source_filename) # This section needs to be updated - I should idealy parse the # existing file to see if any new docs have been added, if not then # I should just leave the file alone rathre than re-create. # #c = open(os.path.join(output_folder, "code.txt"), "w") #c.write("Source Code\n") #c.write("=" * 30 + "\n") # #c.write(".. toctree::\n") #c.write(" :maxdepth: 3\n\n") #for doc in module_docs: # c.write(" " + doc + "\n") # #c.close()
lgpl-2.1
jzoldak/edx-platform
lms/djangoapps/mobile_api/video_outlines/views.py
121
4888
""" Video Outlines We only provide the listing view for a video outline, and video outlines are only displayed at the course level. This is because it makes it a lot easier to optimize and reason about, and it avoids having to tackle the bigger problem of general XBlock representation in this rather specialized formatting. """ from functools import partial from django.http import Http404, HttpResponse from mobile_api.models import MobileApiConfig from rest_framework import generics from rest_framework.response import Response from opaque_keys.edx.locator import BlockUsageLocator from xmodule.exceptions import NotFoundError from xmodule.modulestore.django import modulestore from ..utils import mobile_view, mobile_course_access from .serializers import BlockOutline, video_summary @mobile_view() class VideoSummaryList(generics.ListAPIView): """ **Use Case** Get a list of all videos in the specified course. You can use the video_url value to access the video file. **Example Request** GET /api/mobile/v0.5/video_outlines/courses/{organization}/{course_number}/{course_run} **Response Values** If the request is successful, the request returns an HTTP 200 "OK" response along with an array of videos in the course. The array includes the following information for each video. * named_path: An array that consists of the display names of the courseware objects in the path to the video. * path: An array that specifies the complete path to the video in the courseware hierarchy. The array contains the following values. * category: The type of division in the course outline. Possible values are "chapter", "sequential", and "vertical". * name: The display name for the object. * id: The The unique identifier for the video. * section_url: The URL to the first page of the section that contains the video in the Learning Management System. * summary: An array of data about the video that includes the following values. * category: The type of component. This value will always be "video". * duration: The length of the video, if available. * id: The unique identifier for the video. * language: The language code for the video. * name: The display name of the video. * size: The size of the video file. * transcripts: An array of language codes and URLs to available video transcripts. Use the URL value to access a transcript for the video. * video_thumbnail_url: The URL to the thumbnail image for the video, if available. * video_url: The URL to the video file. Use this value to access the video. * unit_url: The URL to the unit that contains the video in the Learning Management System. """ @mobile_course_access(depth=None) def list(self, request, course, *args, **kwargs): video_profiles = MobileApiConfig.get_video_profiles() video_outline = list( BlockOutline( course.id, course, {"video": partial(video_summary, video_profiles)}, request, video_profiles, ) ) return Response(video_outline) @mobile_view() class VideoTranscripts(generics.RetrieveAPIView): """ **Use Case** Get a transcript for a specified video and language. **Example request** GET /api/mobile/v0.5/video_outlines/transcripts/{organization}/{course_number}/{course_run}/{video ID}/{language code} **Response Values** If the request is successful, the request returns an HTTP 200 "OK" response along with an .srt file that you can download. """ @mobile_course_access() def get(self, request, course, *args, **kwargs): block_id = kwargs['block_id'] lang = kwargs['lang'] usage_key = BlockUsageLocator( course.id, block_type="video", block_id=block_id ) try: video_descriptor = modulestore().get_item(usage_key) transcripts = video_descriptor.get_transcripts_info() content, filename, mimetype = video_descriptor.get_transcript(transcripts, lang=lang) except (NotFoundError, ValueError, KeyError): raise Http404(u"Transcript not found for {}, lang: {}".format(block_id, lang)) response = HttpResponse(content, content_type=mimetype) response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename.encode('utf-8')) return response
agpl-3.0
MalwareLu/malwasm
web/malwasm_web.py
2
6829
#!/usr/bin/env python2.7 # Copyright (C) 2012 Malwasm Developers. # This file is part of Malwasm - https://code.google.com/p/malwasm/ # See the file LICENSE for copying permission. # _ # _ __ ___ __ _| |_ ____ _ ___ _ __ ___ # | '_ ` _ \ / _` | \ \ /\ / / _` / __| '_ ` _ \ # | | | | | | (_| | |\ V V / (_| \__ \ | | | | | # |_| |_| |_|\__,_|_| \_/\_/ \__,_|___/_| |_| |_| # import psycopg2 import psycopg2.extras import json, StringIO import sys, os import datetime from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash, jsonify, send_file sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")) from core.MalwasmConfig import * # Debug flag DEBUG = True # Db config from MalwasmConfig config = MalwasmConfig().get('database') app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): """Returns a new connection to the database.""" return psycopg2.connect("dbname=%s user=%s password=%s host=%s" % (config['dbname'], config['username'], config['password'], config['host'])) @app.before_request def before_request(): """Make sure we are connected to the database each request.""" g.db = connect_db() @app.teardown_request def teardown_request(exception): """Closes the database again at the end of the request.""" if hasattr(g, 'db'): g.db.close() @app.route('/nthreads') def nthreads(): """ Return the number of thread used by a samples """ sample_id = request.args.get('sample_id', -1, type=int) if sample_id == -1: abort(401) cur = g.db.cursor() cur.execute("SELECT DISTINCT thread_id FROM ins WHERE sample_id=%s",(sample_id,)) d = cur.fetchall() threads=[] for t in d: threads.append(t[0]) cur.close() threads.sort() return json.dumps(threads) @app.route('/dump') def dump(): """ Return dump of memory for a sample_id, an ins_id, a thread_id and a address range """ sample_id = request.args.get('sample_id', -1, type=int) ins_id = request.args.get('ins_id', -1, type=int) thread_id = request.args.get('thread_id', -1, type=int) adr_start = request.args.get('start', -1, type=int) adr_stop = request.args.get('stop', -1, type=int) if sample_id == -1 or ins_id == -1 or thread_id == -1 or adr_start == -1\ or adr_stop == -1: abort(401) cur = g.db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("SELECT data, adr_start " + \ "FROM dump " + \ "WHERE sample_id=%s AND ins_id<=%s AND thread_id=%s " + \ "AND adr_start<=%s AND adr_stop>=%s" "ORDER BY ins_id DESC LIMIT 1", (sample_id, ins_id, thread_id, adr_start, adr_stop)); d = cur.fetchone() if d == None: return '', 404 cur.close() output = StringIO.StringIO() output.write(d['data'][ adr_start-d['adr_start'] : adr_stop-d['adr_start'] ]) output.seek(0) return send_file(output) @app.route('/instruction') def instruction(): """Return a instruction information for a sample_id and ins_id""" sample_id = request.args.get('sample_id', -1, type=int) ins_id = request.args.get('ins_id', -1, type=int) thread_id = request.args.get('thread_id', -1, type=int) if sample_id == -1 or ins_id == -1 or thread_id == -1: abort(401) cur = g.db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("SELECT * FROM ins i " +\ "INNER JOIN reg r ON id=ins_id AND r.sample_id=i.sample_id AND i.thread_id=r.thread_id " +\ "WHERE i.sample_id=%s AND ins_id=%s AND i.thread_id=%s", (sample_id, ins_id, thread_id)) d = cur.fetchone() cur.close() return json.dumps(d) @app.route('/samples') def samples(): """Return all samples information""" cur = g.db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) dthandler = lambda obj: obj.strftime('%Y-%m-%d %H:%M:%S') if isinstance(obj, datetime.datetime) else None cur.execute("SELECT id, filename, md5, insert_at, pin_param FROM sample ORDER BY id DESC;") d = cur.fetchall() cur.close() return json.dumps(d, default=dthandler) @app.route('/threadInfo') def threadInfo(): """Return all information about thread_id of a sample_id""" sample_id = request.args.get('sample_id', -1, type=int) thread_id = request.args.get('thread_id', -1, type=int) if sample_id == -1 or thread_id == -1: abort(401) # build information instruction cur = g.db.cursor(cursor_factory=psycopg2.extras.RealDictCursor) cur.execute("SELECT f.name[1] as filename, f.name[2] as section, f.adr " + \ "FROM ( " + \ "SELECT DISTINCT regexp_matches(name, '^(.*):([^\+]*)(.*)?$') as name, adr "+ \ "FROM ins WHERE sample_id=%s AND thread_id=%s) " + \ "AS f ORDER BY adr", (sample_id,thread_id)) d = cur.fetchall() results = {} results['tree'] = {} for r in d: if r['filename'] not in results['tree']: results['tree'][r['filename']]={} if r['section'] not in results['tree'][r['filename']]: results['tree'][r['filename']][r['section']]=[] results['tree'][r['filename']][r['section']].append(r['adr']) cur.execute("SELECT adr, id, asm, name, comment FROM ins WHERE sample_id=%s AND thread_id=%s ORDER BY adr, id", (sample_id,thread_id)) d = cur.fetchall() results['instruction'] = {} for i in d: if i['adr'] not in results['instruction']: results['instruction'][i['adr']]={} results['instruction'][i['adr']][i['id']]={'name' : i['name'], 'asm' : i['asm'], 'comment': i['comment']} cur.execute("SELECT adr_start, adr_stop, MIN(ins_id) AS min_ins_id " + \ "FROM dump WHERE sample_id=%s AND thread_id=%s " + \ "GROUP BY adr_start, adr_stop " + \ "ORDER BY adr_start ASC", (sample_id, thread_id)) ; memRange = cur.fetchall() results['memRange']=[] for r in memRange: cur.execute("SELECT ins_id, adr_start, adr_stop " + \ "FROM dump WHERE sample_id=%s AND thread_id=%s " + \ "AND adr_start=%s AND adr_stop=%s" + \ "ORDER BY ins_id", (sample_id, thread_id, r['adr_start'], r['adr_stop'])); r['list'] = cur.fetchall() results['memRange'].append(r) return json.dumps(results) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run()
gpl-2.0
ric2b/Vivaldi-browser
chromium/build/android/convert_dex_profile_tests.py
7
9805
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for convert_dex_profile. Can be run from build/android/: $ cd build/android $ python convert_dex_profile_tests.py """ import os import sys import tempfile import unittest import convert_dex_profile as cp sys.path.insert(1, os.path.join(os.path.dirname(__file__), 'gyp')) from util import build_utils cp.logging.disable(cp.logging.CRITICAL) # There are two obfuscations used in the tests below, each with the same # unobfuscated profile. The first, corresponding to DEX_DUMP, PROGUARD_MAPPING, # and OBFUSCATED_PROFILE, has an ambiguous method a() which is mapped to both # getInstance and initialize. The second, corresponding to DEX_DUMP_2, # PROGUARD_MAPPING_2 and OBFUSCATED_PROFILE_2, removes the ambiguity. DEX_DUMP = """ Class descriptor : 'La;' Direct methods - #0 : (in La;) name : '<clinit>' type : '(Ljava/lang/String;)V' code - catches : 1 0x000f - 0x001e <any> -> 0x0093 positions : 0x0001 line=310 0x0057 line=313 locals : #1 : (in La;) name : '<init>' type : '()V' positions : locals : Virtual methods - #0 : (in La;) name : 'a' type : '(Ljava/lang/String;)I' positions : 0x0000 line=2 0x0003 line=3 0x001b line=8 locals : 0x0000 - 0x0021 reg=3 this La; #1 : (in La;) name : 'a' type : '(Ljava/lang/Object;)I' positions : 0x0000 line=8 0x0003 line=9 locals : 0x0000 - 0x0021 reg=3 this La; #2 : (in La;) name : 'b' type : '()La;' positions : 0x0000 line=1 locals : """ # pylint: disable=line-too-long PROGUARD_MAPPING = \ """org.chromium.Original -> a: org.chromium.Original sDisplayAndroidManager -> e org.chromium.Original another() -> b 4:4:void inlined():237:237 -> a 4:4:org.chromium.Original getInstance():203 -> a 5:5:void org.chromium.Original$Subclass.<init>(org.chromium.Original,byte):130:130 -> a 5:5:void initialize():237 -> a 5:5:org.chromium.Original getInstance():203 -> a 6:6:void initialize():237:237 -> a 9:9:android.content.Context org.chromium.base.ContextUtils.getApplicationContext():49:49 -> a 9:9:android.content.Context getContext():219 -> a 9:9:void initialize():245 -> a 9:9:org.chromium.Original getInstance():203 -> a""" OBFUSCATED_PROFILE = \ """La; PLa;->b()La; SLa;->a(Ljava/lang/Object;)I HPLa;->a(Ljava/lang/String;)I""" DEX_DUMP_2 = """ Class descriptor : 'La;' Direct methods - #0 : (in La;) name : '<clinit>' type : '(Ljava/lang/String;)V' code - catches : 1 0x000f - 0x001e <any> -> 0x0093 positions : 0x0001 line=310 0x0057 line=313 locals : #1 : (in La;) name : '<init>' type : '()V' positions : locals : Virtual methods - #0 : (in La;) name : 'a' type : '(Ljava/lang/String;)I' positions : 0x0000 line=2 0x0003 line=3 0x001b line=8 locals : 0x0000 - 0x0021 reg=3 this La; #1 : (in La;) name : 'c' type : '(Ljava/lang/Object;)I' positions : 0x0000 line=8 0x0003 line=9 locals : 0x0000 - 0x0021 reg=3 this La; #2 : (in La;) name : 'b' type : '()La;' positions : 0x0000 line=1 locals : """ # pylint: disable=line-too-long PROGUARD_MAPPING_2 = \ """org.chromium.Original -> a: org.chromium.Original sDisplayAndroidManager -> e org.chromium.Original another() -> b void initialize() -> c org.chromium.Original getInstance():203 -> a 4:4:void inlined():237:237 -> a""" OBFUSCATED_PROFILE_2 = \ """La; PLa;->b()La; HPSLa;->a()La; HPLa;->c()V""" UNOBFUSCATED_PROFILE = \ """Lorg/chromium/Original; PLorg/chromium/Original;->another()Lorg/chromium/Original; HPSLorg/chromium/Original;->getInstance()Lorg/chromium/Original; HPLorg/chromium/Original;->initialize()V""" class GenerateProfileTests(unittest.TestCase): def testProcessDex(self): dex = cp.ProcessDex(DEX_DUMP.splitlines()) self.assertIsNotNone(dex['a']) self.assertEquals(len(dex['a'].FindMethodsAtLine('<clinit>', 311, 313)), 1) self.assertEquals(len(dex['a'].FindMethodsAtLine('<clinit>', 309, 315)), 1) clinit = dex['a'].FindMethodsAtLine('<clinit>', 311, 313)[0] self.assertEquals(clinit.name, '<clinit>') self.assertEquals(clinit.return_type, 'V') self.assertEquals(clinit.param_types, 'Ljava/lang/String;') self.assertEquals(len(dex['a'].FindMethodsAtLine('a', 8, None)), 2) self.assertIsNone(dex['a'].FindMethodsAtLine('a', 100, None)) # pylint: disable=protected-access def testProcessProguardMapping(self): dex = cp.ProcessDex(DEX_DUMP.splitlines()) mapping, reverse = cp.ProcessProguardMapping( PROGUARD_MAPPING.splitlines(), dex) self.assertEquals('La;', reverse.GetClassMapping('Lorg/chromium/Original;')) getInstance = cp.Method( 'getInstance', 'Lorg/chromium/Original;', '', 'Lorg/chromium/Original;') initialize = cp.Method('initialize', 'Lorg/chromium/Original;', '', 'V') another = cp.Method( 'another', 'Lorg/chromium/Original;', '', 'Lorg/chromium/Original;') subclassInit = cp.Method( '<init>', 'Lorg/chromium/Original$Subclass;', 'Lorg/chromium/Original;B', 'V') mapped = mapping.GetMethodMapping( cp.Method('a', 'La;', 'Ljava/lang/String;', 'I')) self.assertEquals(len(mapped), 2) self.assertIn(getInstance, mapped) self.assertNotIn(subclassInit, mapped) self.assertNotIn( cp.Method('inlined', 'Lorg/chromium/Original;', '', 'V'), mapped) self.assertIn(initialize, mapped) mapped = mapping.GetMethodMapping( cp.Method('a', 'La;', 'Ljava/lang/Object;', 'I')) self.assertEquals(len(mapped), 1) self.assertIn(getInstance, mapped) mapped = mapping.GetMethodMapping(cp.Method('b', 'La;', '', 'La;')) self.assertEquals(len(mapped), 1) self.assertIn(another, mapped) for from_method, to_methods in mapping._method_mapping.iteritems(): for to_method in to_methods: self.assertIn(from_method, reverse.GetMethodMapping(to_method)) for from_class, to_class in mapping._class_mapping.iteritems(): self.assertEquals(from_class, reverse.GetClassMapping(to_class)) def testProcessProfile(self): dex = cp.ProcessDex(DEX_DUMP.splitlines()) mapping, _ = cp.ProcessProguardMapping(PROGUARD_MAPPING.splitlines(), dex) profile = cp.ProcessProfile(OBFUSCATED_PROFILE.splitlines(), mapping) getInstance = cp.Method( 'getInstance', 'Lorg/chromium/Original;', '', 'Lorg/chromium/Original;') initialize = cp.Method('initialize', 'Lorg/chromium/Original;', '', 'V') another = cp.Method( 'another', 'Lorg/chromium/Original;', '', 'Lorg/chromium/Original;') self.assertIn('Lorg/chromium/Original;', profile._classes) self.assertIn(getInstance, profile._methods) self.assertIn(initialize, profile._methods) self.assertIn(another, profile._methods) self.assertEquals(profile._methods[getInstance], set(['H', 'S', 'P'])) self.assertEquals(profile._methods[initialize], set(['H', 'P'])) self.assertEquals(profile._methods[another], set(['P'])) def testEndToEnd(self): dex = cp.ProcessDex(DEX_DUMP.splitlines()) mapping, _ = cp.ProcessProguardMapping(PROGUARD_MAPPING.splitlines(), dex) profile = cp.ProcessProfile(OBFUSCATED_PROFILE.splitlines(), mapping) with tempfile.NamedTemporaryFile() as temp: profile.WriteToFile(temp.name) with open(temp.name, 'r') as f: for a, b in zip(sorted(f), sorted(UNOBFUSCATED_PROFILE.splitlines())): self.assertEquals(a.strip(), b.strip()) def testObfuscateProfile(self): with build_utils.TempDir() as temp_dir: # The dex dump is used as the dexfile, by passing /bin/cat as the dexdump # program. dex_path = os.path.join(temp_dir, 'dexdump') with open(dex_path, 'w') as dex_file: dex_file.write(DEX_DUMP_2) mapping_path = os.path.join(temp_dir, 'mapping') with open(mapping_path, 'w') as mapping_file: mapping_file.write(PROGUARD_MAPPING_2) unobfuscated_path = os.path.join(temp_dir, 'unobfuscated') with open(unobfuscated_path, 'w') as unobfuscated_file: unobfuscated_file.write(UNOBFUSCATED_PROFILE) obfuscated_path = os.path.join(temp_dir, 'obfuscated') cp.ObfuscateProfile(unobfuscated_path, dex_path, mapping_path, '/bin/cat', obfuscated_path) with open(obfuscated_path) as obfuscated_file: obfuscated_profile = sorted(obfuscated_file.readlines()) for a, b in zip( sorted(OBFUSCATED_PROFILE_2.splitlines()), obfuscated_profile): self.assertEquals(a.strip(), b.strip()) if __name__ == '__main__': unittest.main()
bsd-3-clause
WhySoGeeky/DroidPot
venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/big5freq.py
3133
82594
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # Big5 frequency table # by Taiwan's Mandarin Promotion Council # <http://www.edu.tw:81/mandr/> # # 128 --> 0.42261 # 256 --> 0.57851 # 512 --> 0.74851 # 1024 --> 0.89384 # 2048 --> 0.97583 # # Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98 # Random Distribution Ration = 512/(5401-512)=0.105 # # Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR BIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75 #Char to FreqOrder table BIG5_TABLE_SIZE = 5376 Big5CharToFreqOrder = ( 1,1801,1506, 255,1431, 198, 9, 82, 6,5008, 177, 202,3681,1256,2821, 110, # 16 3814, 33,3274, 261, 76, 44,2114, 16,2946,2187,1176, 659,3971, 26,3451,2653, # 32 1198,3972,3350,4202, 410,2215, 302, 590, 361,1964, 8, 204, 58,4510,5009,1932, # 48 63,5010,5011, 317,1614, 75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, # 64 3682, 3, 10,3973,1471, 29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, # 80 4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947, 34,3556,3204, 64, 604, # 96 5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337, 72, 406,5017, 80, # 112 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449, 69,2987, 591, # 128 179,2096, 471, 115,2035,1844, 60, 50,2988, 134, 806,1869, 734,2036,3454, 180, # 144 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, # 160 2502, 90,2716,1338, 663, 11, 906,1099,2553, 20,2441, 182, 532,1716,5019, 732, # 176 1376,4204,1311,1420,3206, 25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, # 192 3276, 475,1447,3683,5020, 117, 21, 656, 810,1297,2300,2334,3557,5021, 126,4205, # 208 706, 456, 150, 613,4513, 71,1118,2037,4206, 145,3092, 85, 835, 486,2115,1246, # 224 1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, # 240 3558,3135,5023,1956,1153,4207, 83, 296,1199,3093, 192, 624, 93,5024, 822,1898, # 256 2823,3136, 795,2065, 991,1554,1542,1592, 27, 43,2867, 859, 139,1456, 860,4514, # 272 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, # 288 3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, # 304 1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, # 320 5026,5027,2176,3207,3685,2682, 593, 845,1062,3277, 88,1723,2038,3978,1951, 212, # 336 266, 152, 149, 468,1899,4208,4516, 77, 187,5028,3038, 37, 5,2990,5029,3979, # 352 5030,5031, 39,2524,4517,2908,3208,2079, 55, 148, 74,4518, 545, 483,1474,1029, # 368 1665, 217,1870,1531,3138,1104,2655,4209, 24, 172,3562, 900,3980,3563,3564,4519, # 384 32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683, 4,3039,3351,1427,1789, # 400 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, # 416 3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439, 38,5037,1063,5038, 794, # 432 3982,1435,2301, 46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804, 35, 707, # 448 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, # 464 2129,1363,3689,1423, 697, 100,3094, 48, 70,1231, 495,3139,2196,5043,1294,5044, # 480 2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, # 496 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, # 512 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, # 528 3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, # 544 1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, # 560 1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, # 576 1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381, 7, # 592 2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, # 608 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, # 624 4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, # 640 1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, # 656 5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, # 672 2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, # 688 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, # 704 98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, # 720 523,2789,2790,2658,5061, 141,2235,1333, 68, 176, 441, 876, 907,4220, 603,2602, # 736 710, 171,3464, 404, 549, 18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, # 752 5063,2991, 368,5064, 146, 366, 99, 871,3693,1543, 748, 807,1586,1185, 22,2263, # 768 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, # 784 1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068, 59,5069, # 800 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, # 816 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, # 832 5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, # 848 1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, # 864 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, # 880 3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, # 896 4224, 57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, # 912 3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, # 928 279,3145, 51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, # 944 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, # 960 1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, # 976 4227,2475,1436, 953,4228,2055,4545, 671,2400, 79,4229,2446,3285, 608, 567,2689, # 992 3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008 3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024 2402,5097,5098,5099,4232,3045, 0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040 5101, 233,4233,3697,1819,4550,4551,5102, 96,1777,1315,2083,5103, 257,5104,1810, # 1056 3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072 5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088 1484,5110,1712, 127, 67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104 2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120 1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136 78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152 1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168 4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184 3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216 165, 243,4559,3703,2528, 123, 683,4239, 764,4560, 36,3998,1793, 589,2916, 816, # 1232 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248 2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264 5122, 611,1156, 854,2386,1316,2875, 2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280 1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296 2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312 1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328 1994,5135,4564,5136,5137,2198, 13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344 5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360 5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376 5149, 128,2133, 92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392 3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408 4567,2252, 94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424 4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440 2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456 5163,2337,2068, 23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472 3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504 5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863, 41, # 1520 5170,5171,4575,5172,1657,2338, 19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536 1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552 2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568 3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584 4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600 5182,2692, 733, 40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616 3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632 4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648 1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664 1871,2762,3004,5187, 435,5188, 343,1108, 596, 17,1751,4579,2239,3477,3709,5189, # 1680 4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696 1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728 1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744 1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760 3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792 5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808 2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824 1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840 1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551, 30,2268,4266, # 1856 5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888 4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920 2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952 1041,3005, 293,1168, 87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968 1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984 730,1515, 184,2840, 66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000 4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016 4021,5231,5232,1186, 15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032 1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048 3596,1342,1681,1718, 766,3297, 286, 89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064 5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080 5240,3298, 310, 313,3482,2304, 770,4278, 54,3054, 189,4611,3105,3848,4025,5241, # 2096 1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112 2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128 1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144 3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160 2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176 3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192 2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208 4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224 4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240 3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256 97, 81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272 3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304 3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320 4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336 3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352 1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368 5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400 5286, 587, 14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416 1702,1226, 102,1547, 62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448 4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294, 86,1494,1730, # 2464 4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496 2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512 2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885, 28,2695, # 2528 3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544 1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560 4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576 2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592 1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608 1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624 2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640 3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656 1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672 5313,3493,5314,5315,5316,3310,2698,1433,3311, 131, 95,1504,4049, 723,4303,3166, # 2688 1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704 4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654, 53,5320,3014,5321, # 2720 1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752 1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768 4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784 4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800 2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816 1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832 4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864 5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880 2322,3316,5346,5347,4308,5348,4309, 84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896 3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912 4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944 5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960 5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976 1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992 4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008 4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024 2699,1516,3614,1121,1082,1329,3317,4073,1449,3873, 65,1128,2848,2927,2769,1590, # 3040 3874,5370,5371, 12,2668, 45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056 3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072 2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088 1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104 4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120 3736,1859, 91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136 3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152 2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168 4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771, 61,4079,3738,1823,4080, # 3184 5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200 3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216 2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232 3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248 1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264 2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280 3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296 4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063, 56,1396,3113, # 3312 2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328 2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344 5418,1076, 49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360 1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376 2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392 1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408 3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424 4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629, 31,2851, # 3440 2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456 3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472 3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488 2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504 4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520 2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536 3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552 4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568 5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584 3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616 1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412, 42,3119, 464,5455,2642, # 3632 4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648 1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664 4701,5462,3020, 962, 588,3629, 289,3250,2644,1116, 52,5463,3067,1797,5464,5465, # 3680 5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712 5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728 5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744 2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760 3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776 2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792 2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824 1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840 4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856 3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872 3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904 2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936 2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952 4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968 1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984 4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000 1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016 3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048 3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064 5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080 5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096 3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112 3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128 1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144 2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160 5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176 1561,2674,1452,4113,1375,5549,5550, 47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192 1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208 3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224 919,2352,2975,2353,1270,4727,4115, 73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240 1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256 4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272 5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288 2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304 3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336 1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352 2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368 2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384 5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400 5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416 5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432 2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448 2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464 1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480 4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496 3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512 3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528 4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544 4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560 2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576 2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592 5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608 4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624 5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640 4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688 1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704 3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720 4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736 1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752 5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768 2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784 2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800 3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816 5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832 1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848 3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864 5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880 1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896 5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912 2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928 3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944 2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960 3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976 3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992 3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008 4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040 2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056 4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072 3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088 5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104 1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120 5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152 1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184 4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200 1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216 4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232 1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264 3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280 4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296 5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328 3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360 2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376 #last 512 #Everything below is of no interest for detection purpose 2522,1613,4812,5799,3345,3945,2523,5800,4162,5801,1637,4163,2471,4813,3946,5802, # 5392 2500,3034,3800,5803,5804,2195,4814,5805,2163,5806,5807,5808,5809,5810,5811,5812, # 5408 5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828, # 5424 5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844, # 5440 5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856,5857,5858,5859,5860, # 5456 5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872,5873,5874,5875,5876, # 5472 5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888,5889,5890,5891,5892, # 5488 5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905,5906,5907,5908, # 5504 5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920,5921,5922,5923,5924, # 5520 5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936,5937,5938,5939,5940, # 5536 5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952,5953,5954,5955,5956, # 5552 5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968,5969,5970,5971,5972, # 5568 5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984,5985,5986,5987,5988, # 5584 5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004, # 5600 6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020, # 5616 6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032,6033,6034,6035,6036, # 5632 6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052, # 5648 6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068, # 5664 6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084, # 5680 6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100, # 5696 6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116, # 5712 6117,6118,6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,6132, # 5728 6133,6134,6135,6136,6137,6138,6139,6140,6141,6142,6143,6144,6145,6146,6147,6148, # 5744 6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163,6164, # 5760 6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179,6180, # 5776 6181,6182,6183,6184,6185,6186,6187,6188,6189,6190,6191,6192,6193,6194,6195,6196, # 5792 6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210,6211,6212, # 5808 6213,6214,6215,6216,6217,6218,6219,6220,6221,6222,6223,3670,6224,6225,6226,6227, # 5824 6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241,6242,6243, # 5840 6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,6254,6255,6256,6257,6258,6259, # 5856 6260,6261,6262,6263,6264,6265,6266,6267,6268,6269,6270,6271,6272,6273,6274,6275, # 5872 6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,4815,6286,6287,6288,6289,6290, # 5888 6291,6292,4816,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,6303,6304,6305, # 5904 6306,6307,6308,6309,6310,6311,4817,4818,6312,6313,6314,6315,6316,6317,6318,4819, # 5920 6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333,6334, # 5936 6335,6336,6337,4820,6338,6339,6340,6341,6342,6343,6344,6345,6346,6347,6348,6349, # 5952 6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363,6364,6365, # 5968 6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379,6380,6381, # 5984 6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395,6396,6397, # 6000 6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,3441,6411,6412, # 6016 6413,6414,6415,6416,6417,6418,6419,6420,6421,6422,6423,6424,6425,4440,6426,6427, # 6032 6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,6439,6440,6441,6442,6443, # 6048 6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,4821,6455,6456,6457,6458, # 6064 6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472,6473,6474, # 6080 6475,6476,6477,3947,3948,6478,6479,6480,6481,3272,4441,6482,6483,6484,6485,4442, # 6096 6486,6487,6488,6489,6490,6491,6492,6493,6494,6495,6496,4822,6497,6498,6499,6500, # 6112 6501,6502,6503,6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516, # 6128 6517,6518,6519,6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532, # 6144 6533,6534,6535,6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548, # 6160 6549,6550,6551,6552,6553,6554,6555,6556,2784,6557,4823,6558,6559,6560,6561,6562, # 6176 6563,6564,6565,6566,6567,6568,6569,3949,6570,6571,6572,4824,6573,6574,6575,6576, # 6192 6577,6578,6579,6580,6581,6582,6583,4825,6584,6585,6586,3950,2785,6587,6588,6589, # 6208 6590,6591,6592,6593,6594,6595,6596,6597,6598,6599,6600,6601,6602,6603,6604,6605, # 6224 6606,6607,6608,6609,6610,6611,6612,4826,6613,6614,6615,4827,6616,6617,6618,6619, # 6240 6620,6621,6622,6623,6624,6625,4164,6626,6627,6628,6629,6630,6631,6632,6633,6634, # 6256 3547,6635,4828,6636,6637,6638,6639,6640,6641,6642,3951,2984,6643,6644,6645,6646, # 6272 6647,6648,6649,4165,6650,4829,6651,6652,4830,6653,6654,6655,6656,6657,6658,6659, # 6288 6660,6661,6662,4831,6663,6664,6665,6666,6667,6668,6669,6670,6671,4166,6672,4832, # 6304 3952,6673,6674,6675,6676,4833,6677,6678,6679,4167,6680,6681,6682,3198,6683,6684, # 6320 6685,6686,6687,6688,6689,6690,6691,6692,6693,6694,6695,6696,6697,4834,6698,6699, # 6336 6700,6701,6702,6703,6704,6705,6706,6707,6708,6709,6710,6711,6712,6713,6714,6715, # 6352 6716,6717,6718,6719,6720,6721,6722,6723,6724,6725,6726,6727,6728,6729,6730,6731, # 6368 6732,6733,6734,4443,6735,6736,6737,6738,6739,6740,6741,6742,6743,6744,6745,4444, # 6384 6746,6747,6748,6749,6750,6751,6752,6753,6754,6755,6756,6757,6758,6759,6760,6761, # 6400 6762,6763,6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777, # 6416 6778,6779,6780,6781,4168,6782,6783,3442,6784,6785,6786,6787,6788,6789,6790,6791, # 6432 4169,6792,6793,6794,6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806, # 6448 6807,6808,6809,6810,6811,4835,6812,6813,6814,4445,6815,6816,4446,6817,6818,6819, # 6464 6820,6821,6822,6823,6824,6825,6826,6827,6828,6829,6830,6831,6832,6833,6834,6835, # 6480 3548,6836,6837,6838,6839,6840,6841,6842,6843,6844,6845,6846,4836,6847,6848,6849, # 6496 6850,6851,6852,6853,6854,3953,6855,6856,6857,6858,6859,6860,6861,6862,6863,6864, # 6512 6865,6866,6867,6868,6869,6870,6871,6872,6873,6874,6875,6876,6877,3199,6878,6879, # 6528 6880,6881,6882,4447,6883,6884,6885,6886,6887,6888,6889,6890,6891,6892,6893,6894, # 6544 6895,6896,6897,6898,6899,6900,6901,6902,6903,6904,4170,6905,6906,6907,6908,6909, # 6560 6910,6911,6912,6913,6914,6915,6916,6917,6918,6919,6920,6921,6922,6923,6924,6925, # 6576 6926,6927,4837,6928,6929,6930,6931,6932,6933,6934,6935,6936,3346,6937,6938,4838, # 6592 6939,6940,6941,4448,6942,6943,6944,6945,6946,4449,6947,6948,6949,6950,6951,6952, # 6608 6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966,6967,6968, # 6624 6969,6970,6971,6972,6973,6974,6975,6976,6977,6978,6979,6980,6981,6982,6983,6984, # 6640 6985,6986,6987,6988,6989,6990,6991,6992,6993,6994,3671,6995,6996,6997,6998,4839, # 6656 6999,7000,7001,7002,3549,7003,7004,7005,7006,7007,7008,7009,7010,7011,7012,7013, # 6672 7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027,7028,7029, # 6688 7030,4840,7031,7032,7033,7034,7035,7036,7037,7038,4841,7039,7040,7041,7042,7043, # 6704 7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058,7059, # 6720 7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,2985,7071,7072,7073,7074, # 6736 7075,7076,7077,7078,7079,7080,4842,7081,7082,7083,7084,7085,7086,7087,7088,7089, # 6752 7090,7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105, # 6768 7106,7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,4450,7119,7120, # 6784 7121,7122,7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136, # 6800 7137,7138,7139,7140,7141,7142,7143,4843,7144,7145,7146,7147,7148,7149,7150,7151, # 6816 7152,7153,7154,7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167, # 6832 7168,7169,7170,7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183, # 6848 7184,7185,7186,7187,7188,4171,4172,7189,7190,7191,7192,7193,7194,7195,7196,7197, # 6864 7198,7199,7200,7201,7202,7203,7204,7205,7206,7207,7208,7209,7210,7211,7212,7213, # 6880 7214,7215,7216,7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229, # 6896 7230,7231,7232,7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245, # 6912 7246,7247,7248,7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261, # 6928 7262,7263,7264,7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277, # 6944 7278,7279,7280,7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293, # 6960 7294,7295,7296,4844,7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308, # 6976 7309,7310,7311,7312,7313,7314,7315,7316,4451,7317,7318,7319,7320,7321,7322,7323, # 6992 7324,7325,7326,7327,7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339, # 7008 7340,7341,7342,7343,7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,4173,7354, # 7024 7355,4845,7356,7357,7358,7359,7360,7361,7362,7363,7364,7365,7366,7367,7368,7369, # 7040 7370,7371,7372,7373,7374,7375,7376,7377,7378,7379,7380,7381,7382,7383,7384,7385, # 7056 7386,7387,7388,4846,7389,7390,7391,7392,7393,7394,7395,7396,7397,7398,7399,7400, # 7072 7401,7402,7403,7404,7405,3672,7406,7407,7408,7409,7410,7411,7412,7413,7414,7415, # 7088 7416,7417,7418,7419,7420,7421,7422,7423,7424,7425,7426,7427,7428,7429,7430,7431, # 7104 7432,7433,7434,7435,7436,7437,7438,7439,7440,7441,7442,7443,7444,7445,7446,7447, # 7120 7448,7449,7450,7451,7452,7453,4452,7454,3200,7455,7456,7457,7458,7459,7460,7461, # 7136 7462,7463,7464,7465,7466,7467,7468,7469,7470,7471,7472,7473,7474,4847,7475,7476, # 7152 7477,3133,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487,7488,7489,7490,7491, # 7168 7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,3347,7503,7504,7505,7506, # 7184 7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519,7520,7521,4848, # 7200 7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535,7536,7537, # 7216 7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,3801,4849,7550,7551, # 7232 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, # 7248 7568,7569,3035,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582, # 7264 7583,7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598, # 7280 7599,7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614, # 7296 7615,7616,4850,7617,7618,3802,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628, # 7312 7629,7630,7631,7632,4851,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643, # 7328 7644,7645,7646,7647,7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659, # 7344 7660,7661,7662,7663,7664,7665,7666,7667,7668,7669,7670,4453,7671,7672,7673,7674, # 7360 7675,7676,7677,7678,7679,7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690, # 7376 7691,7692,7693,7694,7695,7696,7697,3443,7698,7699,7700,7701,7702,4454,7703,7704, # 7392 7705,7706,7707,7708,7709,7710,7711,7712,7713,2472,7714,7715,7716,7717,7718,7719, # 7408 7720,7721,7722,7723,7724,7725,7726,7727,7728,7729,7730,7731,3954,7732,7733,7734, # 7424 7735,7736,7737,7738,7739,7740,7741,7742,7743,7744,7745,7746,7747,7748,7749,7750, # 7440 3134,7751,7752,4852,7753,7754,7755,4853,7756,7757,7758,7759,7760,4174,7761,7762, # 7456 7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775,7776,7777,7778, # 7472 7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791,7792,7793,7794, # 7488 7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,4854,7806,7807,7808,7809, # 7504 7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823,7824,7825, # 7520 4855,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839,7840, # 7536 7841,7842,7843,7844,7845,7846,7847,3955,7848,7849,7850,7851,7852,7853,7854,7855, # 7552 7856,7857,7858,7859,7860,3444,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870, # 7568 7871,7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886, # 7584 7887,7888,7889,7890,7891,4175,7892,7893,7894,7895,7896,4856,4857,7897,7898,7899, # 7600 7900,2598,7901,7902,7903,7904,7905,7906,7907,7908,4455,7909,7910,7911,7912,7913, # 7616 7914,3201,7915,7916,7917,7918,7919,7920,7921,4858,7922,7923,7924,7925,7926,7927, # 7632 7928,7929,7930,7931,7932,7933,7934,7935,7936,7937,7938,7939,7940,7941,7942,7943, # 7648 7944,7945,7946,7947,7948,7949,7950,7951,7952,7953,7954,7955,7956,7957,7958,7959, # 7664 7960,7961,7962,7963,7964,7965,7966,7967,7968,7969,7970,7971,7972,7973,7974,7975, # 7680 7976,7977,7978,7979,7980,7981,4859,7982,7983,7984,7985,7986,7987,7988,7989,7990, # 7696 7991,7992,7993,7994,7995,7996,4860,7997,7998,7999,8000,8001,8002,8003,8004,8005, # 7712 8006,8007,8008,8009,8010,8011,8012,8013,8014,8015,8016,4176,8017,8018,8019,8020, # 7728 8021,8022,8023,4861,8024,8025,8026,8027,8028,8029,8030,8031,8032,8033,8034,8035, # 7744 8036,4862,4456,8037,8038,8039,8040,4863,8041,8042,8043,8044,8045,8046,8047,8048, # 7760 8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063,8064, # 7776 8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079,8080, # 7792 8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095,8096, # 7808 8097,8098,8099,4864,4177,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110, # 7824 8111,8112,8113,8114,8115,8116,8117,8118,8119,8120,4178,8121,8122,8123,8124,8125, # 7840 8126,8127,8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141, # 7856 8142,8143,8144,8145,4865,4866,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155, # 7872 8156,8157,8158,8159,8160,8161,8162,8163,8164,8165,4179,8166,8167,8168,8169,8170, # 7888 8171,8172,8173,8174,8175,8176,8177,8178,8179,8180,8181,4457,8182,8183,8184,8185, # 7904 8186,8187,8188,8189,8190,8191,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201, # 7920 8202,8203,8204,8205,8206,8207,8208,8209,8210,8211,8212,8213,8214,8215,8216,8217, # 7936 8218,8219,8220,8221,8222,8223,8224,8225,8226,8227,8228,8229,8230,8231,8232,8233, # 7952 8234,8235,8236,8237,8238,8239,8240,8241,8242,8243,8244,8245,8246,8247,8248,8249, # 7968 8250,8251,8252,8253,8254,8255,8256,3445,8257,8258,8259,8260,8261,8262,4458,8263, # 7984 8264,8265,8266,8267,8268,8269,8270,8271,8272,4459,8273,8274,8275,8276,3550,8277, # 8000 8278,8279,8280,8281,8282,8283,8284,8285,8286,8287,8288,8289,4460,8290,8291,8292, # 8016 8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303,8304,8305,8306,8307,4867, # 8032 8308,8309,8310,8311,8312,3551,8313,8314,8315,8316,8317,8318,8319,8320,8321,8322, # 8048 8323,8324,8325,8326,4868,8327,8328,8329,8330,8331,8332,8333,8334,8335,8336,8337, # 8064 8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351,8352,8353, # 8080 8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,4869,4461,8364,8365,8366,8367, # 8096 8368,8369,8370,4870,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382, # 8112 8383,8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398, # 8128 8399,8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,4871,8411,8412,8413, # 8144 8414,8415,8416,8417,8418,8419,8420,8421,8422,4462,8423,8424,8425,8426,8427,8428, # 8160 8429,8430,8431,8432,8433,2986,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443, # 8176 8444,8445,8446,8447,8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459, # 8192 8460,8461,8462,8463,8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475, # 8208 8476,8477,8478,4180,8479,8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490, # 8224 8491,8492,8493,8494,8495,8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506, # 8240 8507,8508,8509,8510,8511,8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522, # 8256 8523,8524,8525,8526,8527,8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538, # 8272 8539,8540,8541,8542,8543,8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554, # 8288 8555,8556,8557,8558,8559,8560,8561,8562,8563,8564,4872,8565,8566,8567,8568,8569, # 8304 8570,8571,8572,8573,4873,8574,8575,8576,8577,8578,8579,8580,8581,8582,8583,8584, # 8320 8585,8586,8587,8588,8589,8590,8591,8592,8593,8594,8595,8596,8597,8598,8599,8600, # 8336 8601,8602,8603,8604,8605,3803,8606,8607,8608,8609,8610,8611,8612,8613,4874,3804, # 8352 8614,8615,8616,8617,8618,8619,8620,8621,3956,8622,8623,8624,8625,8626,8627,8628, # 8368 8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,2865,8639,8640,8641,8642,8643, # 8384 8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655,8656,4463,8657,8658, # 8400 8659,4875,4876,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671,8672, # 8416 8673,8674,8675,8676,8677,8678,8679,8680,8681,4464,8682,8683,8684,8685,8686,8687, # 8432 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, # 8448 8704,8705,8706,8707,8708,8709,2261,8710,8711,8712,8713,8714,8715,8716,8717,8718, # 8464 8719,8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,4181, # 8480 8734,8735,8736,8737,8738,8739,8740,8741,8742,8743,8744,8745,8746,8747,8748,8749, # 8496 8750,8751,8752,8753,8754,8755,8756,8757,8758,8759,8760,8761,8762,8763,4877,8764, # 8512 8765,8766,8767,8768,8769,8770,8771,8772,8773,8774,8775,8776,8777,8778,8779,8780, # 8528 8781,8782,8783,8784,8785,8786,8787,8788,4878,8789,4879,8790,8791,8792,4880,8793, # 8544 8794,8795,8796,8797,8798,8799,8800,8801,4881,8802,8803,8804,8805,8806,8807,8808, # 8560 8809,8810,8811,8812,8813,8814,8815,3957,8816,8817,8818,8819,8820,8821,8822,8823, # 8576 8824,8825,8826,8827,8828,8829,8830,8831,8832,8833,8834,8835,8836,8837,8838,8839, # 8592 8840,8841,8842,8843,8844,8845,8846,8847,4882,8848,8849,8850,8851,8852,8853,8854, # 8608 8855,8856,8857,8858,8859,8860,8861,8862,8863,8864,8865,8866,8867,8868,8869,8870, # 8624 8871,8872,8873,8874,8875,8876,8877,8878,8879,8880,8881,8882,8883,8884,3202,8885, # 8640 8886,8887,8888,8889,8890,8891,8892,8893,8894,8895,8896,8897,8898,8899,8900,8901, # 8656 8902,8903,8904,8905,8906,8907,8908,8909,8910,8911,8912,8913,8914,8915,8916,8917, # 8672 8918,8919,8920,8921,8922,8923,8924,4465,8925,8926,8927,8928,8929,8930,8931,8932, # 8688 4883,8933,8934,8935,8936,8937,8938,8939,8940,8941,8942,8943,2214,8944,8945,8946, # 8704 8947,8948,8949,8950,8951,8952,8953,8954,8955,8956,8957,8958,8959,8960,8961,8962, # 8720 8963,8964,8965,4884,8966,8967,8968,8969,8970,8971,8972,8973,8974,8975,8976,8977, # 8736 8978,8979,8980,8981,8982,8983,8984,8985,8986,8987,8988,8989,8990,8991,8992,4885, # 8752 8993,8994,8995,8996,8997,8998,8999,9000,9001,9002,9003,9004,9005,9006,9007,9008, # 8768 9009,9010,9011,9012,9013,9014,9015,9016,9017,9018,9019,9020,9021,4182,9022,9023, # 8784 9024,9025,9026,9027,9028,9029,9030,9031,9032,9033,9034,9035,9036,9037,9038,9039, # 8800 9040,9041,9042,9043,9044,9045,9046,9047,9048,9049,9050,9051,9052,9053,9054,9055, # 8816 9056,9057,9058,9059,9060,9061,9062,9063,4886,9064,9065,9066,9067,9068,9069,4887, # 8832 9070,9071,9072,9073,9074,9075,9076,9077,9078,9079,9080,9081,9082,9083,9084,9085, # 8848 9086,9087,9088,9089,9090,9091,9092,9093,9094,9095,9096,9097,9098,9099,9100,9101, # 8864 9102,9103,9104,9105,9106,9107,9108,9109,9110,9111,9112,9113,9114,9115,9116,9117, # 8880 9118,9119,9120,9121,9122,9123,9124,9125,9126,9127,9128,9129,9130,9131,9132,9133, # 8896 9134,9135,9136,9137,9138,9139,9140,9141,3958,9142,9143,9144,9145,9146,9147,9148, # 8912 9149,9150,9151,4888,9152,9153,9154,9155,9156,9157,9158,9159,9160,9161,9162,9163, # 8928 9164,9165,9166,9167,9168,9169,9170,9171,9172,9173,9174,9175,4889,9176,9177,9178, # 8944 9179,9180,9181,9182,9183,9184,9185,9186,9187,9188,9189,9190,9191,9192,9193,9194, # 8960 9195,9196,9197,9198,9199,9200,9201,9202,9203,4890,9204,9205,9206,9207,9208,9209, # 8976 9210,9211,9212,9213,9214,9215,9216,9217,9218,9219,9220,9221,9222,4466,9223,9224, # 8992 9225,9226,9227,9228,9229,9230,9231,9232,9233,9234,9235,9236,9237,9238,9239,9240, # 9008 9241,9242,9243,9244,9245,4891,9246,9247,9248,9249,9250,9251,9252,9253,9254,9255, # 9024 9256,9257,4892,9258,9259,9260,9261,4893,4894,9262,9263,9264,9265,9266,9267,9268, # 9040 9269,9270,9271,9272,9273,4467,9274,9275,9276,9277,9278,9279,9280,9281,9282,9283, # 9056 9284,9285,3673,9286,9287,9288,9289,9290,9291,9292,9293,9294,9295,9296,9297,9298, # 9072 9299,9300,9301,9302,9303,9304,9305,9306,9307,9308,9309,9310,9311,9312,9313,9314, # 9088 9315,9316,9317,9318,9319,9320,9321,9322,4895,9323,9324,9325,9326,9327,9328,9329, # 9104 9330,9331,9332,9333,9334,9335,9336,9337,9338,9339,9340,9341,9342,9343,9344,9345, # 9120 9346,9347,4468,9348,9349,9350,9351,9352,9353,9354,9355,9356,9357,9358,9359,9360, # 9136 9361,9362,9363,9364,9365,9366,9367,9368,9369,9370,9371,9372,9373,4896,9374,4469, # 9152 9375,9376,9377,9378,9379,4897,9380,9381,9382,9383,9384,9385,9386,9387,9388,9389, # 9168 9390,9391,9392,9393,9394,9395,9396,9397,9398,9399,9400,9401,9402,9403,9404,9405, # 9184 9406,4470,9407,2751,9408,9409,3674,3552,9410,9411,9412,9413,9414,9415,9416,9417, # 9200 9418,9419,9420,9421,4898,9422,9423,9424,9425,9426,9427,9428,9429,3959,9430,9431, # 9216 9432,9433,9434,9435,9436,4471,9437,9438,9439,9440,9441,9442,9443,9444,9445,9446, # 9232 9447,9448,9449,9450,3348,9451,9452,9453,9454,9455,9456,9457,9458,9459,9460,9461, # 9248 9462,9463,9464,9465,9466,9467,9468,9469,9470,9471,9472,4899,9473,9474,9475,9476, # 9264 9477,4900,9478,9479,9480,9481,9482,9483,9484,9485,9486,9487,9488,3349,9489,9490, # 9280 9491,9492,9493,9494,9495,9496,9497,9498,9499,9500,9501,9502,9503,9504,9505,9506, # 9296 9507,9508,9509,9510,9511,9512,9513,9514,9515,9516,9517,9518,9519,9520,4901,9521, # 9312 9522,9523,9524,9525,9526,4902,9527,9528,9529,9530,9531,9532,9533,9534,9535,9536, # 9328 9537,9538,9539,9540,9541,9542,9543,9544,9545,9546,9547,9548,9549,9550,9551,9552, # 9344 9553,9554,9555,9556,9557,9558,9559,9560,9561,9562,9563,9564,9565,9566,9567,9568, # 9360 9569,9570,9571,9572,9573,9574,9575,9576,9577,9578,9579,9580,9581,9582,9583,9584, # 9376 3805,9585,9586,9587,9588,9589,9590,9591,9592,9593,9594,9595,9596,9597,9598,9599, # 9392 9600,9601,9602,4903,9603,9604,9605,9606,9607,4904,9608,9609,9610,9611,9612,9613, # 9408 9614,4905,9615,9616,9617,9618,9619,9620,9621,9622,9623,9624,9625,9626,9627,9628, # 9424 9629,9630,9631,9632,4906,9633,9634,9635,9636,9637,9638,9639,9640,9641,9642,9643, # 9440 4907,9644,9645,9646,9647,9648,9649,9650,9651,9652,9653,9654,9655,9656,9657,9658, # 9456 9659,9660,9661,9662,9663,9664,9665,9666,9667,9668,9669,9670,9671,9672,4183,9673, # 9472 9674,9675,9676,9677,4908,9678,9679,9680,9681,4909,9682,9683,9684,9685,9686,9687, # 9488 9688,9689,9690,4910,9691,9692,9693,3675,9694,9695,9696,2945,9697,9698,9699,9700, # 9504 9701,9702,9703,9704,9705,4911,9706,9707,9708,9709,9710,9711,9712,9713,9714,9715, # 9520 9716,9717,9718,9719,9720,9721,9722,9723,9724,9725,9726,9727,9728,9729,9730,9731, # 9536 9732,9733,9734,9735,4912,9736,9737,9738,9739,9740,4913,9741,9742,9743,9744,9745, # 9552 9746,9747,9748,9749,9750,9751,9752,9753,9754,9755,9756,9757,9758,4914,9759,9760, # 9568 9761,9762,9763,9764,9765,9766,9767,9768,9769,9770,9771,9772,9773,9774,9775,9776, # 9584 9777,9778,9779,9780,9781,9782,4915,9783,9784,9785,9786,9787,9788,9789,9790,9791, # 9600 9792,9793,4916,9794,9795,9796,9797,9798,9799,9800,9801,9802,9803,9804,9805,9806, # 9616 9807,9808,9809,9810,9811,9812,9813,9814,9815,9816,9817,9818,9819,9820,9821,9822, # 9632 9823,9824,9825,9826,9827,9828,9829,9830,9831,9832,9833,9834,9835,9836,9837,9838, # 9648 9839,9840,9841,9842,9843,9844,9845,9846,9847,9848,9849,9850,9851,9852,9853,9854, # 9664 9855,9856,9857,9858,9859,9860,9861,9862,9863,9864,9865,9866,9867,9868,4917,9869, # 9680 9870,9871,9872,9873,9874,9875,9876,9877,9878,9879,9880,9881,9882,9883,9884,9885, # 9696 9886,9887,9888,9889,9890,9891,9892,4472,9893,9894,9895,9896,9897,3806,9898,9899, # 9712 9900,9901,9902,9903,9904,9905,9906,9907,9908,9909,9910,9911,9912,9913,9914,4918, # 9728 9915,9916,9917,4919,9918,9919,9920,9921,4184,9922,9923,9924,9925,9926,9927,9928, # 9744 9929,9930,9931,9932,9933,9934,9935,9936,9937,9938,9939,9940,9941,9942,9943,9944, # 9760 9945,9946,4920,9947,9948,9949,9950,9951,9952,9953,9954,9955,4185,9956,9957,9958, # 9776 9959,9960,9961,9962,9963,9964,9965,4921,9966,9967,9968,4473,9969,9970,9971,9972, # 9792 9973,9974,9975,9976,9977,4474,9978,9979,9980,9981,9982,9983,9984,9985,9986,9987, # 9808 9988,9989,9990,9991,9992,9993,9994,9995,9996,9997,9998,9999,10000,10001,10002,10003, # 9824 10004,10005,10006,10007,10008,10009,10010,10011,10012,10013,10014,10015,10016,10017,10018,10019, # 9840 10020,10021,4922,10022,4923,10023,10024,10025,10026,10027,10028,10029,10030,10031,10032,10033, # 9856 10034,10035,10036,10037,10038,10039,10040,10041,10042,10043,10044,10045,10046,10047,10048,4924, # 9872 10049,10050,10051,10052,10053,10054,10055,10056,10057,10058,10059,10060,10061,10062,10063,10064, # 9888 10065,10066,10067,10068,10069,10070,10071,10072,10073,10074,10075,10076,10077,10078,10079,10080, # 9904 10081,10082,10083,10084,10085,10086,10087,4475,10088,10089,10090,10091,10092,10093,10094,10095, # 9920 10096,10097,4476,10098,10099,10100,10101,10102,10103,10104,10105,10106,10107,10108,10109,10110, # 9936 10111,2174,10112,10113,10114,10115,10116,10117,10118,10119,10120,10121,10122,10123,10124,10125, # 9952 10126,10127,10128,10129,10130,10131,10132,10133,10134,10135,10136,10137,10138,10139,10140,3807, # 9968 4186,4925,10141,10142,10143,10144,10145,10146,10147,4477,4187,10148,10149,10150,10151,10152, # 9984 10153,4188,10154,10155,10156,10157,10158,10159,10160,10161,4926,10162,10163,10164,10165,10166, #10000 10167,10168,10169,10170,10171,10172,10173,10174,10175,10176,10177,10178,10179,10180,10181,10182, #10016 10183,10184,10185,10186,10187,10188,10189,10190,10191,10192,3203,10193,10194,10195,10196,10197, #10032 10198,10199,10200,4478,10201,10202,10203,10204,4479,10205,10206,10207,10208,10209,10210,10211, #10048 10212,10213,10214,10215,10216,10217,10218,10219,10220,10221,10222,10223,10224,10225,10226,10227, #10064 10228,10229,10230,10231,10232,10233,10234,4927,10235,10236,10237,10238,10239,10240,10241,10242, #10080 10243,10244,10245,10246,10247,10248,10249,10250,10251,10252,10253,10254,10255,10256,10257,10258, #10096 10259,10260,10261,10262,10263,10264,10265,10266,10267,10268,10269,10270,10271,10272,10273,4480, #10112 4928,4929,10274,10275,10276,10277,10278,10279,10280,10281,10282,10283,10284,10285,10286,10287, #10128 10288,10289,10290,10291,10292,10293,10294,10295,10296,10297,10298,10299,10300,10301,10302,10303, #10144 10304,10305,10306,10307,10308,10309,10310,10311,10312,10313,10314,10315,10316,10317,10318,10319, #10160 10320,10321,10322,10323,10324,10325,10326,10327,10328,10329,10330,10331,10332,10333,10334,4930, #10176 10335,10336,10337,10338,10339,10340,10341,10342,4931,10343,10344,10345,10346,10347,10348,10349, #10192 10350,10351,10352,10353,10354,10355,3088,10356,2786,10357,10358,10359,10360,4189,10361,10362, #10208 10363,10364,10365,10366,10367,10368,10369,10370,10371,10372,10373,10374,10375,4932,10376,10377, #10224 10378,10379,10380,10381,10382,10383,10384,10385,10386,10387,10388,10389,10390,10391,10392,4933, #10240 10393,10394,10395,4934,10396,10397,10398,10399,10400,10401,10402,10403,10404,10405,10406,10407, #10256 10408,10409,10410,10411,10412,3446,10413,10414,10415,10416,10417,10418,10419,10420,10421,10422, #10272 10423,4935,10424,10425,10426,10427,10428,10429,10430,4936,10431,10432,10433,10434,10435,10436, #10288 10437,10438,10439,10440,10441,10442,10443,4937,10444,10445,10446,10447,4481,10448,10449,10450, #10304 10451,10452,10453,10454,10455,10456,10457,10458,10459,10460,10461,10462,10463,10464,10465,10466, #10320 10467,10468,10469,10470,10471,10472,10473,10474,10475,10476,10477,10478,10479,10480,10481,10482, #10336 10483,10484,10485,10486,10487,10488,10489,10490,10491,10492,10493,10494,10495,10496,10497,10498, #10352 10499,10500,10501,10502,10503,10504,10505,4938,10506,10507,10508,10509,10510,2552,10511,10512, #10368 10513,10514,10515,10516,3447,10517,10518,10519,10520,10521,10522,10523,10524,10525,10526,10527, #10384 10528,10529,10530,10531,10532,10533,10534,10535,10536,10537,10538,10539,10540,10541,10542,10543, #10400 4482,10544,4939,10545,10546,10547,10548,10549,10550,10551,10552,10553,10554,10555,10556,10557, #10416 10558,10559,10560,10561,10562,10563,10564,10565,10566,10567,3676,4483,10568,10569,10570,10571, #10432 10572,3448,10573,10574,10575,10576,10577,10578,10579,10580,10581,10582,10583,10584,10585,10586, #10448 10587,10588,10589,10590,10591,10592,10593,10594,10595,10596,10597,10598,10599,10600,10601,10602, #10464 10603,10604,10605,10606,10607,10608,10609,10610,10611,10612,10613,10614,10615,10616,10617,10618, #10480 10619,10620,10621,10622,10623,10624,10625,10626,10627,4484,10628,10629,10630,10631,10632,4940, #10496 10633,10634,10635,10636,10637,10638,10639,10640,10641,10642,10643,10644,10645,10646,10647,10648, #10512 10649,10650,10651,10652,10653,10654,10655,10656,4941,10657,10658,10659,2599,10660,10661,10662, #10528 10663,10664,10665,10666,3089,10667,10668,10669,10670,10671,10672,10673,10674,10675,10676,10677, #10544 10678,10679,10680,4942,10681,10682,10683,10684,10685,10686,10687,10688,10689,10690,10691,10692, #10560 10693,10694,10695,10696,10697,4485,10698,10699,10700,10701,10702,10703,10704,4943,10705,3677, #10576 10706,10707,10708,10709,10710,10711,10712,4944,10713,10714,10715,10716,10717,10718,10719,10720, #10592 10721,10722,10723,10724,10725,10726,10727,10728,4945,10729,10730,10731,10732,10733,10734,10735, #10608 10736,10737,10738,10739,10740,10741,10742,10743,10744,10745,10746,10747,10748,10749,10750,10751, #10624 10752,10753,10754,10755,10756,10757,10758,10759,10760,10761,4946,10762,10763,10764,10765,10766, #10640 10767,4947,4948,10768,10769,10770,10771,10772,10773,10774,10775,10776,10777,10778,10779,10780, #10656 10781,10782,10783,10784,10785,10786,10787,10788,10789,10790,10791,10792,10793,10794,10795,10796, #10672 10797,10798,10799,10800,10801,10802,10803,10804,10805,10806,10807,10808,10809,10810,10811,10812, #10688 10813,10814,10815,10816,10817,10818,10819,10820,10821,10822,10823,10824,10825,10826,10827,10828, #10704 10829,10830,10831,10832,10833,10834,10835,10836,10837,10838,10839,10840,10841,10842,10843,10844, #10720 10845,10846,10847,10848,10849,10850,10851,10852,10853,10854,10855,10856,10857,10858,10859,10860, #10736 10861,10862,10863,10864,10865,10866,10867,10868,10869,10870,10871,10872,10873,10874,10875,10876, #10752 10877,10878,4486,10879,10880,10881,10882,10883,10884,10885,4949,10886,10887,10888,10889,10890, #10768 10891,10892,10893,10894,10895,10896,10897,10898,10899,10900,10901,10902,10903,10904,10905,10906, #10784 10907,10908,10909,10910,10911,10912,10913,10914,10915,10916,10917,10918,10919,4487,10920,10921, #10800 10922,10923,10924,10925,10926,10927,10928,10929,10930,10931,10932,4950,10933,10934,10935,10936, #10816 10937,10938,10939,10940,10941,10942,10943,10944,10945,10946,10947,10948,10949,4488,10950,10951, #10832 10952,10953,10954,10955,10956,10957,10958,10959,4190,10960,10961,10962,10963,10964,10965,10966, #10848 10967,10968,10969,10970,10971,10972,10973,10974,10975,10976,10977,10978,10979,10980,10981,10982, #10864 10983,10984,10985,10986,10987,10988,10989,10990,10991,10992,10993,10994,10995,10996,10997,10998, #10880 10999,11000,11001,11002,11003,11004,11005,11006,3960,11007,11008,11009,11010,11011,11012,11013, #10896 11014,11015,11016,11017,11018,11019,11020,11021,11022,11023,11024,11025,11026,11027,11028,11029, #10912 11030,11031,11032,4951,11033,11034,11035,11036,11037,11038,11039,11040,11041,11042,11043,11044, #10928 11045,11046,11047,4489,11048,11049,11050,11051,4952,11052,11053,11054,11055,11056,11057,11058, #10944 4953,11059,11060,11061,11062,11063,11064,11065,11066,11067,11068,11069,11070,11071,4954,11072, #10960 11073,11074,11075,11076,11077,11078,11079,11080,11081,11082,11083,11084,11085,11086,11087,11088, #10976 11089,11090,11091,11092,11093,11094,11095,11096,11097,11098,11099,11100,11101,11102,11103,11104, #10992 11105,11106,11107,11108,11109,11110,11111,11112,11113,11114,11115,3808,11116,11117,11118,11119, #11008 11120,11121,11122,11123,11124,11125,11126,11127,11128,11129,11130,11131,11132,11133,11134,4955, #11024 11135,11136,11137,11138,11139,11140,11141,11142,11143,11144,11145,11146,11147,11148,11149,11150, #11040 11151,11152,11153,11154,11155,11156,11157,11158,11159,11160,11161,4956,11162,11163,11164,11165, #11056 11166,11167,11168,11169,11170,11171,11172,11173,11174,11175,11176,11177,11178,11179,11180,4957, #11072 11181,11182,11183,11184,11185,11186,4958,11187,11188,11189,11190,11191,11192,11193,11194,11195, #11088 11196,11197,11198,11199,11200,3678,11201,11202,11203,11204,11205,11206,4191,11207,11208,11209, #11104 11210,11211,11212,11213,11214,11215,11216,11217,11218,11219,11220,11221,11222,11223,11224,11225, #11120 11226,11227,11228,11229,11230,11231,11232,11233,11234,11235,11236,11237,11238,11239,11240,11241, #11136 11242,11243,11244,11245,11246,11247,11248,11249,11250,11251,4959,11252,11253,11254,11255,11256, #11152 11257,11258,11259,11260,11261,11262,11263,11264,11265,11266,11267,11268,11269,11270,11271,11272, #11168 11273,11274,11275,11276,11277,11278,11279,11280,11281,11282,11283,11284,11285,11286,11287,11288, #11184 11289,11290,11291,11292,11293,11294,11295,11296,11297,11298,11299,11300,11301,11302,11303,11304, #11200 11305,11306,11307,11308,11309,11310,11311,11312,11313,11314,3679,11315,11316,11317,11318,4490, #11216 11319,11320,11321,11322,11323,11324,11325,11326,11327,11328,11329,11330,11331,11332,11333,11334, #11232 11335,11336,11337,11338,11339,11340,11341,11342,11343,11344,11345,11346,11347,4960,11348,11349, #11248 11350,11351,11352,11353,11354,11355,11356,11357,11358,11359,11360,11361,11362,11363,11364,11365, #11264 11366,11367,11368,11369,11370,11371,11372,11373,11374,11375,11376,11377,3961,4961,11378,11379, #11280 11380,11381,11382,11383,11384,11385,11386,11387,11388,11389,11390,11391,11392,11393,11394,11395, #11296 11396,11397,4192,11398,11399,11400,11401,11402,11403,11404,11405,11406,11407,11408,11409,11410, #11312 11411,4962,11412,11413,11414,11415,11416,11417,11418,11419,11420,11421,11422,11423,11424,11425, #11328 11426,11427,11428,11429,11430,11431,11432,11433,11434,11435,11436,11437,11438,11439,11440,11441, #11344 11442,11443,11444,11445,11446,11447,11448,11449,11450,11451,11452,11453,11454,11455,11456,11457, #11360 11458,11459,11460,11461,11462,11463,11464,11465,11466,11467,11468,11469,4963,11470,11471,4491, #11376 11472,11473,11474,11475,4964,11476,11477,11478,11479,11480,11481,11482,11483,11484,11485,11486, #11392 11487,11488,11489,11490,11491,11492,4965,11493,11494,11495,11496,11497,11498,11499,11500,11501, #11408 11502,11503,11504,11505,11506,11507,11508,11509,11510,11511,11512,11513,11514,11515,11516,11517, #11424 11518,11519,11520,11521,11522,11523,11524,11525,11526,11527,11528,11529,3962,11530,11531,11532, #11440 11533,11534,11535,11536,11537,11538,11539,11540,11541,11542,11543,11544,11545,11546,11547,11548, #11456 11549,11550,11551,11552,11553,11554,11555,11556,11557,11558,11559,11560,11561,11562,11563,11564, #11472 4193,4194,11565,11566,11567,11568,11569,11570,11571,11572,11573,11574,11575,11576,11577,11578, #11488 11579,11580,11581,11582,11583,11584,11585,11586,11587,11588,11589,11590,11591,4966,4195,11592, #11504 11593,11594,11595,11596,11597,11598,11599,11600,11601,11602,11603,11604,3090,11605,11606,11607, #11520 11608,11609,11610,4967,11611,11612,11613,11614,11615,11616,11617,11618,11619,11620,11621,11622, #11536 11623,11624,11625,11626,11627,11628,11629,11630,11631,11632,11633,11634,11635,11636,11637,11638, #11552 11639,11640,11641,11642,11643,11644,11645,11646,11647,11648,11649,11650,11651,11652,11653,11654, #11568 11655,11656,11657,11658,11659,11660,11661,11662,11663,11664,11665,11666,11667,11668,11669,11670, #11584 11671,11672,11673,11674,4968,11675,11676,11677,11678,11679,11680,11681,11682,11683,11684,11685, #11600 11686,11687,11688,11689,11690,11691,11692,11693,3809,11694,11695,11696,11697,11698,11699,11700, #11616 11701,11702,11703,11704,11705,11706,11707,11708,11709,11710,11711,11712,11713,11714,11715,11716, #11632 11717,11718,3553,11719,11720,11721,11722,11723,11724,11725,11726,11727,11728,11729,11730,4969, #11648 11731,11732,11733,11734,11735,11736,11737,11738,11739,11740,4492,11741,11742,11743,11744,11745, #11664 11746,11747,11748,11749,11750,11751,11752,4970,11753,11754,11755,11756,11757,11758,11759,11760, #11680 11761,11762,11763,11764,11765,11766,11767,11768,11769,11770,11771,11772,11773,11774,11775,11776, #11696 11777,11778,11779,11780,11781,11782,11783,11784,11785,11786,11787,11788,11789,11790,4971,11791, #11712 11792,11793,11794,11795,11796,11797,4972,11798,11799,11800,11801,11802,11803,11804,11805,11806, #11728 11807,11808,11809,11810,4973,11811,11812,11813,11814,11815,11816,11817,11818,11819,11820,11821, #11744 11822,11823,11824,11825,11826,11827,11828,11829,11830,11831,11832,11833,11834,3680,3810,11835, #11760 11836,4974,11837,11838,11839,11840,11841,11842,11843,11844,11845,11846,11847,11848,11849,11850, #11776 11851,11852,11853,11854,11855,11856,11857,11858,11859,11860,11861,11862,11863,11864,11865,11866, #11792 11867,11868,11869,11870,11871,11872,11873,11874,11875,11876,11877,11878,11879,11880,11881,11882, #11808 11883,11884,4493,11885,11886,11887,11888,11889,11890,11891,11892,11893,11894,11895,11896,11897, #11824 11898,11899,11900,11901,11902,11903,11904,11905,11906,11907,11908,11909,11910,11911,11912,11913, #11840 11914,11915,4975,11916,11917,11918,11919,11920,11921,11922,11923,11924,11925,11926,11927,11928, #11856 11929,11930,11931,11932,11933,11934,11935,11936,11937,11938,11939,11940,11941,11942,11943,11944, #11872 11945,11946,11947,11948,11949,4976,11950,11951,11952,11953,11954,11955,11956,11957,11958,11959, #11888 11960,11961,11962,11963,11964,11965,11966,11967,11968,11969,11970,11971,11972,11973,11974,11975, #11904 11976,11977,11978,11979,11980,11981,11982,11983,11984,11985,11986,11987,4196,11988,11989,11990, #11920 11991,11992,4977,11993,11994,11995,11996,11997,11998,11999,12000,12001,12002,12003,12004,12005, #11936 12006,12007,12008,12009,12010,12011,12012,12013,12014,12015,12016,12017,12018,12019,12020,12021, #11952 12022,12023,12024,12025,12026,12027,12028,12029,12030,12031,12032,12033,12034,12035,12036,12037, #11968 12038,12039,12040,12041,12042,12043,12044,12045,12046,12047,12048,12049,12050,12051,12052,12053, #11984 12054,12055,12056,12057,12058,12059,12060,12061,4978,12062,12063,12064,12065,12066,12067,12068, #12000 12069,12070,12071,12072,12073,12074,12075,12076,12077,12078,12079,12080,12081,12082,12083,12084, #12016 12085,12086,12087,12088,12089,12090,12091,12092,12093,12094,12095,12096,12097,12098,12099,12100, #12032 12101,12102,12103,12104,12105,12106,12107,12108,12109,12110,12111,12112,12113,12114,12115,12116, #12048 12117,12118,12119,12120,12121,12122,12123,4979,12124,12125,12126,12127,12128,4197,12129,12130, #12064 12131,12132,12133,12134,12135,12136,12137,12138,12139,12140,12141,12142,12143,12144,12145,12146, #12080 12147,12148,12149,12150,12151,12152,12153,12154,4980,12155,12156,12157,12158,12159,12160,4494, #12096 12161,12162,12163,12164,3811,12165,12166,12167,12168,12169,4495,12170,12171,4496,12172,12173, #12112 12174,12175,12176,3812,12177,12178,12179,12180,12181,12182,12183,12184,12185,12186,12187,12188, #12128 12189,12190,12191,12192,12193,12194,12195,12196,12197,12198,12199,12200,12201,12202,12203,12204, #12144 12205,12206,12207,12208,12209,12210,12211,12212,12213,12214,12215,12216,12217,12218,12219,12220, #12160 12221,4981,12222,12223,12224,12225,12226,12227,12228,12229,12230,12231,12232,12233,12234,12235, #12176 4982,12236,12237,12238,12239,12240,12241,12242,12243,12244,12245,4983,12246,12247,12248,12249, #12192 4984,12250,12251,12252,12253,12254,12255,12256,12257,12258,12259,12260,12261,12262,12263,12264, #12208 4985,12265,4497,12266,12267,12268,12269,12270,12271,12272,12273,12274,12275,12276,12277,12278, #12224 12279,12280,12281,12282,12283,12284,12285,12286,12287,4986,12288,12289,12290,12291,12292,12293, #12240 12294,12295,12296,2473,12297,12298,12299,12300,12301,12302,12303,12304,12305,12306,12307,12308, #12256 12309,12310,12311,12312,12313,12314,12315,12316,12317,12318,12319,3963,12320,12321,12322,12323, #12272 12324,12325,12326,12327,12328,12329,12330,12331,12332,4987,12333,12334,12335,12336,12337,12338, #12288 12339,12340,12341,12342,12343,12344,12345,12346,12347,12348,12349,12350,12351,12352,12353,12354, #12304 12355,12356,12357,12358,12359,3964,12360,12361,12362,12363,12364,12365,12366,12367,12368,12369, #12320 12370,3965,12371,12372,12373,12374,12375,12376,12377,12378,12379,12380,12381,12382,12383,12384, #12336 12385,12386,12387,12388,12389,12390,12391,12392,12393,12394,12395,12396,12397,12398,12399,12400, #12352 12401,12402,12403,12404,12405,12406,12407,12408,4988,12409,12410,12411,12412,12413,12414,12415, #12368 12416,12417,12418,12419,12420,12421,12422,12423,12424,12425,12426,12427,12428,12429,12430,12431, #12384 12432,12433,12434,12435,12436,12437,12438,3554,12439,12440,12441,12442,12443,12444,12445,12446, #12400 12447,12448,12449,12450,12451,12452,12453,12454,12455,12456,12457,12458,12459,12460,12461,12462, #12416 12463,12464,4989,12465,12466,12467,12468,12469,12470,12471,12472,12473,12474,12475,12476,12477, #12432 12478,12479,12480,4990,12481,12482,12483,12484,12485,12486,12487,12488,12489,4498,12490,12491, #12448 12492,12493,12494,12495,12496,12497,12498,12499,12500,12501,12502,12503,12504,12505,12506,12507, #12464 12508,12509,12510,12511,12512,12513,12514,12515,12516,12517,12518,12519,12520,12521,12522,12523, #12480 12524,12525,12526,12527,12528,12529,12530,12531,12532,12533,12534,12535,12536,12537,12538,12539, #12496 12540,12541,12542,12543,12544,12545,12546,12547,12548,12549,12550,12551,4991,12552,12553,12554, #12512 12555,12556,12557,12558,12559,12560,12561,12562,12563,12564,12565,12566,12567,12568,12569,12570, #12528 12571,12572,12573,12574,12575,12576,12577,12578,3036,12579,12580,12581,12582,12583,3966,12584, #12544 12585,12586,12587,12588,12589,12590,12591,12592,12593,12594,12595,12596,12597,12598,12599,12600, #12560 12601,12602,12603,12604,12605,12606,12607,12608,12609,12610,12611,12612,12613,12614,12615,12616, #12576 12617,12618,12619,12620,12621,12622,12623,12624,12625,12626,12627,12628,12629,12630,12631,12632, #12592 12633,12634,12635,12636,12637,12638,12639,12640,12641,12642,12643,12644,12645,12646,4499,12647, #12608 12648,12649,12650,12651,12652,12653,12654,12655,12656,12657,12658,12659,12660,12661,12662,12663, #12624 12664,12665,12666,12667,12668,12669,12670,12671,12672,12673,12674,12675,12676,12677,12678,12679, #12640 12680,12681,12682,12683,12684,12685,12686,12687,12688,12689,12690,12691,12692,12693,12694,12695, #12656 12696,12697,12698,4992,12699,12700,12701,12702,12703,12704,12705,12706,12707,12708,12709,12710, #12672 12711,12712,12713,12714,12715,12716,12717,12718,12719,12720,12721,12722,12723,12724,12725,12726, #12688 12727,12728,12729,12730,12731,12732,12733,12734,12735,12736,12737,12738,12739,12740,12741,12742, #12704 12743,12744,12745,12746,12747,12748,12749,12750,12751,12752,12753,12754,12755,12756,12757,12758, #12720 12759,12760,12761,12762,12763,12764,12765,12766,12767,12768,12769,12770,12771,12772,12773,12774, #12736 12775,12776,12777,12778,4993,2175,12779,12780,12781,12782,12783,12784,12785,12786,4500,12787, #12752 12788,12789,12790,12791,12792,12793,12794,12795,12796,12797,12798,12799,12800,12801,12802,12803, #12768 12804,12805,12806,12807,12808,12809,12810,12811,12812,12813,12814,12815,12816,12817,12818,12819, #12784 12820,12821,12822,12823,12824,12825,12826,4198,3967,12827,12828,12829,12830,12831,12832,12833, #12800 12834,12835,12836,12837,12838,12839,12840,12841,12842,12843,12844,12845,12846,12847,12848,12849, #12816 12850,12851,12852,12853,12854,12855,12856,12857,12858,12859,12860,12861,4199,12862,12863,12864, #12832 12865,12866,12867,12868,12869,12870,12871,12872,12873,12874,12875,12876,12877,12878,12879,12880, #12848 12881,12882,12883,12884,12885,12886,12887,4501,12888,12889,12890,12891,12892,12893,12894,12895, #12864 12896,12897,12898,12899,12900,12901,12902,12903,12904,12905,12906,12907,12908,12909,12910,12911, #12880 12912,4994,12913,12914,12915,12916,12917,12918,12919,12920,12921,12922,12923,12924,12925,12926, #12896 12927,12928,12929,12930,12931,12932,12933,12934,12935,12936,12937,12938,12939,12940,12941,12942, #12912 12943,12944,12945,12946,12947,12948,12949,12950,12951,12952,12953,12954,12955,12956,1772,12957, #12928 12958,12959,12960,12961,12962,12963,12964,12965,12966,12967,12968,12969,12970,12971,12972,12973, #12944 12974,12975,12976,12977,12978,12979,12980,12981,12982,12983,12984,12985,12986,12987,12988,12989, #12960 12990,12991,12992,12993,12994,12995,12996,12997,4502,12998,4503,12999,13000,13001,13002,13003, #12976 4504,13004,13005,13006,13007,13008,13009,13010,13011,13012,13013,13014,13015,13016,13017,13018, #12992 13019,13020,13021,13022,13023,13024,13025,13026,13027,13028,13029,3449,13030,13031,13032,13033, #13008 13034,13035,13036,13037,13038,13039,13040,13041,13042,13043,13044,13045,13046,13047,13048,13049, #13024 13050,13051,13052,13053,13054,13055,13056,13057,13058,13059,13060,13061,13062,13063,13064,13065, #13040 13066,13067,13068,13069,13070,13071,13072,13073,13074,13075,13076,13077,13078,13079,13080,13081, #13056 13082,13083,13084,13085,13086,13087,13088,13089,13090,13091,13092,13093,13094,13095,13096,13097, #13072 13098,13099,13100,13101,13102,13103,13104,13105,13106,13107,13108,13109,13110,13111,13112,13113, #13088 13114,13115,13116,13117,13118,3968,13119,4995,13120,13121,13122,13123,13124,13125,13126,13127, #13104 4505,13128,13129,13130,13131,13132,13133,13134,4996,4506,13135,13136,13137,13138,13139,4997, #13120 13140,13141,13142,13143,13144,13145,13146,13147,13148,13149,13150,13151,13152,13153,13154,13155, #13136 13156,13157,13158,13159,4998,13160,13161,13162,13163,13164,13165,13166,13167,13168,13169,13170, #13152 13171,13172,13173,13174,13175,13176,4999,13177,13178,13179,13180,13181,13182,13183,13184,13185, #13168 13186,13187,13188,13189,13190,13191,13192,13193,13194,13195,13196,13197,13198,13199,13200,13201, #13184 13202,13203,13204,13205,13206,5000,13207,13208,13209,13210,13211,13212,13213,13214,13215,13216, #13200 13217,13218,13219,13220,13221,13222,13223,13224,13225,13226,13227,4200,5001,13228,13229,13230, #13216 13231,13232,13233,13234,13235,13236,13237,13238,13239,13240,3969,13241,13242,13243,13244,3970, #13232 13245,13246,13247,13248,13249,13250,13251,13252,13253,13254,13255,13256,13257,13258,13259,13260, #13248 13261,13262,13263,13264,13265,13266,13267,13268,3450,13269,13270,13271,13272,13273,13274,13275, #13264 13276,5002,13277,13278,13279,13280,13281,13282,13283,13284,13285,13286,13287,13288,13289,13290, #13280 13291,13292,13293,13294,13295,13296,13297,13298,13299,13300,13301,13302,3813,13303,13304,13305, #13296 13306,13307,13308,13309,13310,13311,13312,13313,13314,13315,13316,13317,13318,13319,13320,13321, #13312 13322,13323,13324,13325,13326,13327,13328,4507,13329,13330,13331,13332,13333,13334,13335,13336, #13328 13337,13338,13339,13340,13341,5003,13342,13343,13344,13345,13346,13347,13348,13349,13350,13351, #13344 13352,13353,13354,13355,13356,13357,13358,13359,13360,13361,13362,13363,13364,13365,13366,13367, #13360 5004,13368,13369,13370,13371,13372,13373,13374,13375,13376,13377,13378,13379,13380,13381,13382, #13376 13383,13384,13385,13386,13387,13388,13389,13390,13391,13392,13393,13394,13395,13396,13397,13398, #13392 13399,13400,13401,13402,13403,13404,13405,13406,13407,13408,13409,13410,13411,13412,13413,13414, #13408 13415,13416,13417,13418,13419,13420,13421,13422,13423,13424,13425,13426,13427,13428,13429,13430, #13424 13431,13432,4508,13433,13434,13435,4201,13436,13437,13438,13439,13440,13441,13442,13443,13444, #13440 13445,13446,13447,13448,13449,13450,13451,13452,13453,13454,13455,13456,13457,5005,13458,13459, #13456 13460,13461,13462,13463,13464,13465,13466,13467,13468,13469,13470,4509,13471,13472,13473,13474, #13472 13475,13476,13477,13478,13479,13480,13481,13482,13483,13484,13485,13486,13487,13488,13489,13490, #13488 13491,13492,13493,13494,13495,13496,13497,13498,13499,13500,13501,13502,13503,13504,13505,13506, #13504 13507,13508,13509,13510,13511,13512,13513,13514,13515,13516,13517,13518,13519,13520,13521,13522, #13520 13523,13524,13525,13526,13527,13528,13529,13530,13531,13532,13533,13534,13535,13536,13537,13538, #13536 13539,13540,13541,13542,13543,13544,13545,13546,13547,13548,13549,13550,13551,13552,13553,13554, #13552 13555,13556,13557,13558,13559,13560,13561,13562,13563,13564,13565,13566,13567,13568,13569,13570, #13568 13571,13572,13573,13574,13575,13576,13577,13578,13579,13580,13581,13582,13583,13584,13585,13586, #13584 13587,13588,13589,13590,13591,13592,13593,13594,13595,13596,13597,13598,13599,13600,13601,13602, #13600 13603,13604,13605,13606,13607,13608,13609,13610,13611,13612,13613,13614,13615,13616,13617,13618, #13616 13619,13620,13621,13622,13623,13624,13625,13626,13627,13628,13629,13630,13631,13632,13633,13634, #13632 13635,13636,13637,13638,13639,13640,13641,13642,5006,13643,13644,13645,13646,13647,13648,13649, #13648 13650,13651,5007,13652,13653,13654,13655,13656,13657,13658,13659,13660,13661,13662,13663,13664, #13664 13665,13666,13667,13668,13669,13670,13671,13672,13673,13674,13675,13676,13677,13678,13679,13680, #13680 13681,13682,13683,13684,13685,13686,13687,13688,13689,13690,13691,13692,13693,13694,13695,13696, #13696 13697,13698,13699,13700,13701,13702,13703,13704,13705,13706,13707,13708,13709,13710,13711,13712, #13712 13713,13714,13715,13716,13717,13718,13719,13720,13721,13722,13723,13724,13725,13726,13727,13728, #13728 13729,13730,13731,13732,13733,13734,13735,13736,13737,13738,13739,13740,13741,13742,13743,13744, #13744 13745,13746,13747,13748,13749,13750,13751,13752,13753,13754,13755,13756,13757,13758,13759,13760, #13760 13761,13762,13763,13764,13765,13766,13767,13768,13769,13770,13771,13772,13773,13774,3273,13775, #13776 13776,13777,13778,13779,13780,13781,13782,13783,13784,13785,13786,13787,13788,13789,13790,13791, #13792 13792,13793,13794,13795,13796,13797,13798,13799,13800,13801,13802,13803,13804,13805,13806,13807, #13808 13808,13809,13810,13811,13812,13813,13814,13815,13816,13817,13818,13819,13820,13821,13822,13823, #13824 13824,13825,13826,13827,13828,13829,13830,13831,13832,13833,13834,13835,13836,13837,13838,13839, #13840 13840,13841,13842,13843,13844,13845,13846,13847,13848,13849,13850,13851,13852,13853,13854,13855, #13856 13856,13857,13858,13859,13860,13861,13862,13863,13864,13865,13866,13867,13868,13869,13870,13871, #13872 13872,13873,13874,13875,13876,13877,13878,13879,13880,13881,13882,13883,13884,13885,13886,13887, #13888 13888,13889,13890,13891,13892,13893,13894,13895,13896,13897,13898,13899,13900,13901,13902,13903, #13904 13904,13905,13906,13907,13908,13909,13910,13911,13912,13913,13914,13915,13916,13917,13918,13919, #13920 13920,13921,13922,13923,13924,13925,13926,13927,13928,13929,13930,13931,13932,13933,13934,13935, #13936 13936,13937,13938,13939,13940,13941,13942,13943,13944,13945,13946,13947,13948,13949,13950,13951, #13952 13952,13953,13954,13955,13956,13957,13958,13959,13960,13961,13962,13963,13964,13965,13966,13967, #13968 13968,13969,13970,13971,13972) #13973 # flake8: noqa
mit
pietergreyling/amphtml
validator/build.py
17
19699
#!/usr/bin/python2.7 # # Copyright 2015 The AMP HTML Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the license. # """A build script which (thus far) works on Ubuntu 14.""" import glob import logging import os import platform import re import shutil import subprocess import sys import tempfile def Die(msg): """Prints error and exits with status 1. Args: msg: The error message to emit """ print >> sys.stderr, msg sys.exit(1) def GetNodeJsCmd(): """Ensure Node.js is installed and return the proper command to run.""" logging.info('entering ...') for cmd in ['node', 'nodejs']: try: output = subprocess.check_output([cmd, '--eval', 'console.log("42")']) if output.strip() == '42': logging.info('... done') return cmd except (subprocess.CalledProcessError, OSError): continue Die('Node.js not found. Try "apt-get install nodejs".') def CheckPrereqs(): """Checks that various prerequisites for this script are satisfied.""" logging.info('entering ...') if platform.system() != 'Linux' and platform.system() != 'Darwin': Die('Sorry, this script assumes Linux or Mac OS X thus far. ' 'Please feel free to edit the source and fix it to your needs.') # Ensure source files are available. for f in ['validator-main.protoascii', 'validator.proto', 'validator_gen_js.py', 'package.json', 'engine/validator.js', 'engine/validator_test.js', 'engine/validator-in-browser.js', 'engine/tokenize-css.js', 'engine/parse-css.js', 'engine/parse-srcset.js', 'engine/parse-url.js']: if not os.path.exists(f): Die('%s not found. Must run in amp_validator source directory.' % f) # Ensure protoc is available. try: libprotoc_version = subprocess.check_output(['protoc', '--version']) except (subprocess.CalledProcessError, OSError): Die('Protobuf compiler not found. Try "apt-get install protobuf-compiler".') # Ensure 'libprotoc 2.5.0' or newer. m = re.search('^(\\w+) (\\d+)\\.(\\d+)\\.(\\d+)', libprotoc_version) if (m.group(1) != 'libprotoc' or (int(m.group(2)), int(m.group(3)), int(m.group(4))) < (2, 5, 0)): Die('Expected libprotoc 2.5.0 or newer, saw: %s' % libprotoc_version) # Ensure that the Python protobuf package is installed. for m in ['descriptor', 'text_format']: module = 'google.protobuf.%s' % m try: __import__(module) except ImportError: Die('%s not found. Try "apt-get install python-protobuf"' % module) # Ensure that npm is installed. try: npm_version = subprocess.check_output(['npm', '--version']) except (subprocess.CalledProcessError, OSError): Die('npm package manager not found. Try "apt-get install npm".') # Ensure npm version '1.3.10' or newer. m = re.search('^(\\d+)\\.(\\d+)\\.(\\d+)$', npm_version) if (int(m.group(1)), int(m.group(2)), int(m.group(3))) < (1, 3, 10): Die('Expected npm version 1.3.10 or newer, saw: %s' % npm_version) # Ensure JVM installed. TODO: Check for version? try: subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT) except (subprocess.CalledProcessError, OSError): Die('Java missing. Try "apt-get install openjdk-7-jre"') logging.info('... done') def SetupOutDir(out_dir): """Sets up a clean output directory. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') assert re.match(r'^[a-zA-Z_\-0-9]+$', out_dir), 'bad out_dir: %s' % out_dir if os.path.exists(out_dir): subprocess.check_call(['rm', '-rf', out_dir]) os.mkdir(out_dir) logging.info('... done') def InstallNodeDependencies(): """Installs the dependencies using npm.""" logging.info('entering ...') # Install the project dependencies specified in package.json into # node_modules. logging.info('installing AMP Validator engine dependencies ...') subprocess.check_call(['npm', 'install']) logging.info('installing AMP Validator nodejs dependencies ...') subprocess.check_call(['npm', 'install'], cwd='nodejs') logging.info('... done') def GenValidatorPb2Py(out_dir): """Calls the proto compiler to generate validator_pb2.py. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') assert re.match(r'^[a-zA-Z_\-0-9]+$', out_dir), 'bad out_dir: %s' % out_dir subprocess.check_call(['protoc', 'validator.proto', '--python_out=%s' % out_dir]) open('%s/__init__.py' % out_dir, 'w').close() logging.info('... done') def GenValidatorProtoascii(out_dir): """Assembles the validator protoascii file from the main and extensions. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') assert re.match(r'^[a-zA-Z_\-0-9]+$', out_dir), 'bad out_dir: %s' % out_dir protoascii_segments = [open('validator-main.protoascii').read()] extensions = glob.glob('extensions/*/0.1/validator-*.protoascii') # In the Github project, the extensions are located in a sibling directory # to the validator rather than a child directory. if not extensions: extensions = glob.glob('../extensions/*/0.1/validator-*.protoascii') extensions.sort() for extension in extensions: protoascii_segments.append(open(extension).read()) f = open('%s/validator.protoascii' % out_dir, 'w') f.write(''.join(protoascii_segments)) f.close() logging.info('... done') def GenValidatorGeneratedJs(out_dir): """Calls validator_gen_js to generate validator-generated.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') assert re.match(r'^[a-zA-Z_\-0-9]+$', out_dir), 'bad out_dir: %s' % out_dir # These imports happen late, within this method because they don't necessarily # exist when the module starts running, and the ones that probably do # are checked by CheckPrereqs. from google.protobuf import text_format from google.protobuf import descriptor from dist import validator_pb2 import validator_gen_js out = [] validator_gen_js.GenerateValidatorGeneratedJs( specfile='%s/validator.protoascii' % out_dir, validator_pb2=validator_pb2, text_format=text_format, descriptor=descriptor, out=out) out.append('') f = open('%s/validator-generated.js' % out_dir, 'w') f.write('\n'.join(out)) f.close() logging.info('... done') def GenValidatorGeneratedMd(out_dir): """Calls validator_gen_md to generate validator-generated.md. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') assert re.match(r'^[a-zA-Z_\-0-9]+$', out_dir), 'bad out_dir: %s' % out_dir # These imports happen late, within this method because they don't necessarily # exist when the module starts running, and the ones that probably do # are checked by CheckPrereqs. from google.protobuf import text_format from dist import validator_pb2 import validator_gen_md out = [] validator_gen_md.GenerateValidatorGeneratedMd( specfile='%s/validator.protoascii' % out_dir, validator_pb2=validator_pb2, text_format=text_format, out=out) out.append('') f = open('%s/validator-generated.md' % out_dir, 'w') f.write('\n'.join(out)) f.close() logging.info('... done') def CompileWithClosure(js_files, closure_entry_points, output_file): """Compiles the arguments with the Closure compiler for transpilation to ES5. Args: js_files: list of files to compile closure_entry_points: entry points (these won't be minimized) output_file: name of the Javascript output file """ cmd = ['java', '-jar', 'node_modules/google-closure-compiler/compiler.jar', '--language_in=ECMASCRIPT6_STRICT', '--language_out=ES5_STRICT', '--js_output_file=%s' % output_file, '--only_closure_dependencies'] cmd += ['--closure_entry_point=%s' % e for e in closure_entry_points] cmd += ['node_modules/google-closure-library/closure/**.js', '!node_modules/google-closure-library/closure/**_test.js', 'node_modules/google-closure-library/third_party/closure/**.js', '!node_modules/google-closure-library/third_party/closure/**_test.js'] cmd += js_files subprocess.check_call(cmd) def CompileValidatorMinified(out_dir): """Generates a minified validator script, which can be imported to validate. Args: out_dir: output directory """ logging.info('entering ...') CompileWithClosure( js_files=['engine/htmlparser.js', 'engine/parse-css.js', 'engine/parse-srcset.js', 'engine/parse-url.js', 'engine/tokenize-css.js', '%s/validator-generated.js' % out_dir, 'engine/validator-in-browser.js', 'engine/validator.js', 'engine/amp4ads-parse-css.js', 'engine/dom-walker.js', 'engine/htmlparser-interface.js'], closure_entry_points=['amp.validator.validateString', 'amp.validator.renderValidationResult', 'amp.validator.renderErrorMessage'], output_file='%s/validator_minified.js' % out_dir) logging.info('... done') def RunSmokeTest(out_dir, nodejs_cmd): """Runs a smoke test (minimum valid AMP and empty html file). Args: out_dir: output directory nodejs_cmd: the command for calling Node.js """ logging.info('entering ...') # Run index.js on the minimum valid amp and observe that it passes. p = subprocess.Popen( [nodejs_cmd, 'nodejs/index.js', '--validator_js', '%s/validator_minified.js' % out_dir, 'testdata/feature_tests/minimum_valid_amp.html'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() if ('testdata/feature_tests/minimum_valid_amp.html: PASS\n', '', p.returncode ) != (stdout, stderr, 0): Die('Smoke test failed. returncode=%d stdout="%s" stderr="%s"' % (p.returncode, stdout, stderr)) # Run index.js on an empty file and observe that it fails. p = subprocess.Popen( [nodejs_cmd, 'nodejs/index.js', '--validator_js', '%s/validator_minified.js' % out_dir, 'testdata/feature_tests/empty.html'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode != 1: Die('smoke test failed. Expected p.returncode==1, saw: %s' % p.returncode) if not stderr.startswith('testdata/feature_tests/empty.html:1:0 ' 'The mandatory tag \'html'): Die('smoke test failed; stderr was: "%s"' % stderr) logging.info('... done') def RunIndexTest(nodejs_cmd): """Runs the index_test.js, which tests the NodeJS API. Args: nodejs_cmd: the command for calling Node.js """ logging.info('entering ...') p = subprocess.Popen( [nodejs_cmd, './index_test.js'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd='nodejs') (stdout, stderr) = p.communicate() if p.returncode != 0: Die('index_test.js failed. returncode=%d stdout="%s" stderr="%s"' % (p.returncode, stdout, stderr)) logging.info('... done') def CompileValidatorTestMinified(out_dir): """Runs closure compiler for validator_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/htmlparser.js', 'engine/parse-css.js', 'engine/parse-srcset.js', 'engine/parse-url.js', 'engine/tokenize-css.js', '%s/validator-generated.js' % out_dir, 'engine/validator-in-browser.js', 'engine/validator.js', 'engine/amp4ads-parse-css.js', 'engine/htmlparser-interface.js', 'engine/dom-walker.js', 'engine/validator_test.js'], closure_entry_points=['amp.validator.ValidatorTest'], output_file='%s/validator_test_minified.js' % out_dir) logging.info('... success') def CompileValidatorLightTestMinified(out_dir): """Runs closure compiler for validator-light_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/htmlparser.js', 'engine/parse-css.js', 'engine/parse-srcset.js', 'engine/parse-url.js', 'engine/tokenize-css.js', '%s/validator-generated.js' % out_dir, 'engine/validator-in-browser.js', 'engine/validator.js', 'engine/amp4ads-parse-css.js', 'engine/htmlparser-interface.js', 'engine/dom-walker.js', 'engine/validator-light_test.js'], closure_entry_points=['amp.validator.ValidatorTest'], output_file='%s/validator-light_test_minified.js' % out_dir) logging.info('... success') def CompileHtmlparserTestMinified(out_dir): """Runs closure compiler for htmlparser_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/htmlparser.js', 'engine/htmlparser-interface.js', 'engine/htmlparser_test.js'], closure_entry_points=['amp.htmlparser.HtmlParserTest'], output_file='%s/htmlparser_test_minified.js' % out_dir) logging.info('... success') def CompileParseCssTestMinified(out_dir): """Runs closure compiler for parse-css_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/parse-css.js', 'engine/parse-url.js', 'engine/tokenize-css.js', 'engine/css-selectors.js', 'engine/json-testutil.js', 'engine/parse-css_test.js', '%s/validator-generated.js' % out_dir], closure_entry_points=['parse_css.ParseCssTest'], output_file='%s/parse-css_test_minified.js' % out_dir) logging.info('... success') def CompileParseUrlTestMinified(out_dir): """Runs closure compiler for parse-url_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/parse-url.js', 'engine/parse-css.js', 'engine/tokenize-css.js', 'engine/css-selectors.js', 'engine/json-testutil.js', 'engine/parse-url_test.js', '%s/validator-generated.js' % out_dir], closure_entry_points=['parse_url.ParseURLTest'], output_file='%s/parse-url_test_minified.js' % out_dir) logging.info('... success') def CompileAmp4AdsParseCssTestMinified(out_dir): """Runs closure compiler for amp4ads-parse-css_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/amp4ads-parse-css_test.js', 'engine/parse-css.js', 'engine/parse-url.js', 'engine/amp4ads-parse-css.js', 'engine/tokenize-css.js', 'engine/css-selectors.js', 'engine/json-testutil.js', '%s/validator-generated.js' % out_dir], closure_entry_points=['parse_css.Amp4AdsParseCssTest'], output_file='%s/amp4ads-parse-css_test_minified.js' % out_dir) logging.info('... success') def CompileParseSrcsetTestMinified(out_dir): """Runs closure compiler for parse-srcset_test.js. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') CompileWithClosure( js_files=['engine/parse-srcset.js', 'engine/json-testutil.js', 'engine/parse-srcset_test.js', '%s/validator-generated.js' % out_dir], closure_entry_points=['parse_srcset.ParseSrcsetTest'], output_file='%s/parse-srcset_test_minified.js' % out_dir) logging.info('... success') def GenerateTestRunner(out_dir): """Generates a test runner: a nodejs script that runs our minified tests. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. """ logging.info('entering ...') f = open('%s/test_runner' % out_dir, 'w') extensions_dir = 'extensions' # In the Github project, the extensions are located in a sibling directory # to the validator rather than a child directory. if not os.path.isdir(extensions_dir): extensions_dir = '../extensions' f.write("""#!/usr/bin/nodejs global.assert = require('assert'); global.fs = require('fs'); global.path = require('path'); var JasmineRunner = require('jasmine'); var jasmine = new JasmineRunner(); process.env.TESTDATA_ROOTS = 'testdata:%s' require('./validator_test_minified'); require('./validator-light_test_minified'); require('./htmlparser_test_minified'); require('./parse-css_test_minified'); require('./parse-url_test_minified'); require('./amp4ads-parse-css_test_minified'); require('./parse-srcset_test_minified'); jasmine.onComplete(function (passed) { process.exit(passed ? 0 : 1); }); jasmine.execute(); """ % extensions_dir) os.chmod('%s/test_runner' % out_dir, 0750) logging.info('... success') def RunTests(out_dir, nodejs_cmd): """Runs all the minified tests. Args: out_dir: directory name of the output directory. Must not have slashes, dots, etc. nodejs_cmd: the command for calling Node.js """ logging.info('entering ...') subprocess.check_call([nodejs_cmd, '%s/test_runner' % out_dir]) logging.info('... success') def Main(): """The main method, which executes all build steps and runs the tests.""" logging.basicConfig( format='[[%(filename)s %(funcName)s]] - %(message)s', level=logging.INFO) nodejs_cmd = GetNodeJsCmd() CheckPrereqs() InstallNodeDependencies() SetupOutDir(out_dir='dist') GenValidatorProtoascii(out_dir='dist') GenValidatorPb2Py(out_dir='dist') GenValidatorProtoascii(out_dir='dist') GenValidatorGeneratedJs(out_dir='dist') GenValidatorGeneratedMd(out_dir='dist') CompileValidatorMinified(out_dir='dist') RunSmokeTest(out_dir='dist', nodejs_cmd=nodejs_cmd) RunIndexTest(nodejs_cmd=nodejs_cmd) CompileValidatorTestMinified(out_dir='dist') CompileValidatorLightTestMinified(out_dir='dist') CompileHtmlparserTestMinified(out_dir='dist') CompileParseCssTestMinified(out_dir='dist') CompileParseUrlTestMinified(out_dir='dist') CompileAmp4AdsParseCssTestMinified(out_dir='dist') CompileParseSrcsetTestMinified(out_dir='dist') GenerateTestRunner(out_dir='dist') RunTests(out_dir='dist', nodejs_cmd=nodejs_cmd) if __name__ == '__main__': Main()
apache-2.0
ryfeus/lambda-packs
Tensorflow_Pandas_Numpy/source3.6/tensorflow/contrib/ffmpeg/__init__.py
82
1251
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # pylint: disable=g-short-docstring-punctuation """Working with audio using FFmpeg. See the @{$python/contrib.ffmpeg} guide. @@decode_audio @@encode_audio """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.ffmpeg.ffmpeg_ops import decode_audio from tensorflow.contrib.ffmpeg.ffmpeg_ops import encode_audio from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = ['decode_audio', 'encode_audio'] remove_undocumented(__name__, _allowed_symbols)
mit
jonyroda97/redbot-amigosprovaveis
lib/pip/_internal/vcs/git.py
8
11275
from __future__ import absolute_import import logging import os.path import re from pip._vendor.packaging.version import parse as parse_version from pip._vendor.six.moves.urllib import parse as urllib_parse from pip._vendor.six.moves.urllib import request as urllib_request from pip._internal.compat import samefile from pip._internal.exceptions import BadCommand from pip._internal.utils.misc import display_path from pip._internal.utils.temp_dir import TempDirectory from pip._internal.vcs import VersionControl, vcs urlsplit = urllib_parse.urlsplit urlunsplit = urllib_parse.urlunsplit logger = logging.getLogger(__name__) HASH_REGEX = re.compile('[a-fA-F0-9]{40}') def looks_like_hash(sha): return bool(HASH_REGEX.match(sha)) class Git(VersionControl): name = 'git' dirname = '.git' repo_name = 'clone' schemes = ( 'git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file', ) # Prevent the user's environment variables from interfering with pip: # https://github.com/pypa/pip/issues/1130 unset_environ = ('GIT_DIR', 'GIT_WORK_TREE') default_arg_rev = 'HEAD' def __init__(self, url=None, *args, **kwargs): # Works around an apparent Git bug # (see https://article.gmane.org/gmane.comp.version-control.git/146500) if url: scheme, netloc, path, query, fragment = urlsplit(url) if scheme.endswith('file'): initial_slashes = path[:-len(path.lstrip('/'))] newpath = ( initial_slashes + urllib_request.url2pathname(path) .replace('\\', '/').lstrip('/') ) url = urlunsplit((scheme, netloc, newpath, query, fragment)) after_plus = scheme.find('+') + 1 url = scheme[:after_plus] + urlunsplit( (scheme[after_plus:], netloc, newpath, query, fragment), ) super(Git, self).__init__(url, *args, **kwargs) def get_base_rev_args(self, rev): return [rev] def get_git_version(self): VERSION_PFX = 'git version ' version = self.run_command(['version'], show_stdout=False) if version.startswith(VERSION_PFX): version = version[len(VERSION_PFX):].split()[0] else: version = '' # get first 3 positions of the git version becasue # on windows it is x.y.z.windows.t, and this parses as # LegacyVersion which always smaller than a Version. version = '.'.join(version.split('.')[:3]) return parse_version(version) def export(self, location): """Export the Git repository at the url to the destination location""" if not location.endswith('/'): location = location + '/' with TempDirectory(kind="export") as temp_dir: self.unpack(temp_dir.path) self.run_command( ['checkout-index', '-a', '-f', '--prefix', location], show_stdout=False, cwd=temp_dir.path ) def get_revision_sha(self, dest, rev): """ Return a commit hash for the given revision if it names a remote branch or tag. Otherwise, return None. Args: dest: the repository directory. rev: the revision name. """ # Pass rev to pre-filter the list. output = self.run_command(['show-ref', rev], cwd=dest, show_stdout=False, on_returncode='ignore') refs = {} for line in output.strip().splitlines(): try: sha, ref = line.split() except ValueError: # Include the offending line to simplify troubleshooting if # this error ever occurs. raise ValueError('unexpected show-ref line: {!r}'.format(line)) refs[ref] = sha branch_ref = 'refs/remotes/origin/{}'.format(rev) tag_ref = 'refs/tags/{}'.format(rev) return refs.get(branch_ref) or refs.get(tag_ref) def check_rev_options(self, dest, rev_options): """Check the revision options before checkout. Returns a new RevOptions object for the SHA1 of the branch or tag if found. Args: rev_options: a RevOptions object. """ rev = rev_options.arg_rev sha = self.get_revision_sha(dest, rev) if sha is not None: return rev_options.make_new(sha) # Do not show a warning for the common case of something that has # the form of a Git commit hash. if not looks_like_hash(rev): logger.warning( "Did not find branch or tag '%s', assuming revision or ref.", rev, ) return rev_options def is_commit_id_equal(self, dest, name): """ Return whether the current commit hash equals the given name. Args: dest: the repository directory. name: a string name. """ if not name: # Then avoid an unnecessary subprocess call. return False return self.get_revision(dest) == name def fetch_new(self, dest, url, rev_options): rev_display = rev_options.to_display() logger.info( 'Cloning %s%s to %s', url, rev_display, display_path(dest), ) self.run_command(['clone', '-q', url, dest]) if rev_options.rev: # Then a specific revision was requested. rev_options = self.check_rev_options(dest, rev_options) # Only do a checkout if the current commit id doesn't match # the requested revision. if not self.is_commit_id_equal(dest, rev_options.rev): rev = rev_options.rev # Only fetch the revision if it's a ref if rev.startswith('refs/'): self.run_command( ['fetch', '-q', url] + rev_options.to_args(), cwd=dest, ) # Change the revision to the SHA of the ref we fetched rev = 'FETCH_HEAD' self.run_command(['checkout', '-q', rev], cwd=dest) #: repo may contain submodules self.update_submodules(dest) def switch(self, dest, url, rev_options): self.run_command(['config', 'remote.origin.url', url], cwd=dest) cmd_args = ['checkout', '-q'] + rev_options.to_args() self.run_command(cmd_args, cwd=dest) self.update_submodules(dest) def update(self, dest, rev_options): # First fetch changes from the default remote if self.get_git_version() >= parse_version('1.9.0'): # fetch tags in addition to everything else self.run_command(['fetch', '-q', '--tags'], cwd=dest) else: self.run_command(['fetch', '-q'], cwd=dest) # Then reset to wanted revision (maybe even origin/master) rev_options = self.check_rev_options(dest, rev_options) cmd_args = ['reset', '--hard', '-q'] + rev_options.to_args() self.run_command(cmd_args, cwd=dest) #: update submodules self.update_submodules(dest) def get_url(self, location): """Return URL of the first remote encountered.""" remotes = self.run_command( ['config', '--get-regexp', r'remote\..*\.url'], show_stdout=False, cwd=location, ) remotes = remotes.splitlines() found_remote = remotes[0] for remote in remotes: if remote.startswith('remote.origin.url '): found_remote = remote break url = found_remote.split(' ')[1] return url.strip() def get_revision(self, location): current_rev = self.run_command( ['rev-parse', 'HEAD'], show_stdout=False, cwd=location, ) return current_rev.strip() def _get_subdirectory(self, location): """Return the relative path of setup.py to the git repo root.""" # find the repo root git_dir = self.run_command(['rev-parse', '--git-dir'], show_stdout=False, cwd=location).strip() if not os.path.isabs(git_dir): git_dir = os.path.join(location, git_dir) root_dir = os.path.join(git_dir, '..') # find setup.py orig_location = location while not os.path.exists(os.path.join(location, 'setup.py')): last_location = location location = os.path.dirname(location) if location == last_location: # We've traversed up to the root of the filesystem without # finding setup.py logger.warning( "Could not find setup.py for directory %s (tried all " "parent directories)", orig_location, ) return None # relative path of setup.py to repo root if samefile(root_dir, location): return None return os.path.relpath(location, root_dir) def get_src_requirement(self, dist, location): repo = self.get_url(location) if not repo.lower().startswith('git:'): repo = 'git+' + repo egg_project_name = dist.egg_name().split('-', 1)[0] if not repo: return None current_rev = self.get_revision(location) req = '%s@%s#egg=%s' % (repo, current_rev, egg_project_name) subdirectory = self._get_subdirectory(location) if subdirectory: req += '&subdirectory=' + subdirectory return req def get_url_rev(self, url): """ Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes don't work with a ssh:// scheme (e.g. GitHub). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. """ if '://' not in url: assert 'file:' not in url url = url.replace('git+', 'git+ssh://') url, rev = super(Git, self).get_url_rev(url) url = url.replace('ssh://', '') else: url, rev = super(Git, self).get_url_rev(url) return url, rev def update_submodules(self, location): if not os.path.exists(os.path.join(location, '.gitmodules')): return self.run_command( ['submodule', 'update', '--init', '--recursive', '-q'], cwd=location, ) @classmethod def controls_location(cls, location): if super(Git, cls).controls_location(location): return True try: r = cls().run_command(['rev-parse'], cwd=location, show_stdout=False, on_returncode='ignore') return not r except BadCommand: logger.debug("could not determine if %s is under git control " "because git is not available", location) return False vcs.register(Git)
gpl-3.0
tianzhihen/python-mode
pymode/libs2/rope/refactor/importutils/module_imports.py
27
16583
import rope.base.pynames from rope.base import ast, utils from rope.refactor.importutils import importinfo from rope.refactor.importutils import actions class ModuleImports(object): def __init__(self, pycore, pymodule, import_filter=None): self.pycore = pycore self.pymodule = pymodule self.separating_lines = 0 self.filter = import_filter @property @utils.saveit def imports(self): finder = _GlobalImportFinder(self.pymodule, self.pycore) result = finder.find_import_statements() self.separating_lines = finder.get_separating_line_count() if self.filter is not None: for import_stmt in result: if not self.filter(import_stmt): import_stmt.readonly = True return result def _get_unbound_names(self, defined_pyobject): visitor = _GlobalUnboundNameFinder(self.pymodule, defined_pyobject) ast.walk(self.pymodule.get_ast(), visitor) return visitor.unbound def remove_unused_imports(self): can_select = _OneTimeSelector(self._get_unbound_names(self.pymodule)) visitor = actions.RemovingVisitor( self.pycore, self._current_folder(), can_select) for import_statement in self.imports: import_statement.accept(visitor) def get_used_imports(self, defined_pyobject): result = [] can_select = _OneTimeSelector(self._get_unbound_names(defined_pyobject)) visitor = actions.FilteringVisitor( self.pycore, self._current_folder(), can_select) for import_statement in self.imports: new_import = import_statement.accept(visitor) if new_import is not None and not new_import.is_empty(): result.append(new_import) return result def get_changed_source(self): imports = self.imports after_removing = self._remove_imports(imports) imports = [stmt for stmt in imports if not stmt.import_info.is_empty()] first_non_blank = self._first_non_blank_line(after_removing, 0) first_import = self._first_import_line() - 1 result = [] # Writing module docs result.extend(after_removing[first_non_blank:first_import]) # Writing imports sorted_imports = sorted(imports, self._compare_import_locations) for stmt in sorted_imports: start = self._get_import_location(stmt) if stmt != sorted_imports[0]: result.append('\n' * stmt.blank_lines) result.append(stmt.get_import_statement() + '\n') if sorted_imports and first_non_blank < len(after_removing): result.append('\n' * self.separating_lines) # Writing the body first_after_imports = self._first_non_blank_line(after_removing, first_import) result.extend(after_removing[first_after_imports:]) return ''.join(result) def _get_import_location(self, stmt): start = stmt.get_new_start() if start is None: start = stmt.get_old_location()[0] return start def _compare_import_locations(self, stmt1, stmt2): def get_location(stmt): if stmt.get_new_start() is not None: return stmt.get_new_start() else: return stmt.get_old_location()[0] return cmp(get_location(stmt1), get_location(stmt2)) def _remove_imports(self, imports): lines = self.pymodule.source_code.splitlines(True) after_removing = [] last_index = 0 for stmt in imports: start, end = stmt.get_old_location() after_removing.extend(lines[last_index:start - 1]) last_index = end - 1 for i in range(start, end): after_removing.append('') after_removing.extend(lines[last_index:]) return after_removing def _first_non_blank_line(self, lines, lineno): result = lineno for line in lines[lineno:]: if line.strip() == '': result += 1 else: break return result def add_import(self, import_info): visitor = actions.AddingVisitor(self.pycore, [import_info]) for import_statement in self.imports: if import_statement.accept(visitor): break else: lineno = self._get_new_import_lineno() blanks = self._get_new_import_blanks() self.imports.append(importinfo.ImportStatement( import_info, lineno, lineno, blank_lines=blanks)) def _get_new_import_blanks(self): return 0 def _get_new_import_lineno(self): if self.imports: return self.imports[-1].end_line return 1 def filter_names(self, can_select): visitor = actions.RemovingVisitor( self.pycore, self._current_folder(), can_select) for import_statement in self.imports: import_statement.accept(visitor) def expand_stars(self): can_select = _OneTimeSelector(self._get_unbound_names(self.pymodule)) visitor = actions.ExpandStarsVisitor( self.pycore, self._current_folder(), can_select) for import_statement in self.imports: import_statement.accept(visitor) def remove_duplicates(self): added_imports = [] for import_stmt in self.imports: visitor = actions.AddingVisitor(self.pycore, [import_stmt.import_info]) for added_import in added_imports: if added_import.accept(visitor): import_stmt.empty_import() else: added_imports.append(import_stmt) def get_relative_to_absolute_list(self): visitor = rope.refactor.importutils.actions.RelativeToAbsoluteVisitor( self.pycore, self._current_folder()) for import_stmt in self.imports: if not import_stmt.readonly: import_stmt.accept(visitor) return visitor.to_be_absolute def get_self_import_fix_and_rename_list(self): visitor = rope.refactor.importutils.actions.SelfImportVisitor( self.pycore, self._current_folder(), self.pymodule.get_resource()) for import_stmt in self.imports: if not import_stmt.readonly: import_stmt.accept(visitor) return visitor.to_be_fixed, visitor.to_be_renamed def _current_folder(self): return self.pymodule.get_resource().parent def sort_imports(self): # IDEA: Sort from import list visitor = actions.SortingVisitor(self.pycore, self._current_folder()) for import_statement in self.imports: import_statement.accept(visitor) in_projects = sorted(visitor.in_project, self._compare_imports) third_party = sorted(visitor.third_party, self._compare_imports) standards = sorted(visitor.standard, self._compare_imports) future = sorted(visitor.future, self._compare_imports) blank_lines = 0 last_index = self._first_import_line() last_index = self._move_imports(future, last_index, 0) last_index = self._move_imports(standards, last_index, 1) last_index = self._move_imports(third_party, last_index, 1) last_index = self._move_imports(in_projects, last_index, 1) self.separating_lines = 2 def _first_import_line(self): nodes = self.pymodule.get_ast().body lineno = 0 if self.pymodule.get_doc() is not None: lineno = 1 if len(nodes) > lineno: lineno = self.pymodule.logical_lines.logical_line_in( nodes[lineno].lineno)[0] else: lineno = self.pymodule.lines.length() while lineno > 1: line = self.pymodule.lines.get_line(lineno - 1) if line.strip() == '': lineno -= 1 else: break return lineno def _compare_imports(self, stmt1, stmt2): str1 = stmt1.get_import_statement() str2 = stmt2.get_import_statement() if str1.startswith('from ') and not str2.startswith('from '): return 1 if not str1.startswith('from ') and str2.startswith('from '): return -1 return cmp(str1, str2) def _move_imports(self, imports, index, blank_lines): if imports: imports[0].move(index, blank_lines) index += 1 if len(imports) > 1: for stmt in imports[1:]: stmt.move(index) index += 1 return index def handle_long_imports(self, maxdots, maxlength): visitor = actions.LongImportVisitor( self._current_folder(), self.pycore, maxdots, maxlength) for import_statement in self.imports: if not import_statement.readonly: import_statement.accept(visitor) for import_info in visitor.new_imports: self.add_import(import_info) return visitor.to_be_renamed def remove_pyname(self, pyname): """Removes pyname when imported in ``from mod import x``""" visitor = actions.RemovePyNameVisitor(self.pycore, self.pymodule, pyname, self._current_folder()) for import_stmt in self.imports: import_stmt.accept(visitor) class _OneTimeSelector(object): def __init__(self, names): self.names = names self.selected_names = set() def __call__(self, imported_primary): if self._can_name_be_added(imported_primary): for name in self._get_dotted_tokens(imported_primary): self.selected_names.add(name) return True return False def _get_dotted_tokens(self, imported_primary): tokens = imported_primary.split('.') for i in range(len(tokens)): yield '.'.join(tokens[:i + 1]) def _can_name_be_added(self, imported_primary): for name in self._get_dotted_tokens(imported_primary): if name in self.names and name not in self.selected_names: return True return False class _UnboundNameFinder(object): def __init__(self, pyobject): self.pyobject = pyobject def _visit_child_scope(self, node): pyobject = self.pyobject.get_module().get_scope().\ get_inner_scope_for_line(node.lineno).pyobject visitor = _LocalUnboundNameFinder(pyobject, self) for child in ast.get_child_nodes(node): ast.walk(child, visitor) def _FunctionDef(self, node): self._visit_child_scope(node) def _ClassDef(self, node): self._visit_child_scope(node) def _Name(self, node): if self._get_root()._is_node_interesting(node) and \ not self.is_bound(node.id): self.add_unbound(node.id) def _Attribute(self, node): result = [] while isinstance(node, ast.Attribute): result.append(node.attr) node = node.value if isinstance(node, ast.Name): result.append(node.id) primary = '.'.join(reversed(result)) if self._get_root()._is_node_interesting(node) and \ not self.is_bound(primary): self.add_unbound(primary) else: ast.walk(node, self) def _get_root(self): pass def is_bound(self, name, propagated=False): pass def add_unbound(self, name): pass class _GlobalUnboundNameFinder(_UnboundNameFinder): def __init__(self, pymodule, wanted_pyobject): super(_GlobalUnboundNameFinder, self).__init__(pymodule) self.unbound = set() self.names = set() for name, pyname in pymodule._get_structural_attributes().items(): if not isinstance(pyname, (rope.base.pynames.ImportedName, rope.base.pynames.ImportedModule)): self.names.add(name) wanted_scope = wanted_pyobject.get_scope() self.start = wanted_scope.get_start() self.end = wanted_scope.get_end() + 1 def _get_root(self): return self def is_bound(self, primary, propagated=False): name = primary.split('.')[0] if name in self.names: return True return False def add_unbound(self, name): names = name.split('.') for i in range(len(names)): self.unbound.add('.'.join(names[:i + 1])) def _is_node_interesting(self, node): return self.start <= node.lineno < self.end class _LocalUnboundNameFinder(_UnboundNameFinder): def __init__(self, pyobject, parent): super(_LocalUnboundNameFinder, self).__init__(pyobject) self.parent = parent def _get_root(self): return self.parent._get_root() def is_bound(self, primary, propagated=False): name = primary.split('.')[0] if propagated: names = self.pyobject.get_scope().get_propagated_names() else: names = self.pyobject.get_scope().get_names() if name in names or self.parent.is_bound(name, propagated=True): return True return False def add_unbound(self, name): self.parent.add_unbound(name) class _GlobalImportFinder(object): def __init__(self, pymodule, pycore): self.current_folder = None if pymodule.get_resource(): self.current_folder = pymodule.get_resource().parent self.pymodule = pymodule self.pycore = pycore self.imports = [] self.pymodule = pymodule self.lines = self.pymodule.lines def visit_import(self, node, end_line): start_line = node.lineno import_statement = importinfo.ImportStatement( importinfo.NormalImport(self._get_names(node.names)), start_line, end_line, self._get_text(start_line, end_line), blank_lines=self._count_empty_lines_before(start_line)) self.imports.append(import_statement) def _count_empty_lines_before(self, lineno): result = 0 for current in range(lineno - 1, 0, -1): line = self.lines.get_line(current) if line.strip() == '': result += 1 else: break return result def _count_empty_lines_after(self, lineno): result = 0 for current in range(lineno + 1, self.lines.length()): line = self.lines.get_line(current) if line.strip() == '': result += 1 else: break return result def get_separating_line_count(self): if not self.imports: return 0 return self._count_empty_lines_after(self.imports[-1].end_line - 1) def _get_text(self, start_line, end_line): result = [] for index in range(start_line, end_line): result.append(self.lines.get_line(index)) return '\n'.join(result) def visit_from(self, node, end_line): level = 0 if node.level: level = node.level import_info = importinfo.FromImport( node.module or '', # see comment at rope.base.ast.walk level, self._get_names(node.names)) start_line = node.lineno self.imports.append(importinfo.ImportStatement( import_info, node.lineno, end_line, self._get_text(start_line, end_line), blank_lines=self._count_empty_lines_before(start_line))) def _get_names(self, alias_names): result = [] for alias in alias_names: result.append((alias.name, alias.asname)) return result def find_import_statements(self): nodes = self.pymodule.get_ast().body for index, node in enumerate(nodes): if isinstance(node, (ast.Import, ast.ImportFrom)): lines = self.pymodule.logical_lines end_line = lines.logical_line_in(node.lineno)[1] + 1 if isinstance(node, ast.Import): self.visit_import(node, end_line) if isinstance(node, ast.ImportFrom): self.visit_from(node, end_line) return self.imports
lgpl-3.0
agileblaze/OpenStackTwoFactorAuthentication
openstack_dashboard/dashboards/admin/networks/tests.py
18
68798
# Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.core.urlresolvers import reverse from django import http from horizon.workflows import views from mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.dashboards.project.networks import tests from openstack_dashboard.test import helpers as test INDEX_URL = reverse('horizon:admin:networks:index') class NetworkTests(test.BaseAdminViewTests): @test.create_stubs({api.neutron: ('network_list', 'list_dhcp_agent_hosting_networks', 'is_extension_supported'), api.keystone: ('tenant_list',)}) def test_index(self): tenants = self.tenants.list() api.neutron.network_list(IsA(http.HttpRequest)) \ .AndReturn(self.networks.list()) api.keystone.tenant_list(IsA(http.HttpRequest))\ .AndReturn([tenants, False]) for network in self.networks.list(): api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network.id)\ .AndReturn(self.agents.list()) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'admin/networks/index.html') networks = res.context['networks_table'].data self.assertItemsEqual(networks, self.networks.list()) @test.create_stubs({api.neutron: ('network_list', 'is_extension_supported',)}) def test_index_network_list_exception(self): api.neutron.network_list(IsA(http.HttpRequest)) \ .AndRaise(self.exceptions.neutron) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) self.mox.ReplayAll() res = self.client.get(INDEX_URL) self.assertTemplateUsed(res, 'admin/networks/index.html') self.assertEqual(len(res.context['networks_table'].data), 0) self.assertMessageCount(res, error=1) @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'list_dhcp_agent_hosting_networks', 'is_extension_supported')}) def test_network_detail(self): self._test_network_detail() @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_network_detail_with_mac_learning(self): self._test_network_detail(mac_learning=True) def _test_network_detail(self, mac_learning=False): network_id = self.networks.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.network_get(IsA(http.HttpRequest), network_id)\ .AndReturn(self.networks.first()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) self.mox.ReplayAll() res = self.client.get(reverse('horizon:admin:networks:detail', args=[network_id])) self.assertTemplateUsed(res, 'project/networks/detail.html') subnets = res.context['subnets_table'].data ports = res.context['ports_table'].data self.assertItemsEqual(subnets, [self.subnets.first()]) self.assertItemsEqual(ports, [self.ports.first()]) @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_network_detail_network_exception(self): self._test_network_detail_network_exception() @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_network_detail_network_exception_with_mac_learning(self): self._test_network_detail_network_exception(mac_learning=True) def _test_network_detail_network_exception(self, mac_learning=False): network_id = self.networks.first().id api.neutron.network_get(IsA(http.HttpRequest), network_id)\ .AndRaise(self.exceptions.neutron) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.get(url) redir_url = INDEX_URL self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'list_dhcp_agent_hosting_networks', 'is_extension_supported')}) def test_network_detail_subnet_exception(self): self._test_network_detail_subnet_exception() @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_network_detail_subnet_exception_with_mac_learning(self): self._test_network_detail_subnet_exception(mac_learning=True) def _test_network_detail_subnet_exception(self, mac_learning=False): network_id = self.networks.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.network_get(IsA(http.HttpRequest), network_id).\ AndReturn(self.networks.first()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id).\ AndRaise(self.exceptions.neutron) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id).\ AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) self.mox.ReplayAll() res = self.client.get(reverse('horizon:admin:networks:detail', args=[network_id])) self.assertTemplateUsed(res, 'project/networks/detail.html') subnets = res.context['subnets_table'].data ports = res.context['ports_table'].data self.assertEqual(len(subnets), 0) self.assertItemsEqual(ports, [self.ports.first()]) @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_network_detail_port_exception(self): self._test_network_detail_port_exception() @test.create_stubs({api.neutron: ('network_get', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_network_detail_port_exception_with_mac_learning(self): self._test_network_detail_port_exception(mac_learning=True) def _test_network_detail_port_exception(self, mac_learning=False): network_id = self.networks.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.network_get(IsA(http.HttpRequest), network_id).\ AndReturn(self.networks.first()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id).\ AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id).\ AndRaise(self.exceptions.neutron) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'dhcp_agent_scheduler')\ .AndReturn(True) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'dhcp_agent_scheduler')\ .AndReturn(True) self.mox.ReplayAll() res = self.client.get(reverse('horizon:admin:networks:detail', args=[network_id])) self.assertTemplateUsed(res, 'project/networks/detail.html') subnets = res.context['subnets_table'].data ports = res.context['ports_table'].data self.assertItemsEqual(subnets, [self.subnets.first()]) self.assertEqual(len(ports), 0) @test.create_stubs({api.neutron: ('profile_list', 'list_extensions',), api.keystone: ('tenant_list',)}) def test_network_create_get(self, test_with_profile=False): tenants = self.tenants.list() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA( http.HttpRequest)).AndReturn([tenants, False]) if test_with_profile: net_profiles = self.net_profiles.list() api.neutron.profile_list(IsA(http.HttpRequest), 'network').AndReturn(net_profiles) api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) self.mox.ReplayAll() url = reverse('horizon:admin:networks:create') res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/create.html') @test.update_settings( OPENSTACK_NEUTRON_NETWORK={'profile_support': 'cisco'}) def test_network_create_get_with_profile(self): self.test_network_create_get(test_with_profile=True) @test.create_stubs({api.neutron: ('network_create', 'profile_list', 'list_extensions',), api.keystone: ('tenant_list',)}) def test_network_create_post(self, test_with_profile=False): tenants = self.tenants.list() tenant_id = self.tenants.first().id network = self.networks.first() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest))\ .AndReturn([tenants, False]) params = {'name': network.name, 'tenant_id': tenant_id, 'admin_state_up': network.admin_state_up, 'router:external': True, 'shared': True, 'provider:network_type': 'local'} if test_with_profile: net_profiles = self.net_profiles.list() net_profile_id = self.net_profiles.first().id api.neutron.profile_list(IsA(http.HttpRequest), 'network').AndReturn(net_profiles) params['net_profile_id'] = net_profile_id api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) api.neutron.network_create(IsA(http.HttpRequest), **params)\ .AndReturn(network) self.mox.ReplayAll() form_data = {'tenant_id': tenant_id, 'name': network.name, 'admin_state': network.admin_state_up, 'external': True, 'shared': True, 'network_type': 'local'} if test_with_profile: form_data['net_profile_id'] = net_profile_id url = reverse('horizon:admin:networks:create') res = self.client.post(url, form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) @test.update_settings( OPENSTACK_NEUTRON_NETWORK={'profile_support': 'cisco'}) def test_network_create_post_with_profile(self): self.test_network_create_post(test_with_profile=True) @test.create_stubs({api.neutron: ('network_create', 'profile_list', 'list_extensions',), api.keystone: ('tenant_list',)}) def test_network_create_post_network_exception(self, test_with_profile=False): tenants = self.tenants.list() tenant_id = self.tenants.first().id network = self.networks.first() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest)).AndReturn([tenants, False]) params = {'name': network.name, 'tenant_id': tenant_id, 'admin_state_up': network.admin_state_up, 'router:external': True, 'shared': False, 'provider:network_type': 'local'} if test_with_profile: net_profiles = self.net_profiles.list() net_profile_id = self.net_profiles.first().id api.neutron.profile_list(IsA(http.HttpRequest), 'network').AndReturn(net_profiles) params['net_profile_id'] = net_profile_id api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) api.neutron.network_create(IsA(http.HttpRequest), **params).AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'tenant_id': tenant_id, 'name': network.name, 'admin_state': network.admin_state_up, 'external': True, 'shared': False, 'network_type': 'local'} if test_with_profile: form_data['net_profile_id'] = net_profile_id url = reverse('horizon:admin:networks:create') res = self.client.post(url, form_data) self.assertNoFormErrors(res) self.assertRedirectsNoFollow(res, INDEX_URL) @test.update_settings( OPENSTACK_NEUTRON_NETWORK={'profile_support': 'cisco'}) def test_network_create_post_network_exception_with_profile(self): self.test_network_create_post_network_exception( test_with_profile=True) @test.create_stubs({api.neutron: ('list_extensions',), api.keystone: ('tenant_list',)}) def test_network_create_vlan_segmentation_id_invalid(self): tenants = self.tenants.list() tenant_id = self.tenants.first().id network = self.networks.first() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest)).AndReturn([tenants, False]) api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) self.mox.ReplayAll() form_data = {'tenant_id': tenant_id, 'name': network.name, 'admin_state': network.admin_state_up, 'external': True, 'shared': False, 'network_type': 'vlan', 'physical_network': 'default', 'segmentation_id': 4095} url = reverse('horizon:admin:networks:create') res = self.client.post(url, form_data) self.assertFormErrors(res, 1) self.assertContains(res, "1 through 4094") @test.create_stubs({api.neutron: ('list_extensions',), api.keystone: ('tenant_list',)}) def test_network_create_gre_segmentation_id_invalid(self): tenants = self.tenants.list() tenant_id = self.tenants.first().id network = self.networks.first() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest)).AndReturn([tenants, False]) api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) self.mox.ReplayAll() form_data = {'tenant_id': tenant_id, 'name': network.name, 'admin_state': network.admin_state_up, 'external': True, 'shared': False, 'network_type': 'gre', 'physical_network': 'default', 'segmentation_id': (2 ** 32) + 1} url = reverse('horizon:admin:networks:create') res = self.client.post(url, form_data) self.assertFormErrors(res, 1) self.assertContains(res, "0 through %s" % ((2 ** 32) - 1)) @test.create_stubs({api.neutron: ('list_extensions',), api.keystone: ('tenant_list',)}) @test.update_settings( OPENSTACK_NEUTRON_NETWORK={ 'segmentation_id_range': {'vxlan': [10, 20]}}) def test_network_create_vxlan_segmentation_id_custom(self): tenants = self.tenants.list() tenant_id = self.tenants.first().id network = self.networks.first() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest)).AndReturn([tenants, False]) api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) self.mox.ReplayAll() form_data = {'tenant_id': tenant_id, 'name': network.name, 'admin_state': network.admin_state_up, 'external': True, 'shared': False, 'network_type': 'vxlan', 'physical_network': 'default', 'segmentation_id': 9} url = reverse('horizon:admin:networks:create') res = self.client.post(url, form_data) self.assertFormErrors(res, 1) self.assertContains(res, "10 through 20") @test.create_stubs({api.neutron: ('list_extensions',), api.keystone: ('tenant_list',)}) @test.update_settings( OPENSTACK_NEUTRON_NETWORK={ 'supported_provider_types': []}) def test_network_create_no_provider_types(self): tenants = self.tenants.list() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest)).AndReturn([tenants, False]) api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) self.mox.ReplayAll() url = reverse('horizon:admin:networks:create') res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/create.html') self.assertContains( res, '<input type="hidden" name="network_type" id="id_network_type" />', html=True) @test.create_stubs({api.neutron: ('list_extensions',), api.keystone: ('tenant_list',)}) @test.update_settings( OPENSTACK_NEUTRON_NETWORK={ 'supported_provider_types': ['local', 'flat', 'gre']}) def test_network_create_unsupported_provider_types(self): tenants = self.tenants.list() extensions = self.api_extensions.list() api.keystone.tenant_list(IsA(http.HttpRequest)).AndReturn([tenants, False]) api.neutron.list_extensions( IsA(http.HttpRequest)).AndReturn(extensions) self.mox.ReplayAll() url = reverse('horizon:admin:networks:create') res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/create.html') network_type = res.context['form'].fields['network_type'] self.assertListEqual(list(network_type.choices), [('local', 'Local'), ('flat', 'Flat'), ('gre', 'GRE')]) @test.create_stubs({api.neutron: ('network_get',)}) def test_network_update_get(self): network = self.networks.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) self.mox.ReplayAll() url = reverse('horizon:admin:networks:update', args=[network.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/update.html') @test.create_stubs({api.neutron: ('network_get',)}) def test_network_update_get_exception(self): network = self.networks.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() url = reverse('horizon:admin:networks:update', args=[network.id]) res = self.client.get(url) redir_url = INDEX_URL self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_update', 'network_get',)}) def test_network_update_post(self): network = self.networks.first() params = {'name': network.name, 'shared': True, 'admin_state_up': network.admin_state_up, 'router:external': True} api.neutron.network_update(IsA(http.HttpRequest), network.id, **params)\ .AndReturn(network) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) self.mox.ReplayAll() form_data = {'network_id': network.id, 'name': network.name, 'tenant_id': network.tenant_id, 'admin_state': network.admin_state_up, 'shared': True, 'external': True} url = reverse('horizon:admin:networks:update', args=[network.id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs({api.neutron: ('network_update', 'network_get',)}) def test_network_update_post_exception(self): network = self.networks.first() params = {'name': network.name, 'shared': False, 'admin_state_up': network.admin_state_up, 'router:external': False} api.neutron.network_update(IsA(http.HttpRequest), network.id, **params)\ .AndRaise(self.exceptions.neutron) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) self.mox.ReplayAll() form_data = {'network_id': network.id, 'name': network.name, 'tenant_id': network.tenant_id, 'admin_state': network.admin_state_up, 'shared': False, 'external': False} url = reverse('horizon:admin:networks:update', args=[network.id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs({api.neutron: ('network_list', 'network_delete', 'list_dhcp_agent_hosting_networks', 'is_extension_supported'), api.keystone: ('tenant_list',)}) def test_delete_network(self): tenants = self.tenants.list() network = self.networks.first() api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network.id).\ AndReturn(self.agents.list()) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.keystone.tenant_list(IsA(http.HttpRequest))\ .AndReturn([tenants, False]) api.neutron.network_list(IsA(http.HttpRequest))\ .AndReturn([network]) api.neutron.network_delete(IsA(http.HttpRequest), network.id) self.mox.ReplayAll() form_data = {'action': 'networks__delete__%s' % network.id} res = self.client.post(INDEX_URL, form_data) self.assertRedirectsNoFollow(res, INDEX_URL) @test.create_stubs({api.neutron: ('network_list', 'network_delete', 'list_dhcp_agent_hosting_networks', 'is_extension_supported'), api.keystone: ('tenant_list',)}) def test_delete_network_exception(self): tenants = self.tenants.list() network = self.networks.first() api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network.id).\ AndReturn(self.agents.list()) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.neutron.is_extension_supported( IsA(http.HttpRequest), 'dhcp_agent_scheduler').AndReturn(True) api.keystone.tenant_list(IsA(http.HttpRequest))\ .AndReturn([tenants, False]) api.neutron.network_list(IsA(http.HttpRequest))\ .AndReturn([network]) api.neutron.network_delete(IsA(http.HttpRequest), network.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'action': 'networks__delete__%s' % network.id} res = self.client.post(INDEX_URL, form_data) self.assertRedirectsNoFollow(res, INDEX_URL) class NetworkSubnetTests(test.BaseAdminViewTests): @test.create_stubs({api.neutron: ('network_get', 'subnet_get',)}) def test_subnet_detail(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) self.mox.ReplayAll() url = reverse('horizon:admin:networks:subnets:detail', args=[subnet.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'project/networks/subnets/detail.html') self.assertEqual(res.context['subnet'].id, subnet.id) @test.create_stubs({api.neutron: ('subnet_get',)}) def test_subnet_detail_exception(self): subnet = self.subnets.first() api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() url = reverse('horizon:admin:networks:subnets:detail', args=[subnet.id]) res = self.client.get(url) # admin DetailView is shared with userpanel one, so # redirection URL on error is userpanel index. redir_url = reverse('horizon:project:networks:index') self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get',)}) def test_subnet_create_get(self): network = self.networks.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() url = reverse('horizon:admin:networks:addsubnet', args=[network.id]) res = self.client.get(url) self.assertTemplateUsed(res, views.WorkflowView.template_name) @test.create_stubs({api.neutron: ('network_get', 'subnet_create',)}) def test_subnet_create_post(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.subnet_create(IsA(http.HttpRequest), network_id=network.id, name=subnet.name, cidr=subnet.cidr, ip_version=subnet.ip_version, gateway_ip=subnet.gateway_ip, enable_dhcp=subnet.enable_dhcp, allocation_pools=subnet.allocation_pools, tenant_id=subnet.tenant_id)\ .AndReturn(subnet) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse('horizon:admin:networks:detail', args=[subnet.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'subnet_create',)}) def test_subnet_create_post_network_exception(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) # admin DetailView is shared with userpanel one, so # redirection URL on error is userpanel index. redir_url = reverse('horizon:project:networks:index') self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'subnet_create',)}) def test_subnet_create_post_subnet_exception(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.subnet_create(IsA(http.HttpRequest), network_id=network.id, name=subnet.name, cidr=subnet.cidr, ip_version=subnet.ip_version, gateway_ip=subnet.gateway_ip, enable_dhcp=subnet.enable_dhcp, tenant_id=subnet.tenant_id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) redir_url = reverse('horizon:admin:networks:detail', args=[subnet.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get',)}) def test_subnet_create_post_cidr_inconsistent(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() # dummy IPv6 address cidr = '2001:0DB8:0:CD30:123:4567:89AB:CDEF/60' form_data = tests.form_data_subnet( subnet, cidr=cidr, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) expected_msg = 'Network Address and IP version are inconsistent.' self.assertContains(res, expected_msg) @test.create_stubs({api.neutron: ('network_get',)}) def test_subnet_create_post_gw_inconsistent(self): network = self.networks.first() subnet = self.subnets.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) self.mox.ReplayAll() # dummy IPv6 address gateway_ip = '2001:0DB8:0:CD30:123:4567:89AB:CDEF' form_data = tests.form_data_subnet(subnet, gateway_ip=gateway_ip, allocation_pools=[]) url = reverse('horizon:admin:networks:addsubnet', args=[subnet.network_id]) res = self.client.post(url, form_data) self.assertContains(res, 'Gateway IP and IP version are inconsistent.') @test.create_stubs({api.neutron: ('subnet_update', 'subnet_get',)}) def test_subnet_update_post(self): subnet = self.subnets.first() api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) api.neutron.subnet_update(IsA(http.HttpRequest), subnet.id, name=subnet.name, enable_dhcp=subnet.enable_dhcp, dns_nameservers=[], host_routes=[])\ .AndReturn(subnet) self.mox.ReplayAll() form_data = tests.form_data_subnet(subnet, allocation_pools=[]) url = reverse('horizon:admin:networks:editsubnet', args=[subnet.network_id, subnet.id]) res = self.client.post(url, form_data) redir_url = reverse('horizon:admin:networks:detail', args=[subnet.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('subnet_update', 'subnet_get',)}) def test_subnet_update_post_gw_inconsistent(self): subnet = self.subnets.first() api.neutron.subnet_get(IsA(http.HttpRequest), subnet.id)\ .AndReturn(subnet) self.mox.ReplayAll() # dummy IPv6 address gateway_ip = '2001:0DB8:0:CD30:123:4567:89AB:CDEF' form_data = tests.form_data_subnet(subnet, gateway_ip=gateway_ip, allocation_pools=[]) url = reverse('horizon:admin:networks:editsubnet', args=[subnet.network_id, subnet.id]) res = self.client.post(url, form_data) self.assertContains(res, 'Gateway IP and IP version are inconsistent.') @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete(self): self._test_subnet_delete() @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete_with_mac_learning(self): self._test_subnet_delete(mac_learning=True) def _test_subnet_delete(self, mac_learning=False): subnet = self.subnets.first() network_id = subnet.network_id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.subnet_delete(IsA(http.HttpRequest), subnet.id) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'subnets__delete__%s' % subnet.id} url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete_exception(self): self._test_subnet_delete_exception() @test.create_stubs({api.neutron: ('subnet_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_subnet_delete_exception_with_mac_learning(self): self._test_subnet_delete_exception(mac_learning=True) def _test_subnet_delete_exception(self, mac_learning=False): subnet = self.subnets.first() network_id = subnet.network_id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.subnet_delete(IsA(http.HttpRequest), subnet.id)\ .AndRaise(self.exceptions.neutron) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'subnets__delete__%s' % subnet.id} url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) class NetworkPortTests(test.BaseAdminViewTests): @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported',)}) def test_port_detail(self): self._test_port_detail() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported',)}) def test_port_detail_with_mac_learning(self): self._test_port_detail(mac_learning=True) def _test_port_detail(self, mac_learning=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(self.ports.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .MultipleTimes().AndReturn(mac_learning) self.mox.ReplayAll() res = self.client.get(reverse('horizon:admin:networks:ports:detail', args=[port.id])) self.assertTemplateUsed(res, 'project/networks/ports/detail.html') self.assertEqual(res.context['port'].id, port.id) @test.create_stubs({api.neutron: ('port_get',)}) def test_port_detail_exception(self): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() res = self.client.get(reverse('horizon:admin:networks:ports:detail', args=[port.id])) # admin DetailView is shared with userpanel one, so # redirection URL on error is userpanel index. redir_url = reverse('horizon:admin:networks:index') self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported',)}) def test_port_create_get(self): self._test_port_create_get() @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported',)}) def test_port_create_get_with_mac_learning(self): self._test_port_create_get(mac_learning=True) def _test_port_create_get(self, mac_learning=False, binding=False): network = self.networks.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() url = reverse('horizon:admin:networks:addport', args=[network.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/ports/create.html') @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported', 'port_create',)}) def test_port_create_post(self): self._test_port_create_post() @test.create_stubs({api.neutron: ('network_get', 'is_extension_supported', 'port_create',)}) def test_port_create_post_with_mac_learning(self): self._test_port_create_post(mac_learning=True, binding=False) def _test_port_create_post(self, mac_learning=False, binding=False): network = self.networks.first() port = self.ports.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = \ port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_create(IsA(http.HttpRequest), tenant_id=network.tenant_id, network_id=network.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndReturn(port) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'network_name': network.name, 'name': port.name, 'admin_state': port.admin_state_up, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_state'] = True url = reverse('horizon:admin:networks:addport', args=[port.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse('horizon:admin:networks:detail', args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('network_get', 'port_create', 'is_extension_supported',)}) def test_port_create_post_exception(self): self._test_port_create_post_exception() @test.create_stubs({api.neutron: ('network_get', 'port_create', 'is_extension_supported',)}) def test_port_create_post_exception_with_mac_learning(self): self._test_port_create_post_exception(mac_learning=True) def _test_port_create_post_exception(self, mac_learning=False, binding=False): network = self.networks.first() port = self.ports.first() api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(self.networks.first()) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_create(IsA(http.HttpRequest), tenant_id=network.tenant_id, network_id=network.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'network_name': network.name, 'name': port.name, 'admin_state': port.admin_state_up, 'mac_state': True, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_learning_enabled'] = True url = reverse('horizon:admin:networks:addport', args=[port.network_id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse('horizon:admin:networks:detail', args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported',)}) def test_port_update_get(self): self._test_port_update_get() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported',)}) def test_port_update_get_with_mac_learning(self): self._test_port_update_get(mac_learning=True) def _test_port_update_get(self, mac_learning=False, binding=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(port) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() url = reverse('horizon:admin:networks:editport', args=[port.network_id, port.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/ports/update.html') @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post(self): self._test_port_update_post() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post_with_mac_learning(self): self._test_port_update_post(mac_learning=True) def _test_port_update_post(self, mac_learning=False, binding=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(port) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_update(IsA(http.HttpRequest), port.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndReturn(port) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'port_id': port.id, 'name': port.name, 'admin_state': port.admin_state_up, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_state'] = True url = reverse('horizon:admin:networks:editport', args=[port.network_id, port.id]) res = self.client.post(url, form_data) redir_url = reverse('horizon:admin:networks:detail', args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post_exception(self): self._test_port_update_post_exception() @test.create_stubs({api.neutron: ('port_get', 'is_extension_supported', 'port_update')}) def test_port_update_post_exception_with_mac_learning(self): self._test_port_update_post_exception(mac_learning=True, binding=False) def _test_port_update_post_exception(self, mac_learning=False, binding=False): port = self.ports.first() api.neutron.port_get(IsA(http.HttpRequest), port.id)\ .AndReturn(port) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'binding')\ .AndReturn(binding) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) extension_kwargs = {} if binding: extension_kwargs['binding__vnic_type'] = port.binding__vnic_type if mac_learning: extension_kwargs['mac_learning_enabled'] = True api.neutron.port_update(IsA(http.HttpRequest), port.id, name=port.name, admin_state_up=port.admin_state_up, device_id=port.device_id, device_owner=port.device_owner, binding__host_id=port.binding__host_id, **extension_kwargs)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'network_id': port.network_id, 'port_id': port.id, 'name': port.name, 'admin_state': port.admin_state_up, 'device_id': port.device_id, 'device_owner': port.device_owner, 'binding__host_id': port.binding__host_id} if binding: form_data['binding__vnic_type'] = port.binding__vnic_type if mac_learning: form_data['mac_state'] = True url = reverse('horizon:admin:networks:editport', args=[port.network_id, port.id]) res = self.client.post(url, form_data) redir_url = reverse('horizon:admin:networks:detail', args=[port.network_id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_port_delete(self): self._test_port_delete() @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_port_delete_with_mac_learning(self): self._test_port_delete(mac_learning=True) def _test_port_delete(self, mac_learning=False): port = self.ports.first() network_id = port.network_id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.port_delete(IsA(http.HttpRequest), port.id) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'ports__delete__%s' % port.id} url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks',)}) def test_port_delete_exception(self): self._test_port_delete_exception() @test.create_stubs({api.neutron: ('port_delete', 'subnet_list', 'port_list', 'is_extension_supported', 'list_dhcp_agent_hosting_networks')}) def test_port_delete_exception_with_mac_learning(self): self._test_port_delete_exception(mac_learning=True) def _test_port_delete_exception(self, mac_learning=False): port = self.ports.first() network_id = port.network_id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.port_delete(IsA(http.HttpRequest), port.id)\ .AndRaise(self.exceptions.neutron) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(mac_learning) self.mox.ReplayAll() form_data = {'action': 'ports__delete__%s' % port.id} url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) class NetworkAgentTests(test.BaseAdminViewTests): @test.create_stubs({api.neutron: ('agent_list', 'network_get', 'list_dhcp_agent_hosting_networks',)}) def test_agent_add_get(self): network = self.networks.first() api.neutron.agent_list(IsA(http.HttpRequest), agent_type='DHCP agent')\ .AndReturn(self.agents.list()) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network.id)\ .AndReturn(self.agents.list()) self.mox.ReplayAll() url = reverse('horizon:admin:networks:adddhcpagent', args=[network.id]) res = self.client.get(url) self.assertTemplateUsed(res, 'admin/networks/agents/add.html') @test.create_stubs({api.neutron: ('agent_list', 'network_get', 'list_dhcp_agent_hosting_networks', 'add_network_to_dhcp_agent',)}) def test_agent_add_post(self): network = self.networks.first() agent_id = self.agents.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network.id)\ .AndReturn([self.agents.list()[1]]) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) api.neutron.agent_list(IsA(http.HttpRequest), agent_type='DHCP agent')\ .AndReturn(self.agents.list()) api.neutron.add_network_to_dhcp_agent(IsA(http.HttpRequest), agent_id, network.id)\ .AndReturn(True) self.mox.ReplayAll() form_data = {'network_id': network.id, 'network_name': network.name, 'agent': agent_id} url = reverse('horizon:admin:networks:adddhcpagent', args=[network.id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse('horizon:admin:networks:detail', args=[network.id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('agent_list', 'network_get', 'list_dhcp_agent_hosting_networks', 'add_network_to_dhcp_agent',)}) def test_agent_add_post_exception(self): network = self.networks.first() agent_id = self.agents.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network.id)\ .AndReturn([self.agents.list()[1]]) api.neutron.network_get(IsA(http.HttpRequest), network.id)\ .AndReturn(network) api.neutron.agent_list(IsA(http.HttpRequest), agent_type='DHCP agent')\ .AndReturn(self.agents.list()) api.neutron.add_network_to_dhcp_agent(IsA(http.HttpRequest), agent_id, network.id)\ .AndRaise(self.exceptions.neutron) self.mox.ReplayAll() form_data = {'network_id': network.id, 'network_name': network.name, 'agent': agent_id} url = reverse('horizon:admin:networks:adddhcpagent', args=[network.id]) res = self.client.post(url, form_data) self.assertNoFormErrors(res) redir_url = reverse('horizon:admin:networks:detail', args=[network.id]) self.assertRedirectsNoFollow(res, redir_url) @test.create_stubs({api.neutron: ('subnet_list', 'port_list', 'list_dhcp_agent_hosting_networks', 'is_extension_supported', 'remove_network_from_dhcp_agent',)}) def test_agent_delete(self): network_id = self.networks.first().id agent_id = self.agents.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.remove_network_from_dhcp_agent(IsA(http.HttpRequest), agent_id, network_id) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(False) self.mox.ReplayAll() form_data = {'action': 'agents__delete__%s' % agent_id} url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url) @test.create_stubs({api.neutron: ('subnet_list', 'port_list', 'list_dhcp_agent_hosting_networks', 'is_extension_supported', 'remove_network_from_dhcp_agent',)}) def test_agent_delete_exception(self): network_id = self.networks.first().id agent_id = self.agents.first().id api.neutron.list_dhcp_agent_hosting_networks(IsA(http.HttpRequest), network_id).\ AndReturn(self.agents.list()) api.neutron.subnet_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.subnets.first()]) api.neutron.port_list(IsA(http.HttpRequest), network_id=network_id)\ .AndReturn([self.ports.first()]) api.neutron.remove_network_from_dhcp_agent(IsA(http.HttpRequest), agent_id, network_id)\ .AndRaise(self.exceptions.neutron) api.neutron.is_extension_supported(IsA(http.HttpRequest), 'mac-learning')\ .AndReturn(False) self.mox.ReplayAll() form_data = {'action': 'agents__delete__%s' % agent_id} url = reverse('horizon:admin:networks:detail', args=[network_id]) res = self.client.post(url, form_data) self.assertRedirectsNoFollow(res, url)
apache-2.0
mailund/IMCoalHMM
scripts/initial-migration-model.py
1
5060
#!/usr/bin/env python """Script for estimating parameters in an initial migration model. """ from argparse import ArgumentParser from IMCoalHMM.likelihood import Likelihood, maximum_likelihood_estimate from IMCoalHMM.isolation_with_migration_model import IsolationMigrationModel from IMCoalHMM.hmm import Forwarder def transform(params): """ Translate the parameters to the input and output parameter space. """ isolation_time, migration_time, coal_rate, recomb_rate, mig_rate = params return isolation_time, migration_time, 2 / coal_rate, recomb_rate, mig_rate def main(): """ Run the main script. """ usage = """%(prog)s [options] <forwarder dirs> This program estimates the parameters of an isolation model with an initial migration period with two species and uniform coalescence and recombination rates.""" parser = ArgumentParser(usage=usage, version="%(prog)s 1.2") parser.add_argument("--header", action="store_true", default=False, help="Include a header on the output") parser.add_argument("-o", "--outfile", type=str, default="/dev/stdout", help="Output file for the estimate (/dev/stdout)") parser.add_argument("--logfile", type=str, default=None, help="Log for all points estimated in the optimization") parser.add_argument("--ancestral-states", type=int, default=10, help="Number of intervals used to discretize the time in the ancestral population (10)") parser.add_argument("--migration-states", type=int, default=10, help="Number of intervals used to discretize the time in the migration period (10)") parser.add_argument("--optimizer", type=str, default="Nelder-Mead", help="Optimization algorithm to use for maximizing the likelihood (Nealder-Mead)", choices=['Nelder-Mead', 'Powell', 'L-BFGS-B', 'TNC']) optimized_params = [ ('isolation-period', 'time where the populations have been isolated', 1e6 / 1e9), ('migration-period', 'time period where the populations exchanged genes', 1e6 / 1e9), ('theta', 'effective population size in 4Ne substitutions', 1e6 / 1e9), ('rho', 'recombination rate in substitutions', 0.4), ('migration-rate', 'migration rate in number of migrations per substitution', 200.0) ] for parameter_name, description, default in optimized_params: parser.add_argument("--%s" % parameter_name, type=float, default=default, help="Initial guess at the %s (%g)" % (description, default)) parser.add_argument('alignments', nargs='+', help='Alignments in ZipHMM format') options = parser.parse_args() if len(options.alignments) < 1: parser.error("Input alignment not provided!") # get options no_migration_states = options.migration_states no_ancestral_states = options.ancestral_states theta = options.theta rho = options.rho forwarders = [Forwarder(arg, NSYM = 3) for arg in options.alignments] init_isolation_time = options.isolation_period init_migration_time = options.migration_period init_coal = 1 / (theta / 2) init_recomb = rho init_migration = options.migration_rate log_likelihood = Likelihood(IsolationMigrationModel(no_migration_states, no_ancestral_states), forwarders) initial_parameters = (init_isolation_time, init_migration_time, init_coal, init_recomb, init_migration) if options.logfile: with open(options.logfile, 'w') as logfile: if options.header: print >> logfile, '\t'.join(['isolation.period', 'migration.period', 'theta', 'rho', 'migration']) mle_parameters = \ maximum_likelihood_estimate(log_likelihood, initial_parameters, log_file=logfile, optimizer_method=options.optimizer, log_param_transform=transform) else: mle_parameters = \ maximum_likelihood_estimate(log_likelihood, initial_parameters, optimizer_method=options.optimizer) max_log_likelihood = log_likelihood(mle_parameters) with open(options.outfile, 'w') as outfile: if options.header: print >> outfile, '\t'.join(['isolation.period', 'migration.period', 'theta', 'rho', 'migration', 'log.likelihood']) print >> outfile, '\t'.join(map(str, transform(mle_parameters) + (max_log_likelihood,))) if __name__ == '__main__': main()
gpl-2.0
prasadvagdargi/med_image_analysis
Examples/Python/DicomModifyTags.py
2
2876
#========================================================================= # # Copyright Insight Software Consortium # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0.txt # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #========================================================================= from __future__ import print_function import SimpleITK as sitk import sys, time if len( sys.argv ) < 3: print( "Usage: python " + __file__ + " <input_image> <output_image>" ) sys.exit ( 1 ) # Read the image, single 3D DICOM slice image = sitk.ReadImage( sys.argv[1] ) # Modify the image (mean) mean_image = sitk.BoxMean( image, [3,3,1] ) # Save the modified image: # We do not provide a method that copies all keys blindly. Our intent is # to force us to remember that we always need to modify the meta-data dicitonary # keys when we save processed images in DICOM format. # In case of the DICOM format, amongst other keys we need to set the Image Type (0008,0008), # the Series Date (0008,0021), and Series Time (0008,0021). Obviously we need to set a # different series number (0020,0011), series instance UID (0020,000E), etc. - we don't do # that here. # Please see the DICOM standard (http://dicom.nema.org/standard.html) for complete details on # how to create valid DICOM images. all_keys = image.GetMetaDataKeys() for key in all_keys: mean_image.SetMetaData( key, image.GetMetaData( key ) ) mean_image.SetMetaData( "0008|0008", "DERIVED\SECONDARY" ) modification_time = time.strftime("%H%M%S") modification_date = time.strftime("%Y%m%d") mean_image.SetMetaData( "0008|0031", modification_time ) mean_image.SetMetaData( "0008|0021", modification_date ) sitk.WriteImage( mean_image, sys.argv[2] ) # Finally, read the image back and see that changes were made # Note that the image type (0008|0008) can contain additional spaces. The requirement is that # the string have an even length (ftp://dicom.nema.org/medical/DICOM/2013/output/chtml/part05/sect_6.2.html). # Where spaces are added is not specified and thus may vary ("DERIVED\SECONDARY ", "DERIVED\ SECONDARY" are # equivalent). modified_image = sitk.ReadImage( sys.argv[2] ) if modified_image.GetMetaData( "0008|0008" ).replace(" ","") != "DERIVED\SECONDARY" or \ modified_image.GetMetaData( "0008|0031" ) != modification_time or \ modified_image.GetMetaData( "0008|0021" ) != modification_date: sys.exit(1) sys.exit( 0 )
apache-2.0
pexip/os-python-suds-jurko
suds/cache.py
1
8166
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library Lesser General Public License for more details at # ( http://www.gnu.org/licenses/lgpl.html ). # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( jortel@redhat.com ) """ Contains basic caching classes. """ import suds from suds.transport import * from suds.sax.parser import Parser from suds.sax.element import Element from datetime import datetime as dt from datetime import timedelta from logging import getLogger import os from tempfile import gettempdir as tmp try: import cPickle as pickle except Exception: import pickle log = getLogger(__name__) class Cache: """ An object object cache. """ def get(self, id): """ Get a object from the cache by ID. @param id: The object ID. @type id: str @return: The object, else None @rtype: any """ raise Exception('not-implemented') def put(self, id, object): """ Put a object into the cache. @param id: The object ID. @type id: str @param object: The object to add. @type object: any """ raise Exception('not-implemented') def purge(self, id): """ Purge a object from the cache by id. @param id: A object ID. @type id: str """ raise Exception('not-implemented') def clear(self): """ Clear all objects from the cache. """ raise Exception('not-implemented') class NoCache(Cache): """ The passthru object cache. """ def get(self, id): return None def put(self, id, object): pass class FileCache(Cache): """ A file-based URL cache. @cvar fnprefix: The file name prefix. @type fnsuffix: str @ivar duration: The cached file duration which defines how long the file will be cached. @type duration: (unit, value) @ivar location: The directory for the cached files. @type location: str """ fnprefix = 'suds' units = ('months', 'weeks', 'days', 'hours', 'minutes', 'seconds') def __init__(self, location=None, **duration): """ @param location: The directory for the cached files. @type location: str @param duration: The cached file duration which defines how long the file will be cached. A duration=0 means forever. The duration may be: (months|weeks|days|hours|minutes|seconds). @type duration: {unit:value} """ if location is None: location = os.path.join(tmp(), 'suds') self.location = location self.duration = (None, 0) self.setduration(**duration) self.checkversion() def fnsuffix(self): """ Get the file name suffix @return: The suffix @rtype: str """ return 'gcf' def setduration(self, **duration): """ Set the caching duration which defines how long the file will be cached. @param duration: The cached file duration which defines how long the file will be cached. A duration=0 means forever. The duration may be: (months|weeks|days|hours|minutes|seconds). @type duration: {unit:value} """ if len(duration) == 1: arg = duration.items()[0] if not arg[0] in self.units: raise Exception('must be: %s' % str(self.units)) self.duration = arg return self def setlocation(self, location): """ Set the location (directory) for the cached files. @param location: The directory for the cached files. @type location: str """ self.location = location def mktmp(self): """ Make the I{location} directory if it doesn't already exits. """ try: if not os.path.isdir(self.location): os.makedirs(self.location) except Exception: log.debug(self.location, exc_info=1) return self def put(self, id, bfr): try: fn = self.__fn(id) f = self.open(fn, 'wb') try: f.write(bfr) finally: f.close() return bfr except Exception: log.debug(id, exc_info=1) return bfr def get(self, id): try: f = self.getf(id) try: return f.read() finally: f.close() except Exception: pass def getf(self, id): try: fn = self.__fn(id) self.validate(fn) return self.open(fn, 'rb') except Exception: pass def validate(self, fn): """ Validate that the file has not expired based on the I{duration}. @param fn: The file name. @type fn: str """ if self.duration[1] < 1: return created = dt.fromtimestamp(os.path.getctime(fn)) d = {self.duration[0]:self.duration[1]} expired = created + timedelta(**d) if expired < dt.now(): log.debug('%s expired, deleted', fn) os.remove(fn) def clear(self): for fn in os.listdir(self.location): path = os.path.join(self.location, fn) if os.path.isdir(path): continue if fn.startswith(self.fnprefix): os.remove(path) log.debug('deleted: %s', path) def purge(self, id): fn = self.__fn(id) try: os.remove(fn) except Exception: pass def open(self, fn, *args): """ Open the cache file making sure the directory is created. """ self.mktmp() return open(fn, *args) def checkversion(self): path = os.path.join(self.location, 'version') try: f = self.open(path) version = f.read() f.close() if version != suds.__version__: raise Exception() except Exception: self.clear() f = self.open(path, 'w') f.write(suds.__version__) f.close() def __fn(self, id): name = id suffix = self.fnsuffix() fn = '%s-%s.%s' % (self.fnprefix, name, suffix) return os.path.join(self.location, fn) class DocumentCache(FileCache): """ Provides xml document caching. """ def fnsuffix(self): return 'xml' def get(self, id): try: fp = self.getf(id) if fp is None: return None p = Parser() return p.parse(fp) except Exception: self.purge(id) def put(self, id, object): if isinstance(object, Element): FileCache.put(self, id, suds.byte_str(str(object))) return object class ObjectCache(FileCache): """ Provides pickled object caching. @cvar protocol: The pickling protocol. @type protocol: int """ protocol = 2 def fnsuffix(self): return 'px' def get(self, id): try: fp = self.getf(id) if fp is None: return None return pickle.load(fp) except Exception: self.purge(id) def put(self, id, object): bfr = pickle.dumps(object, self.protocol) FileCache.put(self, id, bfr) return object
lgpl-3.0
10clouds/edx-platform
common/djangoapps/enrollment/management/tests/test_enroll_user_in_course.py
62
2563
""" Test the change_enrollment command line script.""" import ddt import unittest from uuid import uuid4 from django.conf import settings from django.core.management import call_command from django.core.management.base import CommandError from enrollment.api import get_enrollment from student.tests.factories import UserFactory from xmodule.modulestore.tests.django_utils import SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory @ddt.ddt @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') class EnrollManagementCommandTest(SharedModuleStoreTestCase): """ Test the enroll_user_in_course management command """ @classmethod def setUpClass(cls): super(EnrollManagementCommandTest, cls).setUpClass() cls.course = CourseFactory.create(org='fooX', number='007') def setUp(self): super(EnrollManagementCommandTest, self).setUp() self.course_id = unicode(self.course.id) self.username = 'ralph' + uuid4().hex self.user_email = self.username + '@example.com' UserFactory(username=self.username, email=self.user_email) def test_enroll_user(self): command_args = [ '--course', self.course_id, '--email', self.user_email, ] call_command( 'enroll_user_in_course', *command_args ) user_enroll = get_enrollment(self.username, self.course_id) self.assertTrue(user_enroll['is_active']) def test_enroll_user_twice(self): """ Ensures the command is idempotent. """ command_args = [ '--course', self.course_id, '--email', self.user_email, ] for _ in range(2): call_command( 'enroll_user_in_course', *command_args ) # Second run does not impact the first run (i.e., the # user is still enrolled, no exception was raised, etc) user_enroll = get_enrollment(self.username, self.course_id) self.assertTrue(user_enroll['is_active']) @ddt.data(['--email', 'foo'], ['--course', 'bar'], ['--bad-param', 'baz']) def test_not_enough_args(self, arg): """ When the command is missing certain arguments, it should raise an exception """ command_args = arg with self.assertRaises(CommandError): call_command( 'enroll_user_in_course', *command_args )
agpl-3.0
brentp/bio-playground
mosaic/filter-functional.py
1
1442
from __future__ import print_function import sys from geneimpacts import VEP def isfunctional(csq): if csq['BIOTYPE'] != 'protein_coding': return False if csq['Feature'] == '' or csq['EXON'] == '': return False return ("splic" in csq['Consequence']) or any(c in ('stop_gained', 'stop_lost', 'start_lost', 'initiator_codon_variant', 'rare_amino_acid_variant', 'missense_variant', 'protein_altering_variant', 'frameshift_variant') for c in csq['Consequence'].split('&')) def get_csq_keys(line): keys = line.split("Format:")[1].strip().strip('>"').split("|") return keys for i, line in enumerate(sys.stdin): if line[0] == "#": print(line, end="") if "<ID=CSQ," in line: csq_keys = get_csq_keys(line) continue if i % 1000 == 0: print("filter: %d" % i, file=sys.stderr) toks = line.rstrip().split("\t") info = toks[7] pos = info.index('CSQ=') + 4 vi = info[pos:].split(";")[0] veps = [VEP(c, keys=csq_keys) for c in vi.split(",")] if not any(isfunctional(v) for v in veps): continue if 'max_aaf_all=' in info: vals = info.split('max_aaf_all=')[1].split(";")[0].split(",") if max(map(float, vals)) > 0.001: print("skipping because of max_aaf_all:", line, file=sys.stderr) continue print(line, end="") sys.stdout.flush()
mit
bkahlert/seqan-research
raw/pmbs12/pmsb13-data-20120615/trunk/misc/seqan_instrumentation/bin/classes/simplejson/__init__.py
25
20581
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. :mod:`simplejson` exposes an API familiar to users of the standard library :mod:`marshal` and :mod:`pickle` modules. It is the externally maintained version of the :mod:`json` library contained in Python 2.6, but maintains compatibility with Python 2.4 and Python 2.5 and (currently) has significant performance advantages, even without using the optional C extension for speedups. Encoding basic Python object hierarchies:: >>> import simplejson as json >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) '["foo", {"bar": ["baz", null, 1.0, 2]}]' >>> print json.dumps("\"foo\bar") "\"foo\bar" >>> print json.dumps(u'\u1234') "\u1234" >>> print json.dumps('\\') "\\" >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) {"a": 0, "b": 0, "c": 0} >>> from StringIO import StringIO >>> io = StringIO() >>> json.dump(['streaming API'], io) >>> io.getvalue() '["streaming API"]' Compact encoding:: >>> import simplejson as json >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':')) '[1,2,3,{"4":5,"6":7}]' Pretty printing:: >>> import simplejson as json >>> s = json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=' ') >>> print '\n'.join([l.rstrip() for l in s.splitlines()]) { "4": 5, "6": 7 } Decoding JSON:: >>> import simplejson as json >>> obj = [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') == obj True >>> json.loads('"\\"foo\\bar"') == u'"foo\x08ar' True >>> from StringIO import StringIO >>> io = StringIO('["streaming API"]') >>> json.load(io)[0] == 'streaming API' True Specializing JSON object decoding:: >>> import simplejson as json >>> def as_complex(dct): ... if '__complex__' in dct: ... return complex(dct['real'], dct['imag']) ... return dct ... >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}', ... object_hook=as_complex) (1+2j) >>> from decimal import Decimal >>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1') True Specializing JSON object encoding:: >>> import simplejson as json >>> def encode_complex(obj): ... if isinstance(obj, complex): ... return [obj.real, obj.imag] ... raise TypeError(repr(o) + " is not JSON serializable") ... >>> json.dumps(2 + 1j, default=encode_complex) '[2.0, 1.0]' >>> json.JSONEncoder(default=encode_complex).encode(2 + 1j) '[2.0, 1.0]' >>> ''.join(json.JSONEncoder(default=encode_complex).iterencode(2 + 1j)) '[2.0, 1.0]' Using simplejson.tool from the shell to validate and pretty-print:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expecting property name: line 1 column 2 (char 2) """ __version__ = '2.5.0' __all__ = [ 'dump', 'dumps', 'load', 'loads', 'JSONDecoder', 'JSONDecodeError', 'JSONEncoder', 'OrderedDict', 'simple_first', ] __author__ = 'Bob Ippolito <bob@redivi.com>' from decimal import Decimal from decoder import JSONDecoder, JSONDecodeError from encoder import JSONEncoder def _import_OrderedDict(): import collections try: return collections.OrderedDict except AttributeError: import ordered_dict return ordered_dict.OrderedDict OrderedDict = _import_OrderedDict() def _import_c_make_encoder(): try: from simplejson._speedups import make_encoder return make_encoder except ImportError: return None _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, item_sort_key=None, ) def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, **kw): """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object). If ``skipkeys`` is true then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the some chunks written to ``fp`` may be ``unicode`` instances, subject to normal Python ``str`` to ``unicode`` coercion rules. Unless ``fp.write()`` explicitly understands ``unicode`` (as in ``codecs.getwriter()``) this is likely to cause an error. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If *indent* is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``True``) then decimal.Decimal will be natively serialized to JSON with full precision. If *namedtuple_as_object* is true (default: ``True``), :class:`tuple` subclasses with ``_asdict()`` methods will be encoded as JSON objects. If *tuple_as_array* is true (default: ``True``), :class:`tuple` (and subclasses) will be encoded as JSON arrays. If *bigint_as_string* is true (default: ``False``), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. Note that this is still a lossy operation that will not round-trip correctly and should be used sparingly. If specified, *item_sort_key* is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. This option takes precedence over *sort_keys*. If *sort_keys* is true (default: ``False``), the output of dictionaries will be sorted by item. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not bigint_as_string and not item_sort_key and not kw): iterable = _default_encoder.iterencode(obj) else: if cls is None: cls = JSONEncoder iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, **kw).iterencode(obj) # could accelerate with writelines in some versions of Python, at # a debuggability cost for chunk in iterable: fp.write(chunk) def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding='utf-8', default=None, use_decimal=True, namedtuple_as_object=True, tuple_as_array=True, bigint_as_string=False, sort_keys=False, item_sort_key=None, **kw): """Serialize ``obj`` to a JSON formatted ``str``. If ``skipkeys`` is false then ``dict`` keys that are not basic types (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``) will be skipped instead of raising a ``TypeError``. If ``ensure_ascii`` is false, then the return value will be a ``unicode`` instance subject to normal Python ``str`` to ``unicode`` coercion rules instead of being escaped to an ASCII ``str``. If ``check_circular`` is false, then the circular reference check for container types will be skipped and a circular reference will result in an ``OverflowError`` (or worse). If ``allow_nan`` is false, then it will be a ``ValueError`` to serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``). If ``indent`` is a string, then JSON array elements and object members will be pretty-printed with a newline followed by that string repeated for each level of nesting. ``None`` (the default) selects the most compact representation without any newlines. For backwards compatibility with versions of simplejson earlier than 2.1.0, an integer is also accepted and is converted to a string with that many spaces. If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. ``encoding`` is the character encoding for str instances, default is UTF-8. ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. If *use_decimal* is true (default: ``True``) then decimal.Decimal will be natively serialized to JSON with full precision. If *namedtuple_as_object* is true (default: ``True``), :class:`tuple` subclasses with ``_asdict()`` methods will be encoded as JSON objects. If *tuple_as_array* is true (default: ``True``), :class:`tuple` (and subclasses) will be encoded as JSON arrays. If *bigint_as_string* is true (not the default), ints 2**53 and higher or lower than -2**53 will be encoded as strings. This is to avoid the rounding that happens in Javascript otherwise. If specified, *item_sort_key* is a callable used to sort the items in each dictionary. This is useful if you want to sort items other than in alphabetical order by key. This option takes precendence over *sort_keys*. If *sort_keys* is true (default: ``False``), the output of dictionaries will be sorted by item. To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the ``.default()`` method to serialize additional types), specify it with the ``cls`` kwarg. """ # cached encoder if (not skipkeys and ensure_ascii and check_circular and allow_nan and cls is None and indent is None and separators is None and encoding == 'utf-8' and default is None and use_decimal and namedtuple_as_object and tuple_as_array and not bigint_as_string and not sort_keys and not item_sort_key and not kw): return _default_encoder.encode(obj) if cls is None: cls = JSONEncoder return cls( skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, indent=indent, separators=separators, encoding=encoding, default=default, use_decimal=use_decimal, namedtuple_as_object=namedtuple_as_object, tuple_as_array=tuple_as_array, bigint_as_string=bigint_as_string, sort_keys=sort_keys, item_sort_key=item_sort_key, **kw).encode(obj) _default_decoder = JSONDecoder(encoding=None, object_hook=None, object_pairs_hook=None) def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, namedtuple_as_object=True, tuple_as_array=True, **kw): """Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, use_decimal=use_decimal, **kw) def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): """Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON document) to a Python object. *encoding* determines the encoding used to interpret any :class:`str` objects decoded by this instance (``'utf-8'`` by default). It has no effect when decoding :class:`unicode` objects. Note that currently only encodings that are a superset of ASCII work, strings of other encodings should be passed in as :class:`unicode`. *object_hook*, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given :class:`dict`. This can be used to provide custom deserializations (e.g. to support JSON-RPC class hinting). *object_pairs_hook* is an optional function that will be called with the result of any object literal decode with an ordered list of pairs. The return value of *object_pairs_hook* will be used instead of the :class:`dict`. This feature can be used to implement custom decoders that rely on the order that the key and value pairs are decoded (for example, :func:`collections.OrderedDict` will remember the order of insertion). If *object_hook* is also defined, the *object_pairs_hook* takes priority. *parse_float*, if specified, will be called with the string of every JSON float to be decoded. By default, this is equivalent to ``float(num_str)``. This can be used to use another datatype or parser for JSON floats (e.g. :class:`decimal.Decimal`). *parse_int*, if specified, will be called with the string of every JSON int to be decoded. By default, this is equivalent to ``int(num_str)``. This can be used to use another datatype or parser for JSON integers (e.g. :class:`float`). *parse_constant*, if specified, will be called with one of the following strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``. This can be used to raise an exception if invalid JSON numbers are encountered. If *use_decimal* is true (default: ``False``) then it implies parse_float=decimal.Decimal for parity with ``dump``. To use a custom ``JSONDecoder`` subclass, specify it with the ``cls`` kwarg. """ if (cls is None and encoding is None and object_hook is None and parse_int is None and parse_float is None and parse_constant is None and object_pairs_hook is None and not use_decimal and not kw): return _default_decoder.decode(s) if cls is None: cls = JSONDecoder if object_hook is not None: kw['object_hook'] = object_hook if object_pairs_hook is not None: kw['object_pairs_hook'] = object_pairs_hook if parse_float is not None: kw['parse_float'] = parse_float if parse_int is not None: kw['parse_int'] = parse_int if parse_constant is not None: kw['parse_constant'] = parse_constant if use_decimal: if parse_float is not None: raise TypeError("use_decimal=True implies parse_float=Decimal") kw['parse_float'] = Decimal return cls(encoding=encoding, **kw).decode(s) def _toggle_speedups(enabled): import simplejson.decoder as dec import simplejson.encoder as enc import simplejson.scanner as scan c_make_encoder = _import_c_make_encoder() if enabled: dec.scanstring = dec.c_scanstring or dec.py_scanstring enc.c_make_encoder = c_make_encoder enc.encode_basestring_ascii = (enc.c_encode_basestring_ascii or enc.py_encode_basestring_ascii) scan.make_scanner = scan.c_make_scanner or scan.py_make_scanner else: dec.scanstring = dec.py_scanstring enc.c_make_encoder = None enc.encode_basestring_ascii = enc.py_encode_basestring_ascii scan.make_scanner = scan.py_make_scanner dec.make_scanner = scan.make_scanner global _default_decoder _default_decoder = JSONDecoder( encoding=None, object_hook=None, object_pairs_hook=None, ) global _default_encoder _default_encoder = JSONEncoder( skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, indent=None, separators=None, encoding='utf-8', default=None, ) def simple_first(kv): """Helper function to pass to item_sort_key to sort simple elements to the top, then container elements. """ return (isinstance(kv[1], (list, dict, tuple)), kv[0])
mit
B-MOOC/edx-platform
openedx/core/djangoapps/content/course_structures/migrations/0001_initial.py
102
1759
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'CourseStructure' db.create_table('course_structures_coursestructure', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('created', self.gf('model_utils.fields.AutoCreatedField')(default=datetime.datetime.now)), ('modified', self.gf('model_utils.fields.AutoLastModifiedField')(default=datetime.datetime.now)), ('course_id', self.gf('xmodule_django.models.CourseKeyField')(unique=True, max_length=255, db_index=True)), ('structure_json', self.gf('django.db.models.fields.TextField')(null=True, blank=True)), )) db.send_create_signal('course_structures', ['CourseStructure']) def backwards(self, orm): # Deleting model 'CourseStructure' db.delete_table('course_structures_coursestructure') models = { 'course_structures.coursestructure': { 'Meta': {'object_name': 'CourseStructure'}, 'course_id': ('xmodule_django.models.CourseKeyField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}), 'structure_json': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}) } } complete_apps = ['course_structures']
agpl-3.0
edx/edx-enterprise
integrated_channels/integrated_channel/transmitters/learner_data.py
1
15549
# -*- coding: utf-8 -*- """ Generic learner data transmitter for integrated channels. """ import logging from django.apps import apps from integrated_channels.exceptions import ClientError from integrated_channels.integrated_channel.client import IntegratedChannelApiClient from integrated_channels.integrated_channel.exporters.learner_data import LearnerExporterUtility from integrated_channels.integrated_channel.transmitters import Transmitter from integrated_channels.utils import generate_formatted_log, is_already_transmitted LOGGER = logging.getLogger(__name__) class LearnerTransmitter(Transmitter): """ A generic learner data transmitter. It may be subclassed by specific integrated channel learner data transmitters for each integrated channel's particular learner data transmission requirements and expectations. """ def __init__(self, enterprise_configuration, client=IntegratedChannelApiClient): """ By default, use the abstract integrated channel API client which raises an error when used if not subclassed. """ super().__init__( enterprise_configuration=enterprise_configuration, client=client ) def _generate_common_params(self, **kwargs): """ Pulls labeled common params out of kwargs """ app_label = kwargs.get('app_label', 'integrated_channel') enterprise_customer_uuid = self.enterprise_configuration.enterprise_customer.uuid or None lms_user_id = kwargs.get('learner_to_transmit', None) return app_label, enterprise_customer_uuid, lms_user_id def single_learner_assessment_grade_transmit(self, exporter, **kwargs): """ Send an assessment level grade information to the integrated channel using the client. Args: exporter: The ``LearnerExporter`` instance used to send to the integrated channel. kwargs: Contains integrated channel-specific information for customized transmission variables. - app_label: The app label of the integrated channel for whom to store learner data records for. - model_name: The name of the specific learner data record model to use. - remote_user_id: The remote ID field name on the audit model that will map to the learner. """ app_label, enterprise_customer_uuid, lms_user_id = self._generate_common_params(**kwargs) TransmissionAudit = apps.get_model( # pylint: disable=invalid-name app_label=app_label, model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'), ) kwargs.update( TransmissionAudit=TransmissionAudit, ) # Even though we're transmitting a learner, they can have records per assessment (multiple per course). for learner_data in exporter.single_assessment_level_export(**kwargs): LOGGER.info(generate_formatted_log( app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id, 'create_assessment_reporting started for enrollment {enrollment_id}'.format( enrollment_id=learner_data.enterprise_course_enrollment_id, ))) serialized_payload = learner_data.serialize(enterprise_configuration=self.enterprise_configuration) try: code, body = self.client.create_assessment_reporting( getattr(learner_data, kwargs.get('remote_user_id')), serialized_payload ) except ClientError as client_error: code = client_error.status_code body = client_error.message self.handle_transmission_error(learner_data, client_error, app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id) except Exception: # Log additional data to help debug failures but just have Exception bubble self._log_exception_supplemental_data( learner_data, 'create_assessment_reporting', app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id) raise learner_data.status = str(code) learner_data.error_message = body if code >= 400 else '' learner_data.save() def assessment_level_transmit(self, exporter, **kwargs): """ Send all assessment level grade information under an enterprise enrollment to the integrated channel using the client. Args: exporter: The learner assessment data exporter used to send to the integrated channel. kwargs: Contains integrated channel-specific information for customized transmission variables. - app_label: The app label of the integrated channel for whom to store learner data records for. - model_name: The name of the specific learner data record model to use. - remote_user_id: The remote ID field name of the learner on the audit model. """ app_label, enterprise_customer_uuid, _ = self._generate_common_params(**kwargs) TransmissionAudit = apps.get_model( # pylint: disable=invalid-name app_label=app_label, model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'), ) kwargs.update( TransmissionAudit=TransmissionAudit, ) # Retrieve learner data for each existing enterprise enrollment under the enterprise customer # and transmit the data according to the current enterprise configuration. for learner_data in exporter.bulk_assessment_level_export(): serialized_payload = learner_data.serialize(enterprise_configuration=self.enterprise_configuration) enterprise_enrollment_id = learner_data.enterprise_course_enrollment_id lms_user_id = LearnerExporterUtility.lms_user_id_for_ent_course_enrollment_id( enterprise_enrollment_id) # Check the last transmission for the current enrollment and see if the old grades match the new ones if is_already_transmitted( TransmissionAudit, enterprise_enrollment_id, learner_data.grade, learner_data.subsection_id ): # We've already sent a completion status for this enrollment LOGGER.info(generate_formatted_log( app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id, 'Skipping previously sent EnterpriseCourseEnrollment {}'.format(enterprise_enrollment_id) )) continue try: code, body = self.client.create_assessment_reporting( getattr(learner_data, kwargs.get('remote_user_id')), serialized_payload ) LOGGER.info(generate_formatted_log( app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id, 'create_assessment_reporting successfully completed for EnterpriseCourseEnrollment {}'.format( enterprise_enrollment_id, ) )) except ClientError as client_error: code = client_error.status_code body = client_error.message self.handle_transmission_error(learner_data, client_error, app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id) except Exception: # Log additional data to help debug failures but just have Exception bubble self._log_exception_supplemental_data( learner_data, 'create_assessment_reporting', app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id) raise learner_data.status = str(code) learner_data.error_message = body if code >= 400 else '' learner_data.save() def transmit(self, payload, **kwargs): """ Send a completion status call to the integrated channel using the client. Args: payload: The learner completion data payload to send to the integrated channel. kwargs: Contains integrated channel-specific information for customized transmission variables. - app_label: The app label of the integrated channel for whom to store learner data records for. - model_name: The name of the specific learner data record model to use. - remote_user_id: The remote ID field name of the learner on the audit model. """ app_label, enterprise_customer_uuid, _ = self._generate_common_params(**kwargs) TransmissionAudit = apps.get_model( # pylint: disable=invalid-name app_label=app_label, model_name=kwargs.get('model_name', 'LearnerDataTransmissionAudit'), ) kwargs.update( TransmissionAudit=TransmissionAudit, ) # Since we have started sending courses to integrated channels instead of course runs, # we need to attempt to send transmissions with course keys and course run ids in order to # ensure that we account for whether courses or course runs exist in the integrated channel. # The exporters have been changed to return multiple transmission records to attempt, # one by course key and one by course run id. # If the transmission with the course key succeeds, the next one will get skipped. # If it fails, the one with the course run id will be attempted and (presumably) succeed. for learner_data in payload.export(**kwargs): serialized_payload = learner_data.serialize(enterprise_configuration=self.enterprise_configuration) enterprise_enrollment_id = learner_data.enterprise_course_enrollment_id lms_user_id = LearnerExporterUtility.lms_user_id_for_ent_course_enrollment_id( enterprise_enrollment_id) if learner_data.completed_timestamp is None: # The user has not completed the course, so we shouldn't send a completion status call LOGGER.info('Skipping in-progress enterprise enrollment {}'.format(enterprise_enrollment_id)) continue grade = getattr(learner_data, 'grade', None) if is_already_transmitted(TransmissionAudit, enterprise_enrollment_id, grade): # We've already sent a completion status for this enrollment LOGGER.info(generate_formatted_log( app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id, 'Skipping previously sent enterprise enrollment {}'.format(enterprise_enrollment_id))) continue try: code, body = self.client.create_course_completion( getattr(learner_data, kwargs.get('remote_user_id')), serialized_payload ) LOGGER.info(generate_formatted_log( app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id, 'Successfully sent completion status call for enterprise enrollment {}'.format( enterprise_enrollment_id, ) )) except ClientError as client_error: code = client_error.status_code body = client_error.message self.handle_transmission_error(learner_data, client_error, app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id) except Exception: # Log additional data to help debug failures but have Exception bubble self._log_exception_supplemental_data( learner_data, 'create_assessment_reporting', app_label, enterprise_customer_uuid, lms_user_id, learner_data.course_id) raise learner_data.status = str(code) learner_data.error_message = body if code >= 400 else '' learner_data.save() def deduplicate_assignment_records_transmit(self, exporter, **kwargs): """ Remove duplicated assessments sent to the integrated channel using the client. Args: exporter: The learner completion data payload to send to the integrated channel. kwargs: Contains integrated channel-specific information for customized transmission variables. - app_label: The app label of the integrated channel for whom to store learner data records for. - model_name: The name of the specific learner data record model to use. - remote_user_id: The remote ID field name of the learner on the audit model. """ app_label, enterprise_customer_uuid, _ = self._generate_common_params(**kwargs) courses = exporter.export_unique_courses() code, body = self.client.cleanup_duplicate_assignment_records(courses) if code >= 400: LOGGER.exception(generate_formatted_log( app_label, enterprise_customer_uuid, None, None, 'Deduping assignments transmission experienced a failure, received the error message: {}'.format(body) )) else: LOGGER.info(generate_formatted_log( app_label, enterprise_customer_uuid, None, None, 'Deduping assignments transmission finished successfully, received message: {}'.format(body) )) def _log_exception_supplemental_data(self, learner_data, operation_name, integrated_channel_name, enterprise_customer_uuid, learner_id, course_id): """ Logs extra payload and parameter data to help debug which learner data caused an exception. """ LOGGER.exception(generate_formatted_log( integrated_channel_name, enterprise_customer_uuid, learner_id, course_id, '{operation_name} failed with Exception for ' 'enterprise enrollment {enrollment_id} with payload {payload}'.format( operation_name=operation_name, enrollment_id=learner_data.enterprise_course_enrollment_id, payload=learner_data )), exc_info=True) def handle_transmission_error(self, learner_data, client_exception, integrated_channel_name, enterprise_customer_uuid, learner_id, course_id): """Handle the case where the transmission fails.""" LOGGER.exception(generate_formatted_log( integrated_channel_name, enterprise_customer_uuid, learner_id, course_id, 'Failed to send completion status call for enterprise enrollment {}' 'with payload {}' '\nError message: {}' '\nError status code: {}'.format( learner_data.enterprise_course_enrollment_id, learner_data, client_exception.message, client_exception.status_code )))
agpl-3.0
arborh/tensorflow
tensorflow/python/kernel_tests/conv_ops_3d_test.py
7
28590
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for 3d convolutional operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import test_util from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import nn_ops import tensorflow.python.ops.nn_grad # pylint: disable=unused-import from tensorflow.python.platform import test from tensorflow.python.util.compat import collections_abc from tensorflow.python.eager import context def GetTestConfigs(): """Get all the valid tests configs to run. Returns: all the valid test configs as tuples of data_format and use_gpu. """ test_configs = [("NDHWC", False), ("NDHWC", True)] if test.is_gpu_available(cuda_only=True): # "NCDHW" format is only supported on CUDA. test_configs += [("NCDHW", True)] return test_configs class Conv3DTest(test.TestCase): def _DtypesToTest(self, use_gpu): # double datatype is currently not supported for convolution ops # on the ROCm platform optional_float64 = [] if test.is_built_with_rocm() else [dtypes.float64] if use_gpu: if not test_util.GpuSupportsHalfMatMulAndConv(): return optional_float64 + [dtypes.float32] else: # It is important that float32 comes before float16 here, # as we will be using its gradients as reference for fp16 gradients. return optional_float64 + [dtypes.float32, dtypes.float16] else: return optional_float64 + [dtypes.float32, dtypes.float16] def _SetupValuesForDevice(self, tensor_in_sizes, filter_in_sizes, stride, padding, data_format, dtype, use_gpu): total_size_tensor = 1 total_size_filter = 1 for s in tensor_in_sizes: total_size_tensor *= s for s in filter_in_sizes: total_size_filter *= s # Initializes the input tensor with array containing numbers from 0 to 1. # We keep the input tensor values fairly small to avoid overflowing float16 # during the conv3d. x1 = [f * 1.0 / total_size_tensor for f in range(1, total_size_tensor + 1)] x2 = [f * 1.0 / total_size_filter for f in range(1, total_size_filter + 1)] with self.cached_session(use_gpu=use_gpu): t1 = constant_op.constant(x1, shape=tensor_in_sizes, dtype=dtype) t2 = constant_op.constant(x2, shape=filter_in_sizes, dtype=dtype) if isinstance(stride, collections_abc.Iterable): strides = [1] + list(stride) + [1] else: strides = [1, stride, stride, stride, 1] if data_format == "NCDHW": t1 = test_util.NHWCToNCHW(t1) strides = test_util.NHWCToNCHW(strides) conv = nn_ops.conv3d(t1, t2, strides, padding=padding, data_format=data_format) if data_format == "NCDHW": conv = test_util.NCHWToNHWC(conv) return conv def _VerifyValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, expected): results = [] for data_format, use_gpu in GetTestConfigs(): for dtype in self._DtypesToTest(use_gpu): result = self._SetupValuesForDevice( tensor_in_sizes, filter_in_sizes, stride, padding, data_format, dtype, use_gpu=use_gpu) results.append(result) with self.cached_session() as sess: values = self.evaluate(results) for value in values: print("expected = ", expected) print("actual = ", value) tol = 1e-6 if value.dtype == np.float16: tol = 1e-3 self.assertAllClose(expected, value.flatten(), atol=tol, rtol=tol) def _ComputeReferenceDilatedConv(self, tensor_in_sizes, filter_in_sizes, stride, dilation, padding, data_format, use_gpu): total_size_tensor = 1 total_size_filter = 1 for s in tensor_in_sizes: total_size_tensor *= s for s in filter_in_sizes: total_size_filter *= s # Initializes the input tensor with array containing incrementing # numbers from 1. x1 = [f * 1.0 for f in range(1, total_size_tensor + 1)] x2 = [f * 1.0 for f in range(1, total_size_filter + 1)] with self.cached_session(use_gpu=use_gpu): t1 = constant_op.constant(x1, shape=tensor_in_sizes) t2 = constant_op.constant(x2, shape=filter_in_sizes) if isinstance(stride, collections_abc.Iterable): strides = list(stride) else: strides = [stride, stride, stride] if data_format == "NCDHW": t1 = test_util.NHWCToNCHW(t1) full_strides = [1, 1] + strides full_dilation = [1, 1] + dilation else: full_strides = [1] + strides + [1] full_dilation = [1] + dilation + [1] expected = nn_ops.convolution( t1, t2, padding=padding, strides=strides, dilation_rate=dilation, data_format=data_format) computed = nn_ops.conv3d( t1, t2, strides=full_strides, dilations=full_dilation, padding=padding, data_format=data_format) if data_format == "NCDHW": expected = test_util.NCHWToNHWC(expected) computed = test_util.NCHWToNHWC(computed) return expected, computed def _VerifyDilatedConvValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, dilations): expected_results = [] computed_results = [] default_dilations = ( dilations[0] == 1 and dilations[1] == 1 and dilations[2] == 1) for data_format, use_gpu in GetTestConfigs(): # If any dilation rate is larger than 1, only do test on the GPU # because we currently do not have a CPU implementation for arbitrary # dilation rates. if default_dilations or use_gpu: expected, computed = self._ComputeReferenceDilatedConv( tensor_in_sizes, filter_in_sizes, stride, dilations, padding, data_format, use_gpu) expected_results.append(expected) computed_results.append(computed) tolerance = 1e-2 if use_gpu else 1e-5 with self.cached_session() as sess: expected_values = self.evaluate(expected_results) computed_values = self.evaluate(computed_results) for e_value, c_value in zip(expected_values, computed_values): print("expected = ", e_value) print("actual = ", c_value) self.assertAllClose( e_value.flatten(), c_value.flatten(), atol=tolerance, rtol=1e-6) def testConv3D1x1x1Filter(self): expected_output = [ 0.18518519, 0.22222222, 0.25925926, 0.40740741, 0.5, 0.59259259, 0.62962963, 0.77777778, 0.92592593, 0.85185185, 1.05555556, 1.25925926, 1.07407407, 1.33333333, 1.59259259, 1.2962963, 1.61111111, 1.92592593 ] # These are equivalent to the Conv2D1x1 case. self._VerifyValues( tensor_in_sizes=[1, 2, 3, 1, 3], filter_in_sizes=[1, 1, 1, 3, 3], stride=1, padding="VALID", expected=expected_output) self._VerifyValues( tensor_in_sizes=[1, 2, 1, 3, 3], filter_in_sizes=[1, 1, 1, 3, 3], stride=1, padding="VALID", expected=expected_output) self._VerifyValues( tensor_in_sizes=[1, 1, 2, 3, 3], filter_in_sizes=[1, 1, 1, 3, 3], stride=1, padding="VALID", expected=expected_output) def testConv3D1x1x1Filter2x1x1Dilation(self): ctx = context.context() is_eager = ctx is not None and ctx.executing_eagerly() if test.is_gpu_available(cuda_only=True) or \ (test_util.IsMklEnabled() and is_eager is False): self._VerifyDilatedConvValues( tensor_in_sizes=[1, 3, 6, 1, 1], filter_in_sizes=[1, 1, 1, 1, 1], stride=1, padding="VALID", dilations=[2, 1, 1]) # Expected values computed using scipy's correlate function. def testConv3D2x2x2Filter(self): expected_output = [ 3.77199074, 3.85069444, 3.92939815, 4.2650463, 4.35763889, 4.45023148, 6.73032407, 6.89236111, 7.05439815, 7.22337963, 7.39930556, 7.57523148, 9.68865741, 9.93402778, 10.17939815, 10.18171296, 10.44097222, 10.70023148 ] # expected_shape = [1, 3, 1, 2, 5] self._VerifyValues( tensor_in_sizes=[1, 4, 2, 3, 3], # b, z, y, x, fin filter_in_sizes=[2, 2, 2, 3, 3], # z, y, x, fin, fout stride=1, padding="VALID", expected=expected_output) def testConv3D2x2x2Filter1x2x1Dilation(self): ctx = context.context() is_eager = ctx is not None and ctx.executing_eagerly() if test.is_gpu_available(cuda_only=True) or \ (test_util.IsMklEnabled() and is_eager is False): self._VerifyDilatedConvValues( tensor_in_sizes=[1, 4, 6, 3, 1], filter_in_sizes=[2, 2, 2, 1, 1], stride=1, padding="VALID", dilations=[1, 2, 1]) def testConv3DStrides(self): expected_output = [ 0.06071429, 0.08988095, 0.10238095, 0.11488095, 0.12738095, 0.13988095, 0.08452381, 0.26071429, 0.35238095, 0.36488095, 0.37738095, 0.38988095, 0.40238095, 0.23452381, 0.46071429, 0.61488095, 0.62738095, 0.63988095, 0.65238095, 0.66488095, 0.38452381, 1.12738095, 1.48988095, 1.50238095, 1.51488095, 1.52738095, 1.53988095, 0.88452381, 1.32738095, 1.75238095, 1.76488095, 1.77738095, 1.78988095, 1.80238095, 1.03452381, 1.52738095, 2.01488095, 2.02738095, 2.03988095, 2.05238095, 2.06488095, 1.18452381, 2.19404762, 2.88988095, 2.90238095, 2.91488095, 2.92738095, 2.93988095, 1.68452381, 2.39404762, 3.15238095, 3.16488095, 3.17738095, 3.18988095, 3.20238095, 1.83452381, 2.59404762, 3.41488095, 3.42738095, 3.43988095, 3.45238095, 3.46488095, 1.98452381 ] self._VerifyValues( tensor_in_sizes=[1, 5, 8, 7, 1], filter_in_sizes=[1, 2, 3, 1, 1], stride=[2, 3, 1], # different stride for each spatial dimension padding="SAME", expected=expected_output) def testConv3D2x2x2FilterStride2(self): expected_output = [ 3.77199074, 3.85069444, 3.92939815, 9.68865741, 9.93402778, 10.17939815 ] self._VerifyValues( tensor_in_sizes=[1, 4, 2, 3, 3], filter_in_sizes=[2, 2, 2, 3, 3], stride=2, padding="VALID", expected=expected_output) def testConv3DStride3(self): expected_output = [ 1.51140873, 1.57167659, 1.63194444, 1.56349206, 1.62673611, 1.68998016, 1.6155754, 1.68179563, 1.74801587, 1.9280754, 2.01215278, 2.09623016, 1.98015873, 2.0672123, 2.15426587, 2.03224206, 2.12227183, 2.21230159, 4.4280754, 4.65500992, 4.88194444, 4.48015873, 4.71006944, 4.93998016, 4.53224206, 4.76512897, 4.99801587, 4.84474206, 5.09548611, 5.34623016, 4.8968254, 5.15054563, 5.40426587, 4.94890873, 5.20560516, 5.46230159 ] self._VerifyValues( tensor_in_sizes=[1, 6, 7, 8, 2], filter_in_sizes=[3, 2, 1, 2, 3], stride=3, padding="VALID", expected=expected_output) def testConv3D2x2x2FilterStride2Same(self): expected_output = [ 3.77199074, 3.85069444, 3.92939815, 2.0162037, 2.06597222, 2.11574074, 9.68865741, 9.93402778, 10.17939815, 4.59953704, 4.73263889, 4.86574074 ] self._VerifyValues( tensor_in_sizes=[1, 4, 2, 3, 3], filter_in_sizes=[2, 2, 2, 3, 3], stride=2, padding="SAME", expected=expected_output) def _TestConv3DEmptyTensorOutputShape(self): """Verifies the output shape of the Conv3D op when output tensor is empty. Args: none """ input_shape = [0, 112, 112, 112, 32] filter_shape = [3, 3, 3, 32, 64] output_shape = [0, 112, 112, 112, 64] input_data = 1 filter_data = 1 for data_type in self._DtypesToTest(False): input_tensor = constant_op.constant( input_data, shape=input_shape, dtype=data_type, name="input") filter_tensor = constant_op.constant( filter_data, shape=filter_shape, dtype=data_type, name="filter") conv = nn_ops.conv3d( input_tensor, filter_tensor, strides=[1, 1, 1, 1, 1], dilations=[1, 1, 1, 1, 1], padding="SAME", data_format="NDHWC", name="conv") values = self.evaluate(conv) self.assertEqual(values.shape, tensor_shape.TensorShape(output_shape)) def testKernelSmallerThanStride(self): expected_output = [ 0.03703704, 0.11111111, 0.25925926, 0.33333333, 0.7037037, 0.77777778, 0.92592593, 1. ] self._VerifyValues( tensor_in_sizes=[1, 3, 3, 3, 1], filter_in_sizes=[1, 1, 1, 1, 1], stride=2, padding="SAME", expected=expected_output) self._VerifyValues( tensor_in_sizes=[1, 3, 3, 3, 1], filter_in_sizes=[1, 1, 1, 1, 1], stride=2, padding="VALID", expected=expected_output) expected_output = [ 0.54081633, 0.58017493, 0.28061224, 0.81632653, 0.85568513, 0.40306122, 0.41873178, 0.4340379, 0.19642857, 2.46938776, 2.50874636, 1.1377551, 2.74489796, 2.78425656, 1.26020408, 1.16873178, 1.1840379, 0.51785714, 1.09511662, 1.10604956, 0.44642857, 1.17164723, 1.18258017, 0.47704082, 0.3691691, 0.37244898, 0.125 ] self._VerifyValues( tensor_in_sizes=[1, 7, 7, 7, 1], filter_in_sizes=[2, 2, 2, 1, 1], stride=3, padding="SAME", expected=expected_output) expected_output = [ 0.540816, 0.580175, 0.816327, 0.855685, 2.469388, 2.508746, 2.744898, 2.784257 ] self._VerifyValues( tensor_in_sizes=[1, 7, 7, 7, 1], filter_in_sizes=[2, 2, 2, 1, 1], stride=3, padding="VALID", expected=expected_output) def testKernelSizeMatchesInputSize(self): self._VerifyValues( tensor_in_sizes=[1, 2, 1, 2, 1], filter_in_sizes=[2, 1, 2, 1, 2], stride=1, padding="VALID", expected=[1.5625, 1.875]) def _ConstructAndTestGradientForConfig( self, batch, input_shape, filter_shape, in_depth, out_depth, stride, padding, test_input, data_format, use_gpu): input_planes, input_rows, input_cols = input_shape filter_planes, filter_rows, filter_cols = filter_shape input_shape = [batch, input_planes, input_rows, input_cols, in_depth] filter_shape = [ filter_planes, filter_rows, filter_cols, in_depth, out_depth ] if isinstance(stride, collections_abc.Iterable): strides = [1] + list(stride) + [1] else: strides = [1, stride, stride, stride, 1] if padding == "VALID": output_planes = int( math.ceil((input_planes - filter_planes + 1.0) / strides[1])) output_rows = int( math.ceil((input_rows - filter_rows + 1.0) / strides[2])) output_cols = int( math.ceil((input_cols - filter_cols + 1.0) / strides[3])) else: output_planes = int(math.ceil(float(input_planes) / strides[1])) output_rows = int(math.ceil(float(input_rows) / strides[2])) output_cols = int(math.ceil(float(input_cols) / strides[3])) output_shape = [batch, output_planes, output_rows, output_cols, out_depth] input_size = 1 for x in input_shape: input_size *= x filter_size = 1 for x in filter_shape: filter_size *= x input_data = [x * 1.0 / input_size for x in range(0, input_size)] filter_data = [x * 1.0 / filter_size for x in range(0, filter_size)] for data_type in self._DtypesToTest(use_gpu=use_gpu): # TODO(mjanusz): Modify gradient_checker to also provide max relative # error and synchronize the tolerance levels between the tests for forward # and backward computations. if data_type == dtypes.float64: tolerance = 1e-8 elif data_type == dtypes.float32: tolerance = 5e-3 elif data_type == dtypes.float16: tolerance = 1e-3 with self.cached_session(use_gpu=use_gpu): orig_input_tensor = constant_op.constant( input_data, shape=input_shape, dtype=data_type, name="input") filter_tensor = constant_op.constant( filter_data, shape=filter_shape, dtype=data_type, name="filter") if data_format == "NCDHW": input_tensor = test_util.NHWCToNCHW(orig_input_tensor) new_strides = test_util.NHWCToNCHW(strides) else: input_tensor = orig_input_tensor new_strides = strides conv = nn_ops.conv3d( input_tensor, filter_tensor, new_strides, padding, data_format=data_format, name="conv") if data_format == "NCDHW": conv = test_util.NCHWToNHWC(conv) self.assertEqual(conv.shape, tensor_shape.TensorShape(output_shape)) if test_input: jacob_t, jacob_n = gradient_checker.compute_gradient( orig_input_tensor, input_shape, conv, output_shape) else: jacob_t, jacob_n = gradient_checker.compute_gradient( filter_tensor, filter_shape, conv, output_shape) if data_type != dtypes.float16: reference_jacob_t = jacob_t err = np.fabs(jacob_t - jacob_n).max() else: # Compare fp16 theoretical gradients to fp32 theoretical gradients, # since fp16 numerical gradients are too imprecise. err = np.fabs(jacob_t - reference_jacob_t).max() print("conv3d gradient error = ", err) self.assertLess(err, tolerance) def ConstructAndTestGradient(self, **kwargs): for data_format, use_gpu in GetTestConfigs(): self._ConstructAndTestGradientForConfig(data_format=data_format, use_gpu=use_gpu, **kwargs) @test_util.run_deprecated_v1 def testInputGradientValidPaddingStrideOne(self): self.ConstructAndTestGradient( batch=2, input_shape=(3, 5, 4), filter_shape=(3, 3, 3), in_depth=2, out_depth=3, stride=1, padding="VALID", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientValidPaddingStrideOne(self): self.ConstructAndTestGradient( batch=4, input_shape=(4, 6, 5), filter_shape=(2, 2, 2), in_depth=2, out_depth=3, stride=1, padding="VALID", test_input=False) @test_util.run_deprecated_v1 def testInputGradientValidPaddingStrideTwo(self): self.ConstructAndTestGradient( batch=2, input_shape=(6, 3, 5), filter_shape=(3, 3, 3), in_depth=2, out_depth=3, stride=2, padding="VALID", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientValidPaddingStrideTwo(self): self.ConstructAndTestGradient( batch=2, input_shape=(7, 6, 5), filter_shape=(2, 2, 2), in_depth=2, out_depth=3, stride=2, padding="VALID", test_input=False) @test_util.run_deprecated_v1 def testInputGradientValidPaddingStrideThree(self): self.ConstructAndTestGradient( batch=2, input_shape=(3, 7, 6), filter_shape=(3, 3, 3), in_depth=2, out_depth=3, stride=3, padding="VALID", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientValidPaddingStrideThree(self): self.ConstructAndTestGradient( batch=2, input_shape=(4, 4, 7), filter_shape=(4, 4, 4), in_depth=2, out_depth=3, stride=3, padding="VALID", test_input=False) @test_util.run_deprecated_v1 def testInputGradientSamePaddingStrideOne(self): self.ConstructAndTestGradient( batch=2, input_shape=(3, 2, 2), filter_shape=(3, 2, 1), in_depth=2, out_depth=1, stride=1, padding="SAME", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientSamePaddingStrideOne(self): self.ConstructAndTestGradient( batch=2, input_shape=(3, 6, 5), filter_shape=(2, 2, 2), in_depth=2, out_depth=3, stride=1, padding="SAME", test_input=False) @test_util.run_deprecated_v1 def testInputGradientSamePaddingStrideTwo(self): self.ConstructAndTestGradient( batch=2, input_shape=(6, 3, 4), filter_shape=(3, 3, 3), in_depth=2, out_depth=3, stride=2, padding="SAME", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientSamePaddingStrideTwo(self): self.ConstructAndTestGradient( batch=4, input_shape=(7, 3, 5), filter_shape=(2, 2, 2), in_depth=2, out_depth=3, stride=2, padding="SAME", test_input=False) @test_util.run_deprecated_v1 def testInputGradientSamePaddingStrideThree(self): self.ConstructAndTestGradient( batch=2, input_shape=(9, 3, 6), filter_shape=(3, 3, 3), in_depth=2, out_depth=3, stride=3, padding="SAME", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientSamePaddingStrideThree(self): self.ConstructAndTestGradient( batch=2, input_shape=(9, 4, 7), filter_shape=(4, 4, 4), in_depth=2, out_depth=3, stride=3, padding="SAME", test_input=False) @test_util.run_deprecated_v1 def testInputGradientSamePaddingDifferentStrides(self): self.ConstructAndTestGradient( batch=1, input_shape=(5, 8, 7), filter_shape=(1, 2, 3), in_depth=2, out_depth=3, stride=[2, 3, 1], padding="SAME", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientKernelSizeMatchesInputSize(self): self.ConstructAndTestGradient( batch=2, input_shape=(5, 4, 3), filter_shape=(5, 4, 3), in_depth=2, out_depth=3, stride=1, padding="VALID", test_input=False) @test_util.run_deprecated_v1 def testInputGradientKernelSizeMatchesInputSize(self): self.ConstructAndTestGradient( batch=2, input_shape=(5, 4, 3), filter_shape=(5, 4, 3), in_depth=2, out_depth=3, stride=1, padding="VALID", test_input=True) def disabledtestFilterGradientSamePaddingDifferentStrides(self): self.ConstructAndTestGradient( batch=1, input_shape=(5, 8, 7), filter_shape=(1, 2, 3), in_depth=2, out_depth=3, stride=[2, 3, 1], padding="SAME", test_input=False) # Test the fast path in gemm_pack_rhs/gemm_pack_colmajor_block, when channel # dimension is a multiple of packet size. @test_util.run_deprecated_v1 def testInputGradientValidPaddingStrideOneFastPath(self): self.ConstructAndTestGradient( batch=2, input_shape=(3, 5, 4), filter_shape=(2, 2, 2), in_depth=8, out_depth=2, stride=1, padding="VALID", test_input=True) @test_util.run_deprecated_v1 def testFilterGradientValidPaddingStrideOneFastPath(self): self.ConstructAndTestGradient( batch=2, input_shape=(4, 6, 5), filter_shape=(2, 2, 2), in_depth=8, out_depth=2, stride=1, padding="VALID", test_input=False) # Testing for backprops def _RunAndVerifyBackprop(self, input_sizes, filter_sizes, output_sizes, strides, dilations, padding, data_format, use_gpu, err, mode): total_input_size = 1 total_filter_size = 1 for s in input_sizes: total_input_size *= s for s in filter_sizes: total_filter_size *= s # Initializes the input tensor with array containing incrementing # numbers from 1. x1 = [f * 1.0 for f in range(1, total_input_size + 1)] x2 = [f * 1.0 for f in range(1, total_filter_size + 1)] default_dilations = ( dilations[0] == 1 and dilations[1] == 1 and dilations[2] == 1) # If any dilation rate is larger than 1, only do test on the GPU # because we currently do not have a CPU implementation for arbitrary # dilation rates. if default_dilations or use_gpu: with self.cached_session(use_gpu=use_gpu) as sess: if data_format == "NCDHW": input_sizes = test_util.NHWCToNCHW(input_sizes) t1 = constant_op.constant(x1, shape=input_sizes) t2 = constant_op.constant(x2, shape=filter_sizes) full_strides = [1] + strides + [1] full_dilations = [1] + dilations + [1] if data_format == "NCDHW": full_strides = test_util.NHWCToNCHW(full_strides) full_dilations = test_util.NHWCToNCHW(full_dilations) actual = nn_ops.conv3d( t1, t2, strides=full_strides, dilations=full_dilations, padding=padding, data_format=data_format) expected = nn_ops.convolution( t1, t2, padding=padding, strides=strides, dilation_rate=dilations, data_format=data_format) if data_format == "NCDHW": actual = test_util.NCHWToNHWC(actual) expected = test_util.NCHWToNHWC(expected) actual_grad = gradients_impl.gradients(actual, t1 if mode == "input" else t2)[0] expected_grad = gradients_impl.gradients(expected, t1 if mode == "input" else t2)[0] # "values" consists of two tensors for two backprops actual_value = self.evaluate(actual_grad) expected_value = self.evaluate(expected_grad) self.assertShapeEqual(actual_value, actual_grad) self.assertShapeEqual(expected_value, expected_grad) print("expected = ", expected_value) print("actual = ", actual_value) self.assertArrayNear(expected_value.flatten(), actual_value.flatten(), err) @test_util.run_deprecated_v1 def testConv3D2x2Depth3ValidBackpropFilterStride1x1Dilation2x1(self): if test.is_gpu_available(cuda_only=True): for (data_format, use_gpu) in GetTestConfigs(): self._RunAndVerifyBackprop( input_sizes=[1, 3, 6, 1, 1], filter_sizes=[2, 2, 1, 1, 1], output_sizes=[1, 1, 5, 1, 1], strides=[1, 1, 1], dilations=[2, 1, 1], padding="VALID", data_format=data_format, use_gpu=use_gpu, err=1e-5, mode="filter") @test_util.run_deprecated_v1 def testConv3D2x2Depth3ValidBackpropInputStride1x1Dilation2x1(self): if test.is_gpu_available(cuda_only=True): for (data_format, use_gpu) in GetTestConfigs(): self._RunAndVerifyBackprop( input_sizes=[1, 3, 6, 1, 1], filter_sizes=[2, 2, 1, 1, 1], output_sizes=[1, 1, 5, 1, 1], strides=[1, 1, 1], dilations=[2, 1, 1], padding="VALID", data_format=data_format, use_gpu=use_gpu, err=1e-5, mode="input") if __name__ == "__main__": test.main()
apache-2.0
ivanlmj/Android-DNSSL
Flask/lib/python2.7/site-packages/flask/cli.py
72
18328
# -*- coding: utf-8 -*- """ flask.cli ~~~~~~~~~ A simple command line application to run flask apps. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import sys from threading import Lock, Thread from functools import update_wrapper import click from ._compat import iteritems, reraise from .helpers import get_debug_flag from . import __version__ class NoAppException(click.UsageError): """Raised if an application cannot be found or loaded.""" def find_best_app(module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in 'app', 'application': app = getattr(module, attr_name, None) if app is not None and isinstance(app, Flask): return app # Otherwise find the only object that is a Flask instance. matches = [v for k, v in iteritems(module.__dict__) if isinstance(v, Flask)] if len(matches) == 1: return matches[0] raise NoAppException('Failed to find application in module "%s". Are ' 'you sure it contains a Flask application? Maybe ' 'you wrapped it in a WSGI middleware or you are ' 'using a factory function.' % module.__name__) def prepare_exec_for_file(filename): """Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """ module = [] # Chop off file extensions or package markers if os.path.split(filename)[1] == '__init__.py': filename = os.path.dirname(filename) elif filename.endswith('.py'): filename = filename[:-3] else: raise NoAppException('The file provided (%s) does exist but is not a ' 'valid Python file. This means that it cannot ' 'be used as application. Please change the ' 'extension to .py' % filename) filename = os.path.realpath(filename) dirpath = filename while 1: dirpath, extra = os.path.split(dirpath) module.append(extra) if not os.path.isfile(os.path.join(dirpath, '__init__.py')): break sys.path.insert(0, dirpath) return '.'.join(module[::-1]) def locate_app(app_id): """Attempts to locate the application.""" __traceback_hide__ = True if ':' in app_id: module, app_obj = app_id.split(':', 1) else: module = app_id app_obj = None try: __import__(module) except ImportError: # Reraise the ImportError if it occurred within the imported module. # Determine this by checking whether the trace has a depth > 1. if sys.exc_info()[-1].tb_next: raise else: raise NoAppException('The file/path provided (%s) does not appear' ' to exist. Please verify the path is ' 'correct. If app is not on PYTHONPATH, ' 'ensure the extension is .py' % module) mod = sys.modules[module] if app_obj is None: app = find_best_app(mod) else: app = getattr(mod, app_obj, None) if app is None: raise RuntimeError('Failed to find application in module "%s"' % module) return app def find_default_import_path(): app = os.environ.get('FLASK_APP') if app is None: return if os.path.isfile(app): return prepare_exec_for_file(app) return app def get_version(ctx, param, value): if not value or ctx.resilient_parsing: return message = 'Flask %(version)s\nPython %(python_version)s' click.echo(message % { 'version': __version__, 'python_version': sys.version, }, color=ctx.color) ctx.exit() version_option = click.Option(['--version'], help='Show the flask version', expose_value=False, callback=get_version, is_flag=True, is_eager=True) class DispatchingApp(object): """Special application that dispatches to a Flask application which is imported by name in a background thread. If an error happens it is recorded and shown as part of the WSGI handling which in case of the Werkzeug debugger means that it shows up in the browser. """ def __init__(self, loader, use_eager_loading=False): self.loader = loader self._app = None self._lock = Lock() self._bg_loading_exc_info = None if use_eager_loading: self._load_unlocked() else: self._load_in_background() def _load_in_background(self): def _load_app(): __traceback_hide__ = True with self._lock: try: self._load_unlocked() except Exception: self._bg_loading_exc_info = sys.exc_info() t = Thread(target=_load_app, args=()) t.start() def _flush_bg_loading_exception(self): __traceback_hide__ = True exc_info = self._bg_loading_exc_info if exc_info is not None: self._bg_loading_exc_info = None reraise(*exc_info) def _load_unlocked(self): __traceback_hide__ = True self._app = rv = self.loader() self._bg_loading_exc_info = None return rv def __call__(self, environ, start_response): __traceback_hide__ = True if self._app is not None: return self._app(environ, start_response) self._flush_bg_loading_exception() with self._lock: if self._app is not None: rv = self._app else: rv = self._load_unlocked() return rv(environ, start_response) class ScriptInfo(object): """Help object to deal with Flask applications. This is usually not necessary to interface with as it's used internally in the dispatching to click. In future versions of Flask this object will most likely play a bigger role. Typically it's created automatically by the :class:`FlaskGroup` but you can also manually create it and pass it onwards as click object. """ def __init__(self, app_import_path=None, create_app=None): if create_app is None: if app_import_path is None: app_import_path = find_default_import_path() self.app_import_path = app_import_path else: app_import_path = None #: Optionally the import path for the Flask application. self.app_import_path = app_import_path #: Optionally a function that is passed the script info to create #: the instance of the application. self.create_app = create_app #: A dictionary with arbitrary data that can be associated with #: this script info. self.data = {} self._loaded_app = None def load_app(self): """Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned. """ __traceback_hide__ = True if self._loaded_app is not None: return self._loaded_app if self.create_app is not None: rv = self.create_app(self) else: if not self.app_import_path: raise NoAppException( 'Could not locate Flask application. You did not provide ' 'the FLASK_APP environment variable.\n\nFor more ' 'information see ' 'http://flask.pocoo.org/docs/latest/quickstart/') rv = locate_app(self.app_import_path) debug = get_debug_flag() if debug is not None: rv.debug = debug self._loaded_app = rv return rv pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True) def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled. """ @click.pass_context def decorator(__ctx, *args, **kwargs): with __ctx.ensure_object(ScriptInfo).load_app().app_context(): return __ctx.invoke(f, *args, **kwargs) return update_wrapper(decorator, f) class AppGroup(click.Group): """This works similar to a regular click :class:`~click.Group` but it changes the behavior of the :meth:`command` decorator so that it automatically wraps the functions in :func:`with_appcontext`. Not to be confused with :class:`FlaskGroup`. """ def command(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` unless it's disabled by passing ``with_appcontext=False``. """ wrap_for_ctx = kwargs.pop('with_appcontext', True) def decorator(f): if wrap_for_ctx: f = with_appcontext(f) return click.Group.command(self, *args, **kwargs)(f) return decorator def group(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it defaults the group class to :class:`AppGroup`. """ kwargs.setdefault('cls', AppGroup) return click.Group.group(self, *args, **kwargs) class FlaskGroup(AppGroup): """Special subclass of the :class:`AppGroup` group that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced use cases for which it makes sense to create an instance of this. For information as of why this is useful see :ref:`custom-scripts`. :param add_default_commands: if this is True then the default run and shell commands wil be added. :param add_version_option: adds the ``--version`` option. :param create_app: an optional callback that is passed the script info and returns the loaded app. """ def __init__(self, add_default_commands=True, create_app=None, add_version_option=True, **extra): params = list(extra.pop('params', None) or ()) if add_version_option: params.append(version_option) AppGroup.__init__(self, params=params, **extra) self.create_app = create_app if add_default_commands: self.add_command(run_command) self.add_command(shell_command) self._loaded_plugin_commands = False def _load_plugin_commands(self): if self._loaded_plugin_commands: return try: import pkg_resources except ImportError: self._loaded_plugin_commands = True return for ep in pkg_resources.iter_entry_points('flask.commands'): self.add_command(ep.load(), ep.name) self._loaded_plugin_commands = True def get_command(self, ctx, name): self._load_plugin_commands() # We load built-in commands first as these should always be the # same no matter what the app does. If the app does want to # override this it needs to make a custom instance of this group # and not attach the default commands. # # This also means that the script stays functional in case the # application completely fails. rv = AppGroup.get_command(self, ctx, name) if rv is not None: return rv info = ctx.ensure_object(ScriptInfo) try: rv = info.load_app().cli.get_command(ctx, name) if rv is not None: return rv except NoAppException: pass def list_commands(self, ctx): self._load_plugin_commands() # The commands available is the list of both the application (if # available) plus the builtin commands. rv = set(click.Group.list_commands(self, ctx)) info = ctx.ensure_object(ScriptInfo) try: rv.update(info.load_app().cli.list_commands(ctx)) except Exception: # Here we intentionally swallow all exceptions as we don't # want the help page to break if the app does not exist. # If someone attempts to use the command we try to create # the app again and this will give us the error. pass return sorted(rv) def main(self, *args, **kwargs): obj = kwargs.get('obj') if obj is None: obj = ScriptInfo(create_app=self.create_app) kwargs['obj'] = obj kwargs.setdefault('auto_envvar_prefix', 'FLASK') return AppGroup.main(self, *args, **kwargs) @click.command('run', short_help='Runs a development server.') @click.option('--host', '-h', default='127.0.0.1', help='The interface to bind to.') @click.option('--port', '-p', default=5000, help='The port to bind to.') @click.option('--reload/--no-reload', default=None, help='Enable or disable the reloader. By default the reloader ' 'is active if debug is enabled.') @click.option('--debugger/--no-debugger', default=None, help='Enable or disable the debugger. By default the debugger ' 'is active if debug is enabled.') @click.option('--eager-loading/--lazy-loader', default=None, help='Enable or disable eager loading. By default eager ' 'loading is enabled if the reloader is disabled.') @click.option('--with-threads/--without-threads', default=False, help='Enable or disable multithreading.') @pass_script_info def run_command(info, host, port, reload, debugger, eager_loading, with_threads): """Runs a local development server for the Flask application. This local server is recommended for development purposes only but it can also be used for simple intranet deployments. By default it will not support any sort of concurrency at all to simplify debugging. This can be changed with the --with-threads option which will enable basic multithreading. The reloader and debugger are by default enabled if the debug flag of Flask is enabled and disabled otherwise. """ from werkzeug.serving import run_simple debug = get_debug_flag() if reload is None: reload = bool(debug) if debugger is None: debugger = bool(debug) if eager_loading is None: eager_loading = not reload app = DispatchingApp(info.load_app, use_eager_loading=eager_loading) # Extra startup messages. This depends a bit on Werkzeug internals to # not double execute when the reloader kicks in. if os.environ.get('WERKZEUG_RUN_MAIN') != 'true': # If we have an import path we can print it out now which can help # people understand what's being served. If we do not have an # import path because the app was loaded through a callback then # we won't print anything. if info.app_import_path is not None: print(' * Serving Flask app "%s"' % info.app_import_path) if debug is not None: print(' * Forcing debug mode %s' % (debug and 'on' or 'off')) run_simple(host, port, app, use_reloader=reload, use_debugger=debugger, threaded=with_threads) @click.command('shell', short_help='Runs a shell in the app context.') @with_appcontext def shell_command(): """Runs an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration. This is useful for executing small snippets of management code without having to manually configuring the application. """ import code from flask.globals import _app_ctx_stack app = _app_ctx_stack.top.app banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % ( sys.version, sys.platform, app.import_name, app.debug and ' [debug]' or '', app.instance_path, ) ctx = {} # Support the regular Python interpreter startup script if someone # is using it. startup = os.environ.get('PYTHONSTARTUP') if startup and os.path.isfile(startup): with open(startup, 'r') as f: eval(compile(f.read(), startup, 'exec'), ctx) ctx.update(app.make_shell_context()) code.interact(banner=banner, local=ctx) cli = FlaskGroup(help="""\ This shell command acts as general utility script for Flask applications. It loads the application configured (through the FLASK_APP environment variable) and then provides commands either provided by the application or Flask itself. The most useful commands are the "run" and "shell" command. Example usage: \b %(prefix)s%(cmd)s FLASK_APP=hello.py %(prefix)s%(cmd)s FLASK_DEBUG=1 %(prefix)sflask run """ % { 'cmd': os.name == 'posix' and 'export' or 'set', 'prefix': os.name == 'posix' and '$ ' or '', }) def main(as_module=False): this_module = __package__ + '.cli' args = sys.argv[1:] if as_module: if sys.version_info >= (2, 7): name = 'python -m ' + this_module.rsplit('.', 1)[0] else: name = 'python -m ' + this_module # This module is always executed as "python -m flask.run" and as such # we need to ensure that we restore the actual command line so that # the reloader can properly operate. sys.argv = ['-m', this_module] + sys.argv[1:] else: name = None cli.main(args=args, prog_name=name) if __name__ == '__main__': main(as_module=True)
gpl-2.0
ryfeus/lambda-packs
Sklearn_scipy_numpy/source/scipy/special/_ellip_harm.py
80
5743
from __future__ import division, print_function, absolute_import import threading import numpy as np from ._ufuncs import _ellip_harm from ._ellip_harm_2 import _ellipsoid, _ellipsoid_norm # the functions _ellipsoid, _ellipsoid_norm use global variables, the lock # protects them if the function is called from multiple threads simultaneously _ellip_lock = threading.Lock() def ellip_harm(h2, k2, n, p, s, signm=1, signn=1): r""" Ellipsoidal harmonic functions E^p_n(l) These are also known as Lame functions of the first kind, and are solutions to the Lame equation: .. math:: (s^2 - h^2)(s^2 - k^2)E''(s) + s(2s^2 - h^2 - k^2)E'(s) + (a - q s^2)E(s) = 0 where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not returned) corresponding to the solutions. Parameters ---------- h2 : float ``h**2`` k2 : float ``k**2``; should be larger than ``h**2`` n : int Degree s : float Coordinate p : int Order, can range between [1,2n+1] signm : {1, -1}, optional Sign of prefactor of functions. Can be +/-1. See Notes. signn : {1, -1}, optional Sign of prefactor of functions. Can be +/-1. See Notes. Returns ------- E : float the harmonic :math:`E^p_n(s)` See Also -------- ellip_harm_2, ellip_normal Notes ----- The geometric intepretation of the ellipsoidal functions is explained in [2]_, [3]_, [4]_. The `signm` and `signn` arguments control the sign of prefactors for functions according to their type:: K : +1 L : signm M : signn N : signm*signn .. versionadded:: 0.15.0 References ---------- .. [1] Digital Libary of Mathematical Functions 29.12 http://dlmf.nist.gov/29.12 .. [2] Bardhan and Knepley, "Computational science and re-discovery: open-source implementations of ellipsoidal harmonics for problems in potential theory", Comput. Sci. Disc. 5, 014006 (2012) doi:10.1088/1749-4699/5/1/014006 .. [3] David J.and Dechambre P, "Computation of Ellipsoidal Gravity Field Harmonics for small solar system bodies" pp. 30-36, 2000 .. [4] George Dassios, "Ellipsoidal Harmonics: Theory and Applications" pp. 418, 2012 Examples -------- >>> from scipy.special import ellip_harm >>> w = ellip_harm(5,8,1,1,2.5) >>> w 2.5 Check that the functions indeed are solutions to the Lame equation: >>> from scipy.interpolate import UnivariateSpline >>> def eigenvalue(f, df, ddf): ... r = ((s**2 - h**2)*(s**2 - k**2)*ddf + s*(2*s**2 - h**2 - k**2)*df - n*(n+1)*s**2*f)/f ... return -r.mean(), r.std() >>> s = np.linspace(0.1, 10, 200) >>> k, h, n, p = 8.0, 2.2, 3, 2 >>> E = ellip_harm(h**2, k**2, n, p, s) >>> E_spl = UnivariateSpline(s, E) >>> a, a_err = eigenvalue(E_spl(s), E_spl(s,1), E_spl(s,2)) >>> a, a_err (583.44366156701483, 6.4580890640310646e-11) """ return _ellip_harm(h2, k2, n, p, s, signm, signn) # np.vectorize does not work on Cython functions on Numpy < 1.8, so a wrapper is needed def _ellip_harm_2_vec(h2, k2, n, p, s): return _ellipsoid(h2, k2, n, p, s) _ellip_harm_2_vec = np.vectorize(_ellip_harm_2_vec, otypes='d') def ellip_harm_2(h2, k2, n, p, s): r""" Ellipsoidal harmonic functions F^p_n(l) These are also known as Lame functions of the second kind, and are solutions to the Lame equation: .. math:: (s^2 - h^2)(s^2 - k^2)F''(s) + s(2s^2 - h^2 - k^2)F'(s) + (a - q s^2)F(s) = 0 where :math:`q = (n+1)n` and :math:`a` is the eigenvalue (not returned) corresponding to the solutions. Parameters ---------- h2 : float ``h**2`` k2 : float ``k**2``; should be larger than ``h**2`` n : int Degree. p : int Order, can range between [1,2n+1]. s : float Coordinate Returns ------- F : float The harmonic :math:`F^p_n(s)` Notes ----- Lame functions of the second kind are related to the functions of the first kind: .. math:: F^p_n(s)=(2n + 1)E^p_n(s)\int_{0}^{1/s}\frac{du}{(E^p_n(1/u))^2\sqrt{(1-u^2k^2)(1-u^2h^2)}} .. versionadded:: 0.15.0 See Also -------- ellip_harm, ellip_normal Examples -------- >>> from scipy.special import ellip_harm_2 >>> w = ellip_harm_2(5,8,2,1,10) >>> w 0.00108056853382 """ with _ellip_lock: with np.errstate(all='ignore'): return _ellip_harm_2_vec(h2, k2, n, p, s) def _ellip_normal_vec(h2, k2, n, p): return _ellipsoid_norm(h2, k2, n, p) _ellip_normal_vec = np.vectorize(_ellip_normal_vec, otypes='d') def ellip_normal(h2, k2, n, p): r""" Ellipsoidal harmonic normalization constants gamma^p_n The normalization constant is defined as .. math:: \gamma^p_n=8\int_{0}^{h}dx\int_{h}^{k}dy\frac{(y^2-x^2)(E^p_n(y)E^p_n(x))^2}{\sqrt((k^2-y^2)(y^2-h^2)(h^2-x^2)(k^2-x^2)} Parameters ---------- h2 : float ``h**2`` k2 : float ``k**2``; should be larger than ``h**2`` n : int Degree. p : int Order, can range between [1,2n+1]. Returns ------- gamma : float The normalization constant :math:`\gamma^p_n` See Also -------- ellip_harm, ellip_harm_2 Notes ----- .. versionadded:: 0.15.0 Examples -------- >>> from scipy.special import ellip_normal >>> w = ellip_normal(5,8,3,7) >>> w 1723.38796997 """ with _ellip_lock: with np.errstate(all='ignore'): return _ellip_normal_vec(h2, k2, n, p)
mit
vrtsystems/pyhaystack
pyhaystack/client/ops/his.py
1
31373
#!/usr/bin/env python # -*- coding: utf-8 -*- """ High-level history functions. These wrap the basic his_read function to allow some alternate representations of the historical data. """ import hszinc import fysom import pytz from copy import deepcopy from datetime import tzinfo from six import string_types from ...util import state from ...util.asyncexc import AsynchronousException try: from pandas import Series, DataFrame HAVE_PANDAS = True except ImportError: # pragma: no cover # Not covered, since we'll always have 'pandas' available during tests. HAVE_PANDAS = False def _resolve_tz(tz): """ Resolve a given timestamp. """ if (tz is None) or isinstance(tz, tzinfo): return tz if isinstance(tz, string_types): if '/' in tz: # Olson database name return pytz.timezone(tz) else: return hszinc.zoneinfo.timezone(tz) class HisReadSeriesOperation(state.HaystackOperation): """ Read the series data from a 'point' entity and present it in a concise format. """ FORMAT_LIST = 'list' # [(ts1, value1), (ts2, value2), ...] FORMAT_DICT = 'dict' # {ts1: value1, ts2: value2, ...} FORMAT_SERIES = 'series' # pandas.Series def __init__(self, session, point, rng, tz, series_format): """ Read the series data and return it. :param session: Haystack HTTP session object. :param point: ID of historical 'point' object to read. :param rng: Range to read from 'point' :param tz: Timezone to translate timezones to. May be None. :param series_format: What format to present the series in. """ super(HisReadSeriesOperation, self).__init__() if series_format not in (self.FORMAT_LIST, self.FORMAT_DICT, self.FORMAT_SERIES): raise ValueError('Unrecognised series_format %s' % series_format) if (series_format == self.FORMAT_SERIES) and (not HAVE_PANDAS): raise NotImplementedError('pandas not available.') if isinstance(rng, slice): rng = ','.join([ hszinc.dump_scalar(p, mode=hszinc.MODE_ZINC) for p in (rng.start, rng.stop) ]) self._session = session self._point = point self._range = hszinc.dump_scalar(rng, mode=hszinc.MODE_ZINC) self._tz = _resolve_tz(tz) self._series_format = series_format self._state_machine = fysom.Fysom( initial='init', final='done', events=[ # Event Current State New State ('go', 'init', 'read'), ('read_done', 'read', 'done'), ('exception', '*', 'done'), ], callbacks={ 'onenterread': self._do_read, 'onenterdone': self._do_done, }) def go(self): self._state_machine.go() def _do_read(self, event): """ Request the data from the server. """ self._session.his_read(point=self._point, rng=self._range, callback=self._on_read) def _on_read(self, operation, **kwargs): """ Process the grid, format it into the requested format. """ try: # See if the read succeeded. grid = operation.result if self._tz is None: conv_ts = lambda ts : ts else: conv_ts = lambda ts : ts.astimezone(self._tz) # Convert grid to list of tuples data = [(conv_ts(row['ts']), row['val']) for row in grid] if self._series_format == self.FORMAT_DICT: data = dict(data) elif self._series_format == self.FORMAT_SERIES: # Split into index and data. try: (index, data) = zip(*data) if isinstance(data[0], hszinc.Quantity): values = [each.value for each in data] units = data[0].unit else: values = data units = '' except ValueError: values = [] index = [] units = '' #ser = Series(data=data[0].value, index=index) meta_serie = MetaSeries(data=values, index=index) meta_serie.add_meta('units', units) meta_serie.add_meta('point', self._point) self._state_machine.read_done(result=meta_serie) except: # Catch all exceptions to pass to caller. self._state_machine.exception(result=AsynchronousException()) def _do_done(self, event): """ Return the result from the state machine. """ self._done(event.result) class HisReadFrameOperation(state.HaystackOperation): """ Read the series data from several 'point' entities and present them in a concise format. """ FORMAT_LIST = 'list' # [{'ts': ts1, 'col1': val1, ...}, {...}, ...] FORMAT_DICT = 'dict' # {ts1: {'col1': val1, ...}, ts2: ...} FORMAT_FRAME = 'frame' # pandas.DataFrame def __init__(self, session, columns, rng, tz, frame_format): """ Read the series data and return it. :param session: Haystack HTTP session object. :param columns: IDs of historical point objects to read. :param rng: Range to read from 'point' :param tz: Timezone to translate timezones to. May be None. :param frame_format: What format to present the frame in. """ super(HisReadFrameOperation, self).__init__() self._log = session._log.getChild('his_read_frame') if frame_format not in (self.FORMAT_LIST, self.FORMAT_DICT, self.FORMAT_FRAME): raise ValueError('Unrecognised frame_format %s' % frame_format) if (frame_format == self.FORMAT_FRAME) and (not HAVE_PANDAS): raise NotImplementedError('pandas not available.') if isinstance(rng, slice): rng = ','.join([ hszinc.dump_scalar(p, mode=hszinc.MODE_ZINC) for p in (rng.start, rng.stop) ]) # Convert the columns to a list of tuples. strip_ref = lambda r : r.name if isinstance(r, hszinc.Ref) else r if isinstance(columns, dict): # Ensure all are strings to references columns = [(str(c),strip_ref(r)) for c, r in columns.items()] else: # Translate to a dict: columns = [(strip_ref(c), c) for c in columns] self._session = session self._columns = columns self._range = hszinc.dump_scalar(rng, mode=hszinc.MODE_ZINC) self._tz = _resolve_tz(tz) self._frame_format = frame_format self._data_by_ts = {} self._todo = set([c[0] for c in columns]) self._state_machine = fysom.Fysom( initial='init', final='done', events=[ # Event Current State New State ('probe_multi', 'init', 'probing'), ('do_multi_read', 'probing', 'multi_read'), ('all_read_done', 'multi_read', 'postprocess'), ('do_single_read', 'probing', 'single_read'), ('all_read_done', 'single_read', 'postprocess'), ('process_done', 'postprocess', 'done'), ('exception', '*', 'done'), ], callbacks={ 'onenterprobing': self._do_probe_multi, 'onentermulti_read': self._do_multi_read, 'onentersingle_read': self._do_single_read, 'onenterpostprocess': self._do_postprocess, 'onenterdone': self._do_done, }) def go(self): self._state_machine.probe_multi() def _do_probe_multi(self, event): self._log.debug('Probing for multi-his-read support') self._session.has_features([self._session.FEATURE_HISREAD_MULTI], callback=self._on_probe_multi) def _on_probe_multi(self, operation, **kwargs): try: result = operation.result except: # Catch all exceptions to pass to caller. self._state_machine.exception(result=AsynchronousException()) return if result.get(self._session.FEATURE_HISREAD_MULTI): # Session object supports multi-his-read self._log.debug('Using multi-his-read support') self._state_machine.do_multi_read() else: # Emulate multi-his-read with separate self._log.debug('No multi-his-read support, emulating') self._state_machine.do_single_read() def _get_ts_rec(self, ts): try: return self._data_by_ts[ts] except KeyError: rec = {} self._data_by_ts[ts] = rec return rec def _do_multi_read(self, event): """ Request the data from the server as a single multi-read request. """ self._session.multi_his_read(points=[c[1] for c in self._columns], rng=self._range, callback=self._on_multi_read) def _on_multi_read(self, operation, **kwargs): """ Handle the multi-valued grid. """ try: grid = operation.result if self._tz is None: conv_ts = lambda ts : ts else: conv_ts = lambda ts : ts.astimezone(self._tz) for row in grid: ts = conv_ts(row['ts']) rec = self._get_ts_rec(ts) for (col_idx, (col, _)) in enumerate(self._columns): val = row.get('v%d' % col_idx) if (val is not None) or \ (self._frame_format != self.FORMAT_FRAME): rec[col] = val self._state_machine.all_read_done() except: # Catch all exceptions to pass to caller. self._log.debug('Hit exception', exc_info=1) self._state_machine.exception(result=AsynchronousException()) def _do_single_read(self, event): """ Request the data from the server as multiple single-read requests. """ for col, point in self._columns: self._log.debug('Column %s point %s', col, point) self._session.his_read(point, self._range, lambda operation, **kw : self._on_single_read(operation, col=col)) def _on_single_read(self, operation, col, **kwargs): """ Handle the multi-valued grid. """ self._log.debug('Response back for column %s', col) try: grid = operation.result #print(grid) #print('===========') if self._tz is None: conv_ts = lambda ts : ts else: conv_ts = lambda ts : ts.astimezone(self._tz) self._log.debug('%d records for %s: %s', len(grid), col, grid) for row in grid: ts = conv_ts(row['ts']) if self._tz is None: self._tz = ts.tzinfo rec = self._get_ts_rec(ts) val = row.get('val') if (val is not None) or \ (self._frame_format != self.FORMAT_FRAME): rec[col] = val self._todo.discard(col) self._log.debug('Still waiting for: %s', self._todo) if not self._todo: # No more to read self._state_machine.all_read_done() except: # Catch all exceptions to pass to caller. self._log.debug('Hit exception', exc_info=1) self._state_machine.exception(result=AsynchronousException()) def _do_postprocess(self, event): """ Convert the dict-of-dicts to the desired frame format. """ self._log.debug('Post-processing') try: if self._frame_format == self.FORMAT_LIST: def _merge_ts(item): rec = item[1].copy() rec['ts'] = item[0] return rec data = list(map(_merge_ts, list(self._data_by_ts.items()))) #print(data) elif self._frame_format == self.FORMAT_FRAME: # Build from dict data = MetaDataFrame.from_dict(self._data_by_ts, orient='index') def convert_quantity(val): """ If value is Quantity, convert to value """ if isinstance(val,hszinc.Quantity): return val.value else: return val def get_units(serie): try: first_element = serie.dropna()[0] except IndexError: # needed for empty results return '' if isinstance(first_element, hszinc.Quantity): return first_element.unit else: return '' for name, serie in data.iteritems(): """ Convert Quantity and put unit in metadata """ data.add_meta(name,get_units(serie)) data[name] = data[name].apply(convert_quantity) else: data = self._data_by_ts self._state_machine.process_done(result=data) except: # Catch all exceptions to pass to caller. self._log.debug('Hit exception', exc_info=1) self._state_machine.exception(result=AsynchronousException()) def _do_done(self, event): """ Return the result from the state machine. """ self._done(event.result) class HisWriteSeriesOperation(state.HaystackOperation): """ Write the series data to a 'point' entity. """ def __init__(self, session, point, series, tz): """ Write the series data to the point. :param session: Haystack HTTP session object. :param point: ID of historical 'point' object to write. :param series: Series data to be written to the point. :param tz: If not None, a datetime.tzinfo instance for this write. """ super(HisWriteSeriesOperation, self).__init__() # We've either been given an Entity instance or a string/reference # giving the name of an entity. if isinstance(point, string_types) or isinstance(point, hszinc.Ref): # We have the name of an entity, we'll need to fetch it. self._entity_id = point self._point = None else: # We have an entity. self._point = point self._entity_id = point.id self._session = session self._series = series self._tz = _resolve_tz(tz) self._state_machine = fysom.Fysom( initial='init', final='done', events=[ # Event Current State New State ('have_tz', 'init', 'write'), ('have_point', 'init', 'get_point_tz'), ('need_point', 'init', 'get_point'), ('have_point', 'get_point', 'get_point_tz'), ('have_tz', 'get_point_tz', 'write'), ('need_equip', 'get_point_tz', 'get_equip'), ('have_equip', 'get_equip', 'get_equip_tz'), ('have_tz', 'get_equip_tz', 'write'), ('need_site', 'get_equip_tz', 'get_site'), ('have_site', 'get_site', 'get_site_tz'), ('have_tz', 'get_site_tz', 'write'), ('write_done', 'write', 'done'), ('exception', '*', 'done'), ], callbacks={ 'onenterget_point': self._do_get_point, 'onenterget_point_tz': self._do_get_point_tz, 'onenterget_equip': self._do_get_equip, 'onenterget_equip_tz': self._do_get_equip_tz, 'onenterget_site': self._do_get_site, 'onenterget_site_tz': self._do_get_site_tz, 'onenterwrite': self._do_write, 'onenterdone': self._do_done, }) def go(self): if self._tz is not None: # Do we have a timezone? # We do! self._state_machine.have_tz() elif self._point is not None: # Nope, do we have the point? # We do! self._state_machine.have_point() else: # We need to fetch the point to get its timezone. self._state_machine.need_point() def _do_get_point(self, event): """ Retrieve the point entity. """ self._session.get_entity(self._entity_id, single=True, callback=self._got_point) def _got_point(self, operation, **kwargs): """ Process the return value from get_entity """ try: self._point = operation.result self._state_machine.have_point() except: self._state_machine.exception(result=AsynchronousException()) def _do_get_point_tz(self, event): """ See if the point has a timezone? """ if hasattr(self._point, 'tz') and isinstance(self._point.tz, tzinfo): # We have our timezone. self._tz = self._point.tz self._state_machine.have_tz() else: # Nope, look at the equip then. self._state_machine.need_equip() def _do_get_equip(self, event): """ Retrieve the equip entity. """ self._point.get_equip(callback=self._got_equip) def _got_equip(self, operation, **kwargs): """ Process the return value from get_entity """ try: equip = operation.result self._state_machine.have_equip(equip=equip) except: self._state_machine.exception(result=AsynchronousException()) def _do_get_equip_tz(self, event): """ See if the equip has a timezone? """ equip = event.equip if hasattr(equip, 'tz') and isinstance(equip.tz, tzinfo): # We have our timezone. self._tz = equip.tz self._state_machine.have_tz() else: # Nope, look at the site then. self._state_machine.need_site() def _do_get_site(self, event): """ Retrieve the site entity. """ self._point.get_site(callback=self._got_site) def _got_site(self, operation, **kwargs): """ Process the return value from get_entity """ try: site = operation.result self._state_machine.have_site(site=site) except: self._state_machine.exception(result=AsynchronousException()) def _do_get_site_tz(self, event): """ See if the site has a timezone? """ site = event.site if hasattr(site, 'tz') and isinstance(site.tz, tzinfo): # We have our timezone. self._tz = site.tz self._state_machine.have_tz() else: try: # Nope, no idea then. raise ValueError('No timezone specified for operation, '\ 'point, equip or site.') except: self._state_machine.exception(result=AsynchronousException()) def _do_write(self, event): """ Push the data to the server. """ try: # Process the timestamp records into an appropriate format. if hasattr(self._series, 'to_dict'): records = self._series.to_dict() elif not isinstance(self._series, dict): records = dict(self._series) else: records = self._series if not bool(records): # No data, skip writing this series. self._state_machine.write_done(result=None) return # Time-shift the records. if hasattr(self._tz, 'localize'): localise = lambda ts : self._tz.localize(ts) \ if ts.tzinfo is None else ts.astimezone(self._tz) else: localise = lambda ts : ts.replace(tzinfo=self._tz) \ if ts.tzinfo is None else ts.astimezone(self._tz) records = dict([(localise(ts), val) \ for ts, val in records.items()]) # Write the data self._session.his_write(point=self._entity_id, timestamp_records=records, callback=self._on_write) except: self._state_machine.exception(result=AsynchronousException()) def _on_write(self, operation, **kwargs): """ Handle the write error, if any. """ try: # See if the write succeeded. grid = operation.result if not isinstance(grid, hszinc.Grid): raise TypeError('Unexpected result: %r' % grid) # Move to the done state. self._state_machine.write_done(result=None) except: # Catch all exceptions to pass to caller. self._state_machine.exception(result=AsynchronousException()) def _do_done(self, event): """ Return the result from the state machine. """ self._done(event.result) class HisWriteFrameOperation(state.HaystackOperation): """ Write the series data to several 'point' entities. """ def __init__(self, session, columns, frame, tz): """ Write the series data. :param session: Haystack HTTP session object. :param columns: IDs of historical point objects to read. :param frame: Range to read from 'point' :param tz: Timezone to translate timezones to. """ super(HisWriteFrameOperation, self).__init__() self._log = session._log.getChild('his_write_frame') tz = _resolve_tz(tz) if tz is None: tz = pytz.utc if hasattr(tz, 'localize'): localise = lambda ts : tz.localize(ts) \ if ts.tzinfo is None else ts.astimezone(tz) else: localise = lambda ts : ts.replace(tzinfo=tz) \ if ts.tzinfo is None else ts.astimezone(tz) # Convert frame to list of records. if HAVE_PANDAS: # Convert Pandas frame to dict of dicts form. if isinstance(frame, DataFrame): self._log.debug('Convert from Pandas DataFrame') raw_frame = frame.to_dict(orient='dict') frame = {} for col, col_data in raw_frame.items(): for ts, val in col_data.items(): try: frame_rec = frame[ts] except KeyError: frame_rec = {} frame[ts] = frame_rec frame[col] = val # Convert dict of dicts to records, de-referencing column names. if isinstance(frame, dict): if columns is None: def _to_rec(item): (ts, raw_record) = item record = raw_record.copy() record['ts'] = ts return record else: def _to_rec(item): (ts, raw_record) = item record = {} for col, val in raw_record.items(): entity = columns[col] if hasattr(entity, 'id'): entity = entity.id if isinstance(entity, hszinc.Ref): entity = entity.name record[entity] = val record['ts'] = ts return record frame = list(map(_to_rec, list(frame.items()))) elif columns is not None: # Columns are aliased. De-alias the column names. frame = deepcopy(frame) for row in frame: ts = row.pop('ts') raw = row.copy() row.clear() row['ts'] = ts for column, point in columns.items(): try: value = raw.pop(column) except KeyError: self._log.debug('At %s missing column %s (for %s): %s', ts, column, point, raw) continue row[session._obj_to_ref(point).name] = value # Localise all timestamps, extract columns: columns = set() def _localise_rec(r): r['ts'] = localise(r['ts']) columns.update(set(r.keys()) - set(['ts'])) return r frame = list(map(_localise_rec, frame)) self._session = session self._frame = frame self._columns = columns self._todo = columns.copy() self._tz = _resolve_tz(tz) self._state_machine = fysom.Fysom( initial='init', final='done', events=[ # Event Current State New State ('probe_multi', 'init', 'probing'), ('no_data', 'init', 'done'), ('do_multi_write', 'probing', 'multi_write'), ('all_write_done', 'multi_write', 'done'), ('do_single_write', 'probing', 'single_write'), ('all_write_done', 'single_write', 'done'), ('exception', '*', 'done'), ], callbacks={ 'onenterprobing': self._do_probe_multi, 'onentermulti_write': self._do_multi_write, 'onentersingle_write': self._do_single_write, 'onenterdone': self._do_done, }) def go(self): if not bool(self._columns): self._log.debug('No data to write') self._state_machine.no_data(result=None) else: self._state_machine.probe_multi() def _do_probe_multi(self, event): self._log.debug('Probing for multi-his-write support') self._session.has_features([self._session.FEATURE_HISWRITE_MULTI], callback=self._on_probe_multi) def _on_probe_multi(self, operation, **kwargs): try: result = operation.result except: # Catch all exceptions to pass to caller. self._log.warning('Unable to probe multi-his-write support', exc_info=1) self._state_machine.exception(result=AsynchronousException()) result = {} return self._log.debug('Got result: %s', result) if result.get(self._session.FEATURE_HISWRITE_MULTI): # Session object supports multi-his-write self._log.debug('Using multi-his-write support') self._state_machine.do_multi_write() else: # Emulate multi-his-write with separate self._log.debug('No multi-his-write support, emulating') self._state_machine.do_single_write() def _do_multi_write(self, event): """ Request the data from the server as a single multi-read request. """ self._session.multi_his_write(self._frame, callback=self._on_multi_write) def _on_multi_write(self, operation, **kwargs): """ Handle the multi-valued grid. """ try: grid = operation.result if not isinstance(grid, hszinc.Grid): raise ValueError('Unexpected result %r' % grid) self._state_machine.all_write_done(result=None) except: # Catch all exceptions to pass to caller. self._log.debug('Hit exception', exc_info=1) self._state_machine.exception(result=AsynchronousException()) def _do_single_write(self, event): """ Submit the data in single write requests. """ for point in self._columns: self._log.debug('Point %s', point) # Extract a series for this column series = dict([(r['ts'], r[point]) for r in \ filter(lambda r : r.get(point) is not None, self._frame)]) self._session.his_write_series(point, series, callback=lambda operation, **kw : \ self._on_single_write(operation, point=point)) def _on_single_write(self, operation, point, **kwargs): """ Handle the single write. """ self._log.debug('Response back for point %s', point) try: res = operation.result if res is not None: raise ValueError('Unexpected result %r' % res) self._todo.discard(point) self._log.debug('Still waiting for: %s', self._todo) if not self._todo: # No more to read self._state_machine.all_write_done(result=None) except: # Catch all exceptions to pass to caller. self._log.debug('Hit exception', exc_info=1) self._state_machine.exception(result=AsynchronousException()) def _do_done(self, event): """ Return the result from the state machine. """ self._done(event.result) if HAVE_PANDAS: class MetaSeries(Series): """ Custom Pandas Serie with meta data """ meta = {} @property def _constructor(self): return MetaSeries def add_meta(self, key, value): self.meta[key] = value class MetaDataFrame(DataFrame): """ Custom Pandas Dataframe with meta data Made from MetaSeries """ meta = {} def __init__(self, *args, **kw): super(MetaDataFrame, self).__init__(*args, **kw) @property def _constructor(self): return MetaDataFrame _constructor_sliced = MetaSeries def add_meta(self, key, value): self.meta[key] = value
apache-2.0
shssoichiro/servo
tests/wpt/web-platform-tests/encrypted-media/polyfill/make-polyfill-tests.py
74
1267
#!/usr/bin/python import os, re, os.path, glob head = re.compile( r"^(\s*</head>)", re.MULTILINE ) runtest = re.compile( r"runTest\(\s*(\S.*?)\s*\)", re.DOTALL ) scripts = ''' <!-- Polyfill files (NOTE: These are added by auto-generation script) --> <script src=/encrypted-media/polyfill/chrome-polyfill.js></script> <script src=/encrypted-media/polyfill/firefox-polyfill.js></script> <script src=/encrypted-media/polyfill/edge-persistent-usage-record.js></script> <script src=/encrypted-media/polyfill/edge-keystatuses.js></script> <script src=/encrypted-media/polyfill/clearkey-polyfill.js></script>''' def process_file( infile, outfile ) : with open( outfile, "w" ) as output : with open( infile, "r" ) as input : output.write( runtest.sub( r"runTest( \1, 'polyfill: ' )", head.sub( scripts + r"\1", input.read() ) ) ) if __name__ == '__main__' : if (not os.getcwd().endswith('polyfill')) : print "Please run from polyfill directory" exit( 1 ) for infile in glob.glob( "../*.html" ) : process_file( infile, os.path.basename( infile ) ) for infile in glob.glob( "../resources/*.html" ) : process_file( infile, os.path.join( "resources", os.path.basename( infile ) ) )
mpl-2.0
dwillmer/jedi
jedi/evaluate/dynamic.py
33
4936
""" One of the really important features of |jedi| is to have an option to understand code like this:: def foo(bar): bar. # completion here foo(1) There's no doubt wheter bar is an ``int`` or not, but if there's also a call like ``foo('str')``, what would happen? Well, we'll just show both. Because that's what a human would expect. It works as follows: - |Jedi| sees a param - search for function calls named ``foo`` - execute these calls and check the input. This work with a ``ParamListener``. """ from itertools import chain from jedi._compatibility import unicode from jedi.parser import tree from jedi import settings from jedi import debug from jedi.evaluate.cache import memoize_default from jedi.evaluate import imports class ParamListener(object): """ This listener is used to get the params for a function. """ def __init__(self): self.param_possibilities = [] def execute(self, params): self.param_possibilities += params @debug.increase_indent def search_params(evaluator, param): """ A dynamic search for param values. If you try to complete a type: >>> def func(foo): ... foo >>> func(1) >>> func("") It is not known what the type ``foo`` without analysing the whole code. You have to look for all calls to ``func`` to find out what ``foo`` possibly is. """ if not settings.dynamic_params: return [] func = param.get_parent_until(tree.Function) debug.dbg('Dynamic param search for %s in %s.', param, str(func.name)) # Compare the param names. names = [n for n in search_function_call(evaluator, func) if n.value == param.name.value] # Evaluate the ExecutedParams to types. result = list(chain.from_iterable(n.parent.eval(evaluator) for n in names)) debug.dbg('Dynamic param result %s', result) return result @memoize_default([], evaluator_is_first_arg=True) def search_function_call(evaluator, func): """ Returns a list of param names. """ from jedi.evaluate import representation as er def get_params_for_module(module): """ Returns the values of a param, or an empty array. """ @memoize_default([], evaluator_is_first_arg=True) def get_posibilities(evaluator, module, func_name): try: names = module.used_names[func_name] except KeyError: return [] for name in names: parent = name.parent if tree.is_node(parent, 'trailer'): parent = parent.parent trailer = None if tree.is_node(parent, 'power'): for t in parent.children[1:]: if t == '**': break if t.start_pos > name.start_pos and t.children[0] == '(': trailer = t break if trailer is not None: types = evaluator.goto_definition(name) # We have to remove decorators, because they are not the # "original" functions, this way we can easily compare. # At the same time we also have to remove InstanceElements. undec = [] for escope in types: if escope.isinstance(er.Function, er.Instance) \ and escope.decorates is not None: undec.append(escope.decorates) elif isinstance(escope, er.InstanceElement): undec.append(escope.var) else: undec.append(escope) if evaluator.wrap(compare) in undec: # Only if we have the correct function we execute # it, otherwise just ignore it. evaluator.eval_trailer(types, trailer) return listener.param_possibilities return get_posibilities(evaluator, module, func_name) current_module = func.get_parent_until() func_name = unicode(func.name) compare = func if func_name == '__init__': cls = func.get_parent_scope() if isinstance(cls, tree.Class): func_name = unicode(cls.name) compare = cls # add the listener listener = ParamListener() func.listeners.add(listener) try: result = [] # This is like backtracking: Get the first possible result. for mod in imports.get_modules_containing_name(evaluator, [current_module], func_name): result = get_params_for_module(mod) if result: break finally: # cleanup: remove the listener; important: should not stick. func.listeners.remove(listener) return result
mit
ManoSeimas/manoseimas.lt
manoseimas/compatibility_test/tests/__init__.py
1
9447
# coding: utf-8 from __future__ import absolute_import from __future__ import unicode_literals import datetime import itertools from django_webtest import WebTest import factory from django.core.urlresolvers import reverse from django.test import TestCase from manoseimas.scrapy.models import PersonVote from manoseimas.factories import AdminUserFactory from manoseimas.models import ManoSeimasUser from manoseimas.mps_v2.models import Group, ParliamentMember from manoseimas.mps_v2.factories import GroupFactory, ParliamentMemberFactory, GroupMembershipFactory from manoseimas.compatibility_test.models import UserResult from manoseimas.compatibility_test.views import topics_all from manoseimas.compatibility_test import factories class TestAnswersJson(WebTest): csrf_checks = False def test_answers_json_get(self): self.assertEqual(ManoSeimasUser.objects.count(), 0) test = factories.CompatTestFactory() resp = self.app.get(reverse('answers_json', kwargs={'test_id': test.id})) self.assertEqual(resp.json, {'answers': {}, 'test_id': test.id}) # lazy user is created self.assertEqual(ManoSeimasUser.objects.count(), 1) self.assertEqual(UserResult.objects.count(), 0) def test_answers_json_post(self): answers = { '1': 'yes', '2': 'no', } test = factories.CompatTestFactory() resp = self.app.post_json( reverse('answers_json', kwargs={'test_id': test.id}), answers ) user = ManoSeimasUser.objects.first() self.assertEqual(resp.json, {'answers': answers, 'test_id': test.id}) # lazy user is created self.assertEqual(ManoSeimasUser.objects.count(), 1) # answers are saved self.assertEqual(UserResult.objects.count(), 1) ur = UserResult.objects.first() self.assertEqual(ur.user, user) self.assertEqual(ur.result, answers) class TestCompatibilityTest(TestCase): def test_topics_all(self): test = factories.CompatTestFactory() topic = factories.TopicFactory() factories.TestGroupFactory(test=test, topics=[topic]) factories.TopicFactory(name='Darbo kodeksas') self.assertEqual(topics_all(test.id), [ { 'id': topic.pk, 'group': 'Socialiniai reikalai', 'name': 'Aukštojo mokslo reforma', 'slug': 'aukstojo-mokslo-reforma', 'description': 'Aukštojo mokslo reforma', 'arguments': [], 'votings': [], 'image': None, }, ]) class TestViews(WebTest): maxDiff = None csrf_checks = False def test_index_view(self): topic = factories.TopicFactory() factories.TopicVotingFactory.create_batch(3, topic=topic) group = factories.TestGroupFactory(topics=[topic]) resp = self.app.get('/testas/') self.assertRedirects(resp, '/testas/%d/' % group.test.id) resp = resp.follow() self.assertEqual(resp.html.title.string, 'Politinių pažiūrų testas - manoSeimas.lt') def test_results_view(self): tp1, tp2 = topics = [ factories.TopicFactory(name='Socialinis modelis'), factories.TopicFactory(name='Kariuomenė'), ] data = [ ('1', 'DP', 'Jonas', 'Jonaitis', [1, -0.3]), ('2', 'DP', 'Petras', 'Petraitis', [1, 0.5]), ('3', 'LLS', 'Jonas', 'Petraitis', [-0.8, 1]), ] genpos = lambda positions: {topic.pk: position for topic, position in zip(topics, positions)} GroupFactory(abbr='DP', name='Darbo partijos frakcija', positions=genpos([1, 0.3])) GroupFactory(abbr='LLS', name='Liberalų sąjūdžio frakcija', positions=genpos([0.5, -0.3])) mps = [] for p_asm_id, fraction, first_name, last_name, positions in data: group = Group.objects.get(abbr=fraction) mp = ParliamentMemberFactory( source_id=p_asm_id, first_name=first_name, last_name=last_name, term_of_office='2012-2016', positions=genpos(positions), ) GroupMembershipFactory(member=mp, group=group) mps.append(mp) mp1, mp2, mp3 = mps gr1, gr2 = Group.objects.filter(abbr__in=['DP', 'LLS']).order_by('pk') test = factories.CompatTestFactory() factories.TestGroupFactory(topics=topics, test=test) resp = self.app.post(reverse('test_results', kwargs={'test_id': test.id})) fractions = [{ 'title': x['title'], 'short_title': x['short_title'], 'answers': {int(k): v for k, v in x['answers'].items()}, 'members_amount': x['members_amount'], } for x in resp.json['fractions']] self.assertEqual(fractions, [ { 'title': 'Darbo partijos frakcija', 'short_title': 'DP', 'answers': {int(tp1.pk): 1, int(tp2.pk): 0.3}, 'members_amount': 2, }, { 'title': 'Liberalų sąjūdžio frakcija', 'short_title': 'LLS', 'answers': {int(tp1.pk): 0.5, int(tp2.pk): -0.3}, 'members_amount': 1, }, ]) mps = [{ 'name': x['name'], 'fraction': x['fraction'], 'answers': {int(k): v for k, v in x['answers'].items()}, } for x in resp.json['mps']] self.assertEqual(mps, [ { 'name': 'Jonas Jonaitis', 'fraction': 'DP', 'answers': {int(tp1.pk): 1, int(tp2.pk): -0.3} }, { 'name': 'Petras Petraitis', 'fraction': 'DP', 'answers': {int(tp1.pk): 1, int(tp2.pk): 0.5} }, { 'name': 'Jonas Petraitis', 'fraction': 'LLS', 'answers': {int(tp1.pk): -0.8, int(tp2.pk): 1} }, ]) def test_results_view_answers(self): answers = { '1': 'yes', '2': 'no', } topics = factories.TopicFactory.create_batch( 2, name=factory.Iterator(['Socialinis modelis', 'Kariuomenė']), ) test = factories.CompatTestFactory() factories.TestGroupFactory(topics=topics, test=test) resp = self.app.post(reverse('test_results', kwargs={'test_id': test.id})) self.assertEqual(resp.json['user_answers'], None) ur = factories.UserResultFactory(result=answers) self.app.set_user(ur.user) resp = self.app.post(reverse('test_results', kwargs={'test_id': test.id})) self.assertEqual(resp.json['user_answers'], answers) class TestPositions(WebTest): maxDiff = None def test_position(self): AdminUserFactory() votings = [] seq = itertools.count(1) topic = factories.TopicFactory() factories.TestGroupFactory(topics=[topic]) mps = [ ('1', 'LSDPF', 'Petras', 'Gražulis', [1, 2]), ('2', 'LSDPF', 'Mantas', 'Adomėnas', [-2, 2]), ('3', 'TSLKDF', 'Remigijus', 'Ačas', [-2, 0, -1]), ] GroupFactory(abbr='LSDPF', name='Lietuvos socialdemokratų partijos frakcija') GroupFactory(abbr='TSLKDF', name='Tėvynės sąjungos-Lietuvos krikščionių demokratų frakcija') # Create some votings and assigne them to the topic for i in range(3): voting = factories.VotingFactory() factories.TopicVotingFactory(topic=topic, voting=voting) votings.append(voting) # Create person votes for topic and votings for p_asm_id, fraction, first_name, last_name, votes in mps: group = Group.objects.get(abbr=fraction) mp = ParliamentMemberFactory( source_id=p_asm_id, first_name=first_name, last_name=last_name, term_of_office='2012-2016', ) GroupMembershipFactory(member=mp, group=group) for i, vote in enumerate(votes): PersonVote.objects.create( key=str(next(seq)), voting_id=votings[i].key, p_asm_id=p_asm_id, fraction=fraction, name='%s %s' % (first_name, last_name), vote=vote, timestamp=datetime.datetime(2012, 11, 16), ) # Save topic from Django admin url = reverse('admin:compatibility_test_topic_change', args=[topic.pk]) resp = self.app.get(url, user='admin') resp.forms['topic_form'].submit('_save') # Check if ParliamentMember positions where updated. gr = lambda x: {int(k): float(v) for k, v in Group.objects.get(abbr=x).positions.items()} mp = lambda x: {int(k): float(v) for k, v in ParliamentMember.objects.get(first_name=x).positions.items()} self.assertEqual(gr('LSDPF'), {topic.pk: 0.75}) self.assertEqual(gr('TSLKDF'), {topic.pk: -1.0}) self.assertEqual(mp('Petras'), {topic.pk: 1.5}) self.assertEqual(mp('Mantas'), {topic.pk: 0.0}) self.assertEqual(mp('Remigijus'), {topic.pk: -1.0})
agpl-3.0
zergling-man/Rinbot
modules/tiny_games.py
1
6976
import random as ra import asyncio from discord.abc import User as duser from objects import hge import discord excluded=False commands={'rps101':['rps'], 'rpslist':['rpsl'], 'enqueue':['queue','q'], 'listqueue':['lq'], 'popqueue':['pop','pq','next'], 'rikka':[], 'hgopen':['hgo'], 'hgclose':['hgc'], 'hgjoin':['hgj','hg'], 'hglist':['hgl'], 'hgpause':['hgp','hgresume','hgr'], 'hgleave':[]} async def rps101(args, channel, message): names,_,results=u.parserps101() throw=u.strip(args[0]) if throw not in names: await channel.send('Not a valid choice! Use "rpslist" command!') throw=names.index(throw) mythrow=ra.randint(0,100) gap=(throw-mythrow)%101 if gap==0: await channel.send(content="Draw! How unusual! We both picked {0}".format(names[throw].upper())) elif gap in range(1,51): await channel.send("I picked {2}, so you lost. {1} {0}".format(results[mythrow][gap-1],names[mythrow].upper(),names[mythrow])) elif gap in range(51,101): await channel.send("I picked {2}, so you won! {1} {0}".format(results[throw][100-gap],names[throw].upper(),names[mythrow])) else: await channel.send("Not sure what just happened there... Game broke. My throw: {0} Your throw: {1}".format(mythrow,throw)) async def rpslist(args,channel,message): names,_,_=u.parserps101() await channel.send(names) async def enqueue(args, channel, message): try: u.queue[channel.guild.id].append('{0}#{1}'.format(message.author.name,message.author.discriminator)) except KeyError: u.queue[channel.guild.id]=['{0}#{1}'.format(message.author.name,message.author.discriminator)] await channel.send('Queued!') async def listqueue(args, channel, message): if channel.guild.id in u.queue and u.queue[channel.guild.id]: await channel.send(', '.join(u.queue[channel.guild.id])) else: await channel.send('Nobody in queue!') async def popqueue(args, channel, message): pop=args[0] if len(args) else 0 try: out=u.queue[channel.guild.id].pop(pop) except KeyError: await channel.send("Nobody in queue to remove!") return await channel.send(out) async def hgopen(args, channel, message): if not p.latentperms(['manage_guild'],channel,message.author): await channel.send('You lack permissions for this.') return if len(args)<1: await channel.send('You must specify a role for the players.') return prole=u.findobj(args[0], channel.guild.roles).id ch=channel.id srole=prole players=48 if len(args)==2: # Got to guess. a=u.findobj(args[1], channel.guild.roles) b=u.findobj(args[1], channel.guild.channels) if a: srole=a.id elif b: ch=b.id else: players=int(args[1]) elif len(args)==3: srole=u.findobj(args[1], channel.guild.roles).id a=u.findobj(args[2], channel.guild.channels) if a: ch=a.id else: players=int(args[2]) elif len(args)==4: srole=u.findobj(args[1], channel.guild.roles).id a=u.findobj(args[2], channel.guild.channels).id players=int(args[3]) event=hge.createevent(channel.guild.id,channel.id,prole,srole,players) if not event: await channel.send(hge.strings['runningevent']) await channel.send(hge.strings['eventstarted'].format(ch,u.p[channel.guild.id])) async def hgclose(args, channel, message): if not p.latentperms(['manage_guild'],channel,message.author): await channel.send('You lack permissions for this.') return event=hge.getevent(channel.guild) if not event: await channel.send(hge.strings['noevent']) return players=hge.getplayers(event['id']) hge.endevent(event['id']) await channel.send(hge.strings['eventended']) players=[u.findobj(x,channel.guild.members) for x in players] for user in players: if user is None: continue prole=u.findobj(event['playerrole'],channel.guild.roles) srole=u.findobj(event['specrole'],channel.guild.roles) try: await user.remove_roles(prole, srole, reason="Game over") except (discord.Forbidden, discord.HTTPException): await channel.send(hge.strings['noperm'].format((prole,srole),user)) async def hglist(args, channel, message): event=hge.getevent(channel.guild.id) if not event: await channel.send(hge.strings['noevent']) return if not event['active']: await channel.send(hge.strings['ispaused']) return players=hge.getplayers(event['id'],spectators=False) players=[u.findobj(pid,channel.guild.members) for pid in players] l=int(len(players)/2+0.5) firsthalf={i+1:players[i] for i in range(len(players[:l]))} secondhalf={i+l+1:players[i+l] for i in range(len(players[l:]))} await channel.send('\n'.join(['{0}. {1}#{2} ({3})'.format(pos,member.name,member.discriminator,member.id) for pos,member in firsthalf.items()])) await channel.send('\n'.join(['{0}. {1}#{2} ({3})'.format(pos,member.name,member.discriminator,member.id) for pos,member in secondhalf.items()])) async def hgjoin(args, channel, message): event=hge.getevent(channel.guild.id) if not event: await channel.send(hge.strings['noevent']) return if not event['active']: await channel.send(hge.strings['ispaused']) return attempt=hge.join(event['id'],event['participants'],message.author.id) if attempt==False: await channel.send(hge.strings['dupejoin']) return if attempt<=event['participants']: prole=u.findobj(event['playerrole'],channel.guild.roles) try: await message.author.add_roles(prole, reason="Gametime") except (discord.Forbidden, discord.HTTPException): await channel.send(hge.strings['noperm'].format(prole,message.author.username)) else: srole=u.findobj(event['specrole'],channel.guild.roles) try: await message.author.add_roles(srole,reason="Gametime") except (discord.Forbidden, discord.HTTPException): await channel.send(hge.strings['noperm'].format(srole,message.author.username)) await channel.send(hge.strings['joinevent']) async def hgleave(args, channel, message): event=hge.getevent(channel.guild.id) l=hge.leave(event['id'],message.author.id) if l: await channel.send(hge.strings['leftevent']) prole=u.findobj(event['playerrole'],channel.guild.roles) srole=u.findobj(event['specrole'],channel.guild.roles) user=message.author try: await user.remove_roles(prole, srole, reason="Game over") except (discord.Forbidden, discord.HTTPException): await channel.send(hge.strings['noperm'].format((prole,srole),user)) else: await channel.send(hge.strings['noevent']) async def hgpause(args, channel, message): event=hge.freeze(guild=channel.guild.id) if event is None: await channel.send(hge.strings['noevent']) return pause='p' if not event else 'unp' await channel.send('Event {}aused.'.format(pause)) async def rikka(args, channel, message): u.trace(args) main=args[0] if len(args)>0 else '🤔' chars=['👈','👇','👉','👆'] if len(args)<2 else args[1:] message=await channel.send('{0}{1}{0}'.format(chars[-1],main)) for i in range(10*len(chars)): await asyncio.sleep(0.5) #Uh, not sure if this is imported # Oh yeah apparently it is, cool. await message.edit(content='{0}{1}{0}'.format(chars[i%len(chars)],main))
mit
jupierce/openshift-tools
openshift/installer/vendored/openshift-ansible-3.2.24/roles/os_firewall/library/os_firewall_manage_iptables.py
28
10532
#!/usr/bin/python # -*- coding: utf-8 -*- # vim: expandtab:tabstop=4:shiftwidth=4 # pylint: disable=fixme, missing-docstring from subprocess import call, check_output DOCUMENTATION = ''' --- module: os_firewall_manage_iptables short_description: This module manages iptables rules for a given chain author: Jason DeTiberus requirements: [ ] ''' EXAMPLES = ''' ''' class IpTablesError(Exception): def __init__(self, msg, cmd, exit_code, output): super(IpTablesError, self).__init__(msg) self.msg = msg self.cmd = cmd self.exit_code = exit_code self.output = output class IpTablesAddRuleError(IpTablesError): pass class IpTablesRemoveRuleError(IpTablesError): pass class IpTablesSaveError(IpTablesError): pass class IpTablesCreateChainError(IpTablesError): def __init__(self, chain, msg, cmd, exit_code, output): # pylint: disable=too-many-arguments, line-too-long, redefined-outer-name super(IpTablesCreateChainError, self).__init__(msg, cmd, exit_code, output) self.chain = chain class IpTablesCreateJumpRuleError(IpTablesError): def __init__(self, chain, msg, cmd, exit_code, output): # pylint: disable=too-many-arguments, line-too-long, redefined-outer-name super(IpTablesCreateJumpRuleError, self).__init__(msg, cmd, exit_code, output) self.chain = chain # TODO: impliment rollbacks for any events that where successful and an # exception was thrown later. for example, when the chain is created # successfully, but the add/remove rule fails. class IpTablesManager(object): # pylint: disable=too-many-instance-attributes def __init__(self, module): self.module = module self.ip_version = module.params['ip_version'] self.check_mode = module.check_mode self.chain = module.params['chain'] self.create_jump_rule = module.params['create_jump_rule'] self.jump_rule_chain = module.params['jump_rule_chain'] self.cmd = self.gen_cmd() self.save_cmd = self.gen_save_cmd() self.output = [] self.changed = False def save(self): try: self.output.append(check_output(self.save_cmd, stderr=subprocess.STDOUT)) except subprocess.CalledProcessError as ex: raise IpTablesSaveError( msg="Failed to save iptables rules", cmd=ex.cmd, exit_code=ex.returncode, output=ex.output) def verify_chain(self): if not self.chain_exists(): self.create_chain() if self.create_jump_rule and not self.jump_rule_exists(): self.create_jump() def add_rule(self, port, proto): rule = self.gen_rule(port, proto) if not self.rule_exists(rule): self.verify_chain() if self.check_mode: self.changed = True self.output.append("Create rule for %s %s" % (proto, port)) else: cmd = self.cmd + ['-A'] + rule try: self.output.append(check_output(cmd)) self.changed = True self.save() except subprocess.CalledProcessError as ex: raise IpTablesCreateChainError( chain=self.chain, msg="Failed to create rule for " "%s %s" % (proto, port), cmd=ex.cmd, exit_code=ex.returncode, output=ex.output) def remove_rule(self, port, proto): rule = self.gen_rule(port, proto) if self.rule_exists(rule): if self.check_mode: self.changed = True self.output.append("Remove rule for %s %s" % (proto, port)) else: cmd = self.cmd + ['-D'] + rule try: self.output.append(check_output(cmd)) self.changed = True self.save() except subprocess.CalledProcessError as ex: raise IpTablesRemoveRuleError( chain=self.chain, msg="Failed to remove rule for %s %s" % (proto, port), cmd=ex.cmd, exit_code=ex.returncode, output=ex.output) def rule_exists(self, rule): check_cmd = self.cmd + ['-C'] + rule return True if call(check_cmd) == 0 else False def gen_rule(self, port, proto): return [self.chain, '-p', proto, '-m', 'state', '--state', 'NEW', '-m', proto, '--dport', str(port), '-j', 'ACCEPT'] def create_jump(self): if self.check_mode: self.changed = True self.output.append("Create jump rule for chain %s" % self.chain) else: try: cmd = self.cmd + ['-L', self.jump_rule_chain, '--line-numbers'] output = check_output(cmd, stderr=subprocess.STDOUT) # break the input rules into rows and columns input_rules = [s.split() for s in output.split('\n')] # Find the last numbered rule last_rule_num = None last_rule_target = None for rule in input_rules[:-1]: if rule: try: last_rule_num = int(rule[0]) except ValueError: continue last_rule_target = rule[1] # Naively assume that if the last row is a REJECT or DROP rule, # then we can insert our rule right before it, otherwise we # assume that we can just append the rule. if (last_rule_num and last_rule_target and last_rule_target in ['REJECT', 'DROP']): # insert rule cmd = self.cmd + ['-I', self.jump_rule_chain, str(last_rule_num)] else: # append rule cmd = self.cmd + ['-A', self.jump_rule_chain] cmd += ['-j', self.chain] output = check_output(cmd, stderr=subprocess.STDOUT) self.changed = True self.output.append(output) self.save() except subprocess.CalledProcessError as ex: if '--line-numbers' in ex.cmd: raise IpTablesCreateJumpRuleError( chain=self.chain, msg=("Failed to query existing " + self.jump_rule_chain + " rules to determine jump rule location"), cmd=ex.cmd, exit_code=ex.returncode, output=ex.output) else: raise IpTablesCreateJumpRuleError( chain=self.chain, msg=("Failed to create jump rule for chain " + self.chain), cmd=ex.cmd, exit_code=ex.returncode, output=ex.output) def create_chain(self): if self.check_mode: self.changed = True self.output.append("Create chain %s" % self.chain) else: try: cmd = self.cmd + ['-N', self.chain] self.output.append(check_output(cmd, stderr=subprocess.STDOUT)) self.changed = True self.output.append("Successfully created chain %s" % self.chain) self.save() except subprocess.CalledProcessError as ex: raise IpTablesCreateChainError( chain=self.chain, msg="Failed to create chain: %s" % self.chain, cmd=ex.cmd, exit_code=ex.returncode, output=ex.output ) def jump_rule_exists(self): cmd = self.cmd + ['-C', self.jump_rule_chain, '-j', self.chain] return True if call(cmd) == 0 else False def chain_exists(self): cmd = self.cmd + ['-L', self.chain] return True if call(cmd) == 0 else False def gen_cmd(self): cmd = 'iptables' if self.ip_version == 'ipv4' else 'ip6tables' return ["/usr/sbin/%s" % cmd] def gen_save_cmd(self): # pylint: disable=no-self-use return ['/usr/libexec/iptables/iptables.init', 'save'] def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), action=dict(required=True, choices=['add', 'remove', 'verify_chain']), chain=dict(required=False, default='OS_FIREWALL_ALLOW'), create_jump_rule=dict(required=False, type='bool', default=True), jump_rule_chain=dict(required=False, default='INPUT'), protocol=dict(required=False, choices=['tcp', 'udp']), port=dict(required=False, type='int'), ip_version=dict(required=False, default='ipv4', choices=['ipv4', 'ipv6']), ), supports_check_mode=True ) action = module.params['action'] protocol = module.params['protocol'] port = module.params['port'] if action in ['add', 'remove']: if not protocol: error = "protocol is required when action is %s" % action module.fail_json(msg=error) if not port: error = "port is required when action is %s" % action module.fail_json(msg=error) iptables_manager = IpTablesManager(module) try: if action == 'add': iptables_manager.add_rule(port, protocol) elif action == 'remove': iptables_manager.remove_rule(port, protocol) elif action == 'verify_chain': iptables_manager.verify_chain() except IpTablesError as ex: module.fail_json(msg=ex.msg) return module.exit_json(changed=iptables_manager.changed, output=iptables_manager.output) # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
apache-2.0
andrewbird/wader
test/test_aes.py
1
6946
# -*- coding: utf-8 -*- # Copyright (C) 2011 Vodafone España, S.A. # Author: Andrew Bird # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. """Unittests for the aes module""" from cStringIO import StringIO import os import pickle import random from twisted.trial import unittest from wader.common.aes import encryptData, decryptData def transform_passwd(passwd): valid_lengths = [16, 24, 32] for l in valid_lengths: if l >= len(passwd): return passwd.zfill(l) msg = "Password '%s' is too long, max length is 32 chars" raise Exception(msg % passwd) def make_gsm_dict(passwd): return {'gsm': {'passwd': passwd}} class TestEncoding(unittest.TestCase): """Tests for encoding""" def test_decode_fixed(self): T = [('b7b96d81cc86e6f9', '', 'cb867e4037a302198ee51523393923996cf56621de3e21ca46c147c7635a' '4597287a45f17dd984ccf9195db3b21e404007959d57fdd12594e96cb65d' 'fc453f6d'), ('0000000000497a9b', '2ed9eff633', 'e53100eac23d4afb2a0ed0f3b16b0a35066f71fea80a3559c2d21d368173' '8c0042d2f8bdbb4467eea3bf7102922fdb5f14ddc810837bc8ded8fcf40e' '717e82c5cee71acbe17d1135b99e5115c6cf881d'), ('000000000000d07d', '9771d7edad6b', '2a682d46c4ce665ba7acc238f11f50c836defd05de1431a2af5ab47dd4f4' '6c775a91b26fc087f347d5f1fe592575d3b1681372777e943ffaa2f77e81' 'e5c5ab6d32fa420c261ecebc72a3daf96e69ba4e'), ('39db1d780077cf13', '', '583c69ee32ced39574654a64701eb36d04e98d052976d840be4691d12a51' '7e1839f6208354ca244abcf28d6e9fecbef7c5559417c1e23285802a8ffc' 'ca907ff7'), ('00000000000052e0', '17a0b94b488e', '15e06ff63bd85c6b06a2d2f6a36128fa0154cdb7778676c5bd589ca0c3ea' 'ac4b8f179002b69d322b110f10a208e365285f7aff5ada1d36ee6cfc140e' '77f1f25b8ea13185b2add3896071a2fbf0bdd051'), ('00000000004ccb76', '034604574e', '3a058a4cb44af041b7e9609e0b05d2607b74e358f2046402671a715ee5c2' '453d5beb41acb8a01fd4278ceb2a58d07002ee92b567b3f60d68311aadd4' '538715022930390e43fe41853f6587261eae4dde'), ('e477fd4e2ab84397', '', 'd9b1ee5dadede634e5e508a9de6d2c5f5179efb5da65dcd4721d8c9fe6d1' '011eec6672a93e619413b20960b66b8c2a770ab736f83767434a0e03f392' '6fd967ca'), ('00000073966b9008', '15eed9', 'f87df3422f9a8e95c89149be782de06ca6c4d4189a2c5686d1186b51ebf2' 'dad879f15c1eb1943dd6e321e05dcc9759ef25189cc7980e6b3a8ae5ab38' 'f6fb20e31b4fe49929c8613f699dfe6b2adc71bf'), ('0000e34a67f172f8', '41dfd679b972', '490cc79eed800e217ab62702284d3e5c61022b8ec0459eb54ec1fd2071e1' 'e486f6a7d895b2ef34553dba1daed165a1d8a61e439cfa83777f1b5a97d0' 'c8e2ac081ef3fa703083c3db97211b33630ec2b1'), ('0000000000000018', 'f462f7e7aa525d1125cd7f', '17bfeab05df5be698372e71c107b5ac750846cc9e5d0259ea706945889a7' '70699f2f5229e4ed03f47a5b755d66cceb0d9796ec0e09ed28413986e447' '84fa9158a6ed086d98aca1558266b4db6150c1b9fa83b5597ea17559422b' 'ee95b9272afd'), ('0000000986b93eda', '785964d244f22e', '1459254a9dbe14a088acb911badff5b17d2993541a7080c6cc01de99096b' '48a81fed141f38a7843a55a88ad8b065394afde5a8a735b773a266cdbc20' '59fa73b2ebd25d47e71350c0e5b5f6bb352a7def'), ('0000002ef2b543f79bb97371', '447759', '55d47083f0cb00b9dd4065530f2ea67eb0065c20d4efe9f0125cf4b47785' '6268bd1718d544d3346c7d12d6293a222318890cc3c32ec776e711add688' '13a0bb0bdcbdb82e6244fd56f477a578d452b763'), ('b5f166646d9dde97', '9c082a9c', 'a3408b3e99b0fced6bda3eb648714169814f2260157c82d28780aacb30b0' '9905928fbf5bcfd98188d7dd185e625a3b05bd312e211b4a96f88e796a4a' 'ee137319afa8a7726f2dc0190c1e3c8377633dfe'), ('0000000085532a66', 'db57406690243f06', 'c0015c98db59407a43d09401aadef3bdab330d9926cffb8f9d7b0f8bbff5' 'b07a062b6fe6c2bc77bcd5d55f8c81fc943e772c86666cd875c007804226' '3f6a3dcca0acd83483156a744cbafbee0d43c0b3'), ('00000000005bd30e', '559958a4411bf08e0f', '270bba1a98649e37ec0de94d46085fcbbe50f50688f2eb5848bcb5aa601d' 'c98eb6e714b85c3679d21dd4a59beec82d48f09db11da49283bc261df59b' '770c20027ab75c190126875d118c8e659e4a7465'), ('00000b78961f4a341ce23df7', '4c73', 'f65de12f497d67e1d65902f4ed34e5c3ef0e881ae3942f29391e0f7fc7f8' '4a7bf67dea6b2d7c3e5cbbdb0801ed89703bb3b325b063d96b9eec7a11ed' '229361dc')] for t in T: original = make_gsm_dict(t[1]) # decode pickledobj = decryptData(t[0], t[2].decode('hex'), testforpickle=True) decrypted = pickle.load(StringIO(pickledobj)) self.assertEqual(decrypted, original) def test_encode_decode(self): n_keys = 8 n_passwds = 8 LEN = 12 for keys in range(n_keys): length = int(random.random() * LEN) key = os.urandom(LEN - length).encode('hex') padded_key = transform_passwd(key) for passwds in range(n_passwds): passwd = os.urandom(length).encode('hex') original = make_gsm_dict(passwd) # encode encrypted = encryptData(padded_key, pickle.dumps(original)) # decode pickledobj = decryptData(padded_key, encrypted) decrypted = pickle.load(StringIO(pickledobj)) self.assertEqual(decrypted, original)
gpl-2.0
dkamotsky/program-y
src/test/processors/post/test_formatnumbers.py
3
1511
import unittest from programy.processors.post.formatnumbers import FormatNumbersPostProcessor from programy.bot import Bot from programy.brain import Brain from programy.config.brain import BrainConfiguration from programy.config.bot import BotConfiguration class FormatNmbersTests(unittest.TestCase): def setUp(self): self.bot = Bot(Brain(BrainConfiguration()), config=BotConfiguration()) def test_format_numbers(self): processor = FormatNumbersPostProcessor() result = processor.process(self.bot, "testid", "23") self.assertIsNotNone(result) self.assertEqual("23", result) result = processor.process(self.bot, "testid", "23.45") self.assertIsNotNone(result) self.assertEqual("23.45", result) result = processor.process(self.bot, "testid", "23. 45") self.assertIsNotNone(result) self.assertEqual("23.45", result) result = processor.process(self.bot, "testid", "23 . 45") self.assertIsNotNone(result) self.assertEqual("23.45", result) result = processor.process(self.bot, "testid", "23,450") self.assertIsNotNone(result) self.assertEqual("23,450", result) result = processor.process(self.bot, "testid", "23, 450") self.assertIsNotNone(result) self.assertEqual("23,450", result) result = processor.process(self.bot, "testid", "23, 450, 000") self.assertIsNotNone(result) self.assertEqual("23,450,000", result)
mit
aakash-cr7/zulip
zerver/tornado/event_queue.py
2
36822
# See http://zulip.readthedocs.io/en/latest/events-system.html for # high-level documentation on how this system works. from __future__ import absolute_import from typing import cast, AbstractSet, Any, Callable, Dict, List, \ Mapping, MutableMapping, Optional, Iterable, Sequence, Set, Text, Union from django.utils.translation import ugettext as _ from django.conf import settings from django.utils import timezone from collections import deque import datetime import os import time import socket import logging import ujson import requests import atexit import sys import signal import tornado.autoreload import tornado.ioloop import random import traceback from zerver.models import UserProfile, Client from zerver.decorator import RespondAsynchronously from zerver.tornado.handlers import clear_handler_by_id, get_handler_by_id, \ finish_handler, handler_stats_string from zerver.lib.utils import statsd from zerver.middleware import async_request_restart from zerver.lib.narrow import build_narrow_filter from zerver.lib.queue import queue_json_publish from zerver.lib.request import JsonableError from zerver.lib.timestamp import timestamp_to_datetime from zerver.tornado.descriptors import clear_descriptor_by_handler_id, set_descriptor_by_handler_id import copy import six requests_client = requests.Session() for host in ['127.0.0.1', 'localhost']: if settings.TORNADO_SERVER and host in settings.TORNADO_SERVER: # This seems like the only working solution to ignore proxy in # requests library. requests_client.trust_env = False # The idle timeout used to be a week, but we found that in that # situation, queues from dead browser sessions would grow quite large # due to the accumulation of message data in those queues. IDLE_EVENT_QUEUE_TIMEOUT_SECS = 60 * 10 EVENT_QUEUE_GC_FREQ_MSECS = 1000 * 60 * 5 # Capped limit for how long a client can request an event queue # to live MAX_QUEUE_TIMEOUT_SECS = 7 * 24 * 60 * 60 # The heartbeats effectively act as a server-side timeout for # get_events(). The actual timeout value is randomized for each # client connection based on the below value. We ensure that the # maximum timeout value is 55 seconds, to deal with crappy home # wireless routers that kill "inactive" http connections. HEARTBEAT_MIN_FREQ_SECS = 45 class ClientDescriptor(object): def __init__(self, user_profile_id, user_profile_email, realm_id, event_queue, event_types, client_type_name, apply_markdown=True, all_public_streams=False, lifespan_secs=0, narrow=[]): # type: (int, Text, int, EventQueue, Optional[Sequence[str]], Text, bool, bool, int, Iterable[Sequence[Text]]) -> None # These objects are serialized on shutdown and restored on restart. # If fields are added or semantics are changed, temporary code must be # added to load_event_queues() to update the restored objects. # Additionally, the to_dict and from_dict methods must be updated self.user_profile_id = user_profile_id self.user_profile_email = user_profile_email self.realm_id = realm_id self.current_handler_id = None # type: Optional[int] self.current_client_name = None # type: Optional[Text] self.event_queue = event_queue self.queue_timeout = lifespan_secs self.event_types = event_types self.last_connection_time = time.time() self.apply_markdown = apply_markdown self.all_public_streams = all_public_streams self.client_type_name = client_type_name self._timeout_handle = None # type: Any # TODO: should be return type of ioloop.add_timeout self.narrow = narrow self.narrow_filter = build_narrow_filter(narrow) # Clamp queue_timeout to between minimum and maximum timeouts self.queue_timeout = max(IDLE_EVENT_QUEUE_TIMEOUT_SECS, min(self.queue_timeout, MAX_QUEUE_TIMEOUT_SECS)) def to_dict(self): # type: () -> Dict[str, Any] # If you add a new key to this dict, make sure you add appropriate # migration code in from_dict or load_event_queues to account for # loading event queues that lack that key. return dict(user_profile_id=self.user_profile_id, user_profile_email=self.user_profile_email, realm_id=self.realm_id, event_queue=self.event_queue.to_dict(), queue_timeout=self.queue_timeout, event_types=self.event_types, last_connection_time=self.last_connection_time, apply_markdown=self.apply_markdown, all_public_streams=self.all_public_streams, narrow=self.narrow, client_type_name=self.client_type_name) def __repr__(self): # type: () -> str return "ClientDescriptor<%s>" % (self.event_queue.id,) @classmethod def from_dict(cls, d): # type: (MutableMapping[str, Any]) -> ClientDescriptor if 'user_profile_email' not in d: # Temporary migration for the addition of the new user_profile_email field from zerver.models import get_user_profile_by_id d['user_profile_email'] = get_user_profile_by_id(d['user_profile_id']).email if 'client_type' in d: # Temporary migration for the rename of client_type to client_type_name d['client_type_name'] = d['client_type'] ret = cls(d['user_profile_id'], d['user_profile_email'], d['realm_id'], EventQueue.from_dict(d['event_queue']), d['event_types'], d['client_type_name'], d['apply_markdown'], d['all_public_streams'], d['queue_timeout'], d.get('narrow', [])) ret.last_connection_time = d['last_connection_time'] return ret def prepare_for_pickling(self): # type: () -> None self.current_handler_id = None self._timeout_handle = None def add_event(self, event): # type: (Dict[str, Any]) -> None if self.current_handler_id is not None: handler = get_handler_by_id(self.current_handler_id) async_request_restart(handler._request) self.event_queue.push(event) self.finish_current_handler() def finish_current_handler(self): # type: () -> bool if self.current_handler_id is not None: err_msg = "Got error finishing handler for queue %s" % (self.event_queue.id,) try: finish_handler(self.current_handler_id, self.event_queue.id, self.event_queue.contents(), self.apply_markdown) except Exception: logging.exception(err_msg) finally: self.disconnect_handler() return True return False def accepts_event(self, event): # type: (Mapping[str, Any]) -> bool if self.event_types is not None and event["type"] not in self.event_types: return False if event["type"] == "message": return self.narrow_filter(event) return True # TODO: Refactor so we don't need this function def accepts_messages(self): # type: () -> bool return self.event_types is None or "message" in self.event_types def idle(self, now): # type: (float) -> bool if not hasattr(self, 'queue_timeout'): self.queue_timeout = IDLE_EVENT_QUEUE_TIMEOUT_SECS return (self.current_handler_id is None and now - self.last_connection_time >= self.queue_timeout) def connect_handler(self, handler_id, client_name): # type: (int, Text) -> None self.current_handler_id = handler_id self.current_client_name = client_name set_descriptor_by_handler_id(handler_id, self) self.last_connection_time = time.time() def timeout_callback(): # type: () -> None self._timeout_handle = None # All clients get heartbeat events self.add_event(dict(type='heartbeat')) ioloop = tornado.ioloop.IOLoop.instance() heartbeat_time = time.time() + HEARTBEAT_MIN_FREQ_SECS + random.randint(0, 10) if self.client_type_name != 'API: heartbeat test': self._timeout_handle = ioloop.add_timeout(heartbeat_time, timeout_callback) def disconnect_handler(self, client_closed=False): # type: (bool) -> None if self.current_handler_id: clear_descriptor_by_handler_id(self.current_handler_id, None) clear_handler_by_id(self.current_handler_id) if client_closed: logging.info("Client disconnected for queue %s (%s via %s)" % (self.event_queue.id, self.user_profile_email, self.current_client_name)) self.current_handler_id = None self.current_client_name = None if self._timeout_handle is not None: ioloop = tornado.ioloop.IOLoop.instance() ioloop.remove_timeout(self._timeout_handle) self._timeout_handle = None def cleanup(self): # type: () -> None # Before we can GC the event queue, we need to disconnect the # handler and notify the client (or connection server) so that # they can cleanup their own state related to the GC'd event # queue. Finishing the handler before we GC ensures the # invariant that event queues are idle when passed to # `do_gc_event_queues` is preserved. self.finish_current_handler() do_gc_event_queues({self.event_queue.id}, {self.user_profile_id}, {self.realm_id}) def compute_full_event_type(event): # type: (Mapping[str, Any]) -> str if event["type"] == "update_message_flags": if event["all"]: # Put the "all" case in its own category return "all_flags/%s/%s" % (event["flag"], event["operation"]) return "flags/%s/%s" % (event["operation"], event["flag"]) return event["type"] class EventQueue(object): def __init__(self, id): # type: (str) -> None self.queue = deque() # type: deque[Dict[str, Any]] self.next_event_id = 0 # type: int self.id = id # type: str self.virtual_events = {} # type: Dict[str, Dict[str, Any]] def to_dict(self): # type: () -> Dict[str, Any] # If you add a new key to this dict, make sure you add appropriate # migration code in from_dict or load_event_queues to account for # loading event queues that lack that key. return dict(id=self.id, next_event_id=self.next_event_id, queue=list(self.queue), virtual_events=self.virtual_events) @classmethod def from_dict(cls, d): # type: (Dict[str, Any]) -> EventQueue ret = cls(d['id']) ret.next_event_id = d['next_event_id'] ret.queue = deque(d['queue']) ret.virtual_events = d.get("virtual_events", {}) return ret def push(self, event): # type: (Dict[str, Any]) -> None event['id'] = self.next_event_id self.next_event_id += 1 full_event_type = compute_full_event_type(event) if (full_event_type in ["pointer", "restart"] or full_event_type.startswith("flags/")): if full_event_type not in self.virtual_events: self.virtual_events[full_event_type] = copy.deepcopy(event) return # Update the virtual event with the values from the event virtual_event = self.virtual_events[full_event_type] virtual_event["id"] = event["id"] if "timestamp" in event: virtual_event["timestamp"] = event["timestamp"] if full_event_type == "pointer": virtual_event["pointer"] = event["pointer"] elif full_event_type == "restart": virtual_event["server_generation"] = event["server_generation"] elif full_event_type.startswith("flags/"): virtual_event["messages"] += event["messages"] else: self.queue.append(event) # Note that pop ignores virtual events. This is fine in our # current usage since virtual events should always be resolved to # a real event before being given to users. def pop(self): # type: () -> Dict[str, Any] return self.queue.popleft() def empty(self): # type: () -> bool return len(self.queue) == 0 and len(self.virtual_events) == 0 # See the comment on pop; that applies here as well def prune(self, through_id): # type: (int) -> None while len(self.queue) != 0 and self.queue[0]['id'] <= through_id: self.pop() def contents(self): # type: () -> List[Dict[str, Any]] contents = [] # type: List[Dict[str, Any]] virtual_id_map = {} # type: Dict[str, Dict[str, Any]] for event_type in self.virtual_events: virtual_id_map[self.virtual_events[event_type]["id"]] = self.virtual_events[event_type] virtual_ids = sorted(list(virtual_id_map.keys())) # Merge the virtual events into their final place in the queue index = 0 length = len(virtual_ids) for event in self.queue: while index < length and virtual_ids[index] < event["id"]: contents.append(virtual_id_map[virtual_ids[index]]) index += 1 contents.append(event) while index < length: contents.append(virtual_id_map[virtual_ids[index]]) index += 1 self.virtual_events = {} self.queue = deque(contents) return contents # maps queue ids to client descriptors clients = {} # type: Dict[str, ClientDescriptor] # maps user id to list of client descriptors user_clients = {} # type: Dict[int, List[ClientDescriptor]] # maps realm id to list of client descriptors with all_public_streams=True realm_clients_all_streams = {} # type: Dict[int, List[ClientDescriptor]] # list of registered gc hooks. # each one will be called with a user profile id, queue, and bool # last_for_client that is true if this is the last queue pertaining # to this user_profile_id # that is about to be deleted gc_hooks = [] # type: List[Callable[[int, ClientDescriptor, bool], None]] next_queue_id = 0 def add_client_gc_hook(hook): # type: (Callable[[int, ClientDescriptor, bool], None]) -> None gc_hooks.append(hook) def get_client_descriptor(queue_id): # type: (str) -> ClientDescriptor return clients.get(queue_id) def get_client_descriptors_for_user(user_profile_id): # type: (int) -> List[ClientDescriptor] return user_clients.get(user_profile_id, []) def get_client_descriptors_for_realm_all_streams(realm_id): # type: (int) -> List[ClientDescriptor] return realm_clients_all_streams.get(realm_id, []) def add_to_client_dicts(client): # type: (ClientDescriptor) -> None user_clients.setdefault(client.user_profile_id, []).append(client) if client.all_public_streams or client.narrow != []: realm_clients_all_streams.setdefault(client.realm_id, []).append(client) def allocate_client_descriptor(new_queue_data): # type: (MutableMapping[str, Any]) -> ClientDescriptor global next_queue_id queue_id = str(settings.SERVER_GENERATION) + ':' + str(next_queue_id) next_queue_id += 1 new_queue_data["event_queue"] = EventQueue(queue_id).to_dict() client = ClientDescriptor.from_dict(new_queue_data) clients[queue_id] = client add_to_client_dicts(client) return client def do_gc_event_queues(to_remove, affected_users, affected_realms): # type: (AbstractSet[str], AbstractSet[int], AbstractSet[int]) -> None def filter_client_dict(client_dict, key): # type: (MutableMapping[int, List[ClientDescriptor]], int) -> None if key not in client_dict: return new_client_list = [c for c in client_dict[key] if c.event_queue.id not in to_remove] if len(new_client_list) == 0: del client_dict[key] else: client_dict[key] = new_client_list for user_id in affected_users: filter_client_dict(user_clients, user_id) for realm_id in affected_realms: filter_client_dict(realm_clients_all_streams, realm_id) for id in to_remove: for cb in gc_hooks: cb(clients[id].user_profile_id, clients[id], clients[id].user_profile_id not in user_clients) del clients[id] def gc_event_queues(): # type: () -> None start = time.time() to_remove = set() # type: Set[str] affected_users = set() # type: Set[int] affected_realms = set() # type: Set[int] for (id, client) in six.iteritems(clients): if client.idle(start): to_remove.add(id) affected_users.add(client.user_profile_id) affected_realms.add(client.realm_id) # We don't need to call e.g. finish_current_handler on the clients # being removed because they are guaranteed to be idle and thus # not have a current handler. do_gc_event_queues(to_remove, affected_users, affected_realms) logging.info(('Tornado removed %d idle event queues owned by %d users in %.3fs.' + ' Now %d active queues, %s') % (len(to_remove), len(affected_users), time.time() - start, len(clients), handler_stats_string())) statsd.gauge('tornado.active_queues', len(clients)) statsd.gauge('tornado.active_users', len(user_clients)) def dump_event_queues(): # type: () -> None start = time.time() with open(settings.JSON_PERSISTENT_QUEUE_FILENAME, "w") as stored_queues: ujson.dump([(qid, client.to_dict()) for (qid, client) in six.iteritems(clients)], stored_queues) logging.info('Tornado dumped %d event queues in %.3fs' % (len(clients), time.time() - start)) def load_event_queues(): # type: () -> None global clients start = time.time() # ujson chokes on bad input pretty easily. We separate out the actual # file reading from the loading so that we don't silently fail if we get # bad input. try: with open(settings.JSON_PERSISTENT_QUEUE_FILENAME, "r") as stored_queues: json_data = stored_queues.read() try: clients = dict((qid, ClientDescriptor.from_dict(client)) for (qid, client) in ujson.loads(json_data)) except Exception: logging.exception("Could not deserialize event queues") except (IOError, EOFError): pass for client in six.itervalues(clients): # Put code for migrations due to event queue data format changes here add_to_client_dicts(client) logging.info('Tornado loaded %d event queues in %.3fs' % (len(clients), time.time() - start)) def send_restart_events(immediate=False): # type: (bool) -> None event = dict(type='restart', server_generation=settings.SERVER_GENERATION) # type: Dict[str, Any] if immediate: event['immediate'] = True for client in six.itervalues(clients): if client.accepts_event(event): client.add_event(event.copy()) def setup_event_queue(): # type: () -> None if not settings.TEST_SUITE: load_event_queues() atexit.register(dump_event_queues) # Make sure we dump event queues even if we exit via signal signal.signal(signal.SIGTERM, lambda signum, stack: sys.exit(1)) # type: ignore # https://github.com/python/mypy/issues/2955 tornado.autoreload.add_reload_hook(dump_event_queues) # type: ignore # TODO: Fix missing tornado.autoreload stub try: os.rename(settings.JSON_PERSISTENT_QUEUE_FILENAME, "/var/tmp/event_queues.json.last") except OSError: pass # Set up event queue garbage collection ioloop = tornado.ioloop.IOLoop.instance() pc = tornado.ioloop.PeriodicCallback(gc_event_queues, EVENT_QUEUE_GC_FREQ_MSECS, ioloop) pc.start() send_restart_events(immediate=settings.DEVELOPMENT) def fetch_events(query): # type: (Mapping[str, Any]) -> Dict[str, Any] queue_id = query["queue_id"] # type: str dont_block = query["dont_block"] # type: bool last_event_id = query["last_event_id"] # type: int user_profile_id = query["user_profile_id"] # type: int new_queue_data = query.get("new_queue_data") # type: Optional[MutableMapping[str, Any]] user_profile_email = query["user_profile_email"] # type: Text client_type_name = query["client_type_name"] # type: Text handler_id = query["handler_id"] # type: int try: was_connected = False orig_queue_id = queue_id extra_log_data = "" if queue_id is None: if dont_block: client = allocate_client_descriptor(new_queue_data) queue_id = client.event_queue.id else: raise JsonableError(_("Missing 'queue_id' argument")) else: if last_event_id is None: raise JsonableError(_("Missing 'last_event_id' argument")) client = get_client_descriptor(queue_id) if client is None: raise JsonableError(_("Bad event queue id: %s") % (queue_id,)) if user_profile_id != client.user_profile_id: raise JsonableError(_("You are not authorized to get events from this queue")) client.event_queue.prune(last_event_id) was_connected = client.finish_current_handler() if not client.event_queue.empty() or dont_block: response = dict(events=client.event_queue.contents(), handler_id=handler_id) # type: Dict[str, Any] if orig_queue_id is None: response['queue_id'] = queue_id if len(response["events"]) == 1: extra_log_data = "[%s/%s/%s]" % (queue_id, len(response["events"]), response["events"][0]["type"]) else: extra_log_data = "[%s/%s]" % (queue_id, len(response["events"])) if was_connected: extra_log_data += " [was connected]" return dict(type="response", response=response, extra_log_data=extra_log_data) # After this point, dont_block=False, the queue is empty, and we # have a pre-existing queue, so we wait for new events. if was_connected: logging.info("Disconnected handler for queue %s (%s/%s)" % (queue_id, user_profile_email, client_type_name)) except JsonableError as e: if hasattr(e, 'to_json_error_msg') and callable(e.to_json_error_msg): return dict(type="error", handler_id=handler_id, message=e.to_json_error_msg()) raise e client.connect_handler(handler_id, client_type_name) return dict(type="async") # The following functions are called from Django # Workaround to support the Python-requests 1.0 transition of .json # from a property to a function requests_json_is_function = callable(requests.Response.json) def extract_json_response(resp): # type: (requests.Response) -> Dict[str, Any] if requests_json_is_function: return resp.json() else: return resp.json # type: ignore # mypy trusts the stub, not the runtime type checking of this fn def request_event_queue(user_profile, user_client, apply_markdown, queue_lifespan_secs, event_types=None, all_public_streams=False, narrow=[]): # type: (UserProfile, Client, bool, int, Optional[Iterable[str]], bool, Iterable[Sequence[Text]]) -> Optional[str] if settings.TORNADO_SERVER: req = {'dont_block': 'true', 'apply_markdown': ujson.dumps(apply_markdown), 'all_public_streams': ujson.dumps(all_public_streams), 'client': 'internal', 'user_client': user_client.name, 'narrow': ujson.dumps(narrow), 'lifespan_secs': queue_lifespan_secs} if event_types is not None: req['event_types'] = ujson.dumps(event_types) try: resp = requests_client.get(settings.TORNADO_SERVER + '/api/v1/events', auth=requests.auth.HTTPBasicAuth( user_profile.email, user_profile.api_key), params=req) except requests.adapters.ConnectionError: logging.error('Tornado server does not seem to be running, check %s ' 'and %s for more information.' % (settings.ERROR_FILE_LOG_PATH, "tornado.log")) raise requests.adapters.ConnectionError( "Django cannot connect to Tornado server (%s); try restarting" % (settings.TORNADO_SERVER)) resp.raise_for_status() return extract_json_response(resp)['queue_id'] return None def get_user_events(user_profile, queue_id, last_event_id): # type: (UserProfile, str, int) -> List[Dict] if settings.TORNADO_SERVER: resp = requests_client.get(settings.TORNADO_SERVER + '/api/v1/events', auth=requests.auth.HTTPBasicAuth( user_profile.email, user_profile.api_key), params={'queue_id': queue_id, 'last_event_id': last_event_id, 'dont_block': 'true', 'client': 'internal'}) resp.raise_for_status() return extract_json_response(resp)['events'] return [] # Send email notifications to idle users # after they are idle for 1 hour NOTIFY_AFTER_IDLE_HOURS = 1 def build_offline_notification(user_profile_id, message_id): # type: (int, int) -> Dict[str, Any] return {"user_profile_id": user_profile_id, "message_id": message_id, "timestamp": time.time()} def missedmessage_hook(user_profile_id, queue, last_for_client): # type: (int, ClientDescriptor, bool) -> None # Only process missedmessage hook when the last queue for a # client has been garbage collected if not last_for_client: return message_ids_to_notify = [] # type: List[Dict[str, Any]] for event in queue.event_queue.contents(): if not event['type'] == 'message' or not event['flags']: continue if 'mentioned' in event['flags'] and 'read' not in event['flags']: notify_info = dict(message_id=event['message']['id']) if not event.get('push_notified', False): notify_info['send_push'] = True if not event.get('email_notified', False): notify_info['send_email'] = True message_ids_to_notify.append(notify_info) for notify_info in message_ids_to_notify: msg_id = notify_info['message_id'] notice = build_offline_notification(user_profile_id, msg_id) if notify_info.get('send_push', False): queue_json_publish("missedmessage_mobile_notifications", notice, lambda notice: None) if notify_info.get('send_email', False): queue_json_publish("missedmessage_emails", notice, lambda notice: None) def receiver_is_idle(user_profile_id, realm_presences): # type: (int, Optional[Dict[int, Dict[Text, Dict[str, Any]]]]) -> bool # If a user has no message-receiving event queues, they've got no open zulip # session so we notify them all_client_descriptors = get_client_descriptors_for_user(user_profile_id) message_event_queues = [client for client in all_client_descriptors if client.accepts_messages()] off_zulip = len(message_event_queues) == 0 # It's possible a recipient is not in the realm of a sender. We don't have # presence information in this case (and it's hard to get without an additional # db query) so we simply don't try to guess if this cross-realm recipient # has been idle for too long if realm_presences is None or user_profile_id not in realm_presences: return off_zulip # We want to find the newest "active" presence entity and compare that to the # activity expiry threshold. user_presence = realm_presences[user_profile_id] latest_active_timestamp = None idle = False for client, status in six.iteritems(user_presence): if (latest_active_timestamp is None or status['timestamp'] > latest_active_timestamp) and \ status['status'] == 'active': latest_active_timestamp = status['timestamp'] if latest_active_timestamp is None: idle = True else: active_datetime = timestamp_to_datetime(latest_active_timestamp) # 140 seconds is consistent with activity.js:OFFLINE_THRESHOLD_SECS idle = timezone.now() - active_datetime > datetime.timedelta(seconds=140) return off_zulip or idle def process_message_event(event_template, users): # type: (Mapping[str, Any], Iterable[Mapping[str, Any]]) -> None realm_presences = {int(k): v for k, v in event_template['presences'].items()} # type: Dict[int, Dict[Text, Dict[str, Any]]] sender_queue_id = event_template.get('sender_queue_id', None) # type: Optional[str] message_dict_markdown = event_template['message_dict_markdown'] # type: Dict[str, Any] message_dict_no_markdown = event_template['message_dict_no_markdown'] # type: Dict[str, Any] sender_id = message_dict_markdown['sender_id'] # type: int message_id = message_dict_markdown['id'] # type: int message_type = message_dict_markdown['type'] # type: str sending_client = message_dict_markdown['client'] # type: Text # To remove duplicate clients: Maps queue ID to {'client': Client, 'flags': flags} send_to_clients = {} # type: Dict[str, Dict[str, Any]] # Extra user-specific data to include extra_user_data = {} # type: Dict[int, Any] if 'stream_name' in event_template and not event_template.get("invite_only"): for client in get_client_descriptors_for_realm_all_streams(event_template['realm_id']): send_to_clients[client.event_queue.id] = {'client': client, 'flags': None} if sender_queue_id is not None and client.event_queue.id == sender_queue_id: send_to_clients[client.event_queue.id]['is_sender'] = True for user_data in users: user_profile_id = user_data['id'] # type: int flags = user_data.get('flags', []) # type: Iterable[str] for client in get_client_descriptors_for_user(user_profile_id): send_to_clients[client.event_queue.id] = {'client': client, 'flags': flags} if sender_queue_id is not None and client.event_queue.id == sender_queue_id: send_to_clients[client.event_queue.id]['is_sender'] = True # If the recipient was offline and the message was a single or group PM to him # or she was @-notified potentially notify more immediately received_pm = message_type == "private" and user_profile_id != sender_id mentioned = 'mentioned' in flags idle = receiver_is_idle(user_profile_id, realm_presences) always_push_notify = user_data.get('always_push_notify', False) if (received_pm or mentioned) and (idle or always_push_notify): notice = build_offline_notification(user_profile_id, message_id) queue_json_publish("missedmessage_mobile_notifications", notice, lambda notice: None) notified = dict(push_notified=True) # type: Dict[str, bool] # Don't send missed message emails if always_push_notify is True if idle: # We require RabbitMQ to do this, as we can't call the email handler # from the Tornado process. So if there's no rabbitmq support do nothing queue_json_publish("missedmessage_emails", notice, lambda notice: None) notified['email_notified'] = True extra_user_data[user_profile_id] = notified for client_data in six.itervalues(send_to_clients): client = client_data['client'] flags = client_data['flags'] is_sender = client_data.get('is_sender', False) # type: bool extra_data = extra_user_data.get(client.user_profile_id, None) # type: Optional[Mapping[str, bool]] if not client.accepts_messages(): # The actual check is the accepts_event() check below; # this line is just an optimization to avoid copying # message data unnecessarily continue if client.apply_markdown: message_dict = message_dict_markdown else: message_dict = message_dict_no_markdown # Make sure Zephyr mirroring bots know whether stream is invite-only if "mirror" in client.client_type_name and event_template.get("invite_only"): message_dict = message_dict.copy() message_dict["invite_only_stream"] = True if flags is not None: message_dict['is_mentioned'] = 'mentioned' in flags user_event = dict(type='message', message=message_dict, flags=flags) # type: Dict[str, Any] if extra_data is not None: user_event.update(extra_data) if is_sender: local_message_id = event_template.get('local_id', None) if local_message_id is not None: user_event["local_message_id"] = local_message_id if not client.accepts_event(user_event): continue # The below prevents (Zephyr) mirroring loops. if ('mirror' in sending_client and sending_client.lower() == client.client_type_name.lower()): continue client.add_event(user_event) def process_event(event, users): # type: (Mapping[str, Any], Iterable[int]) -> None for user_profile_id in users: for client in get_client_descriptors_for_user(user_profile_id): if client.accepts_event(event): client.add_event(dict(event)) def process_userdata_event(event_template, users): # type: (Mapping[str, Any], Iterable[Mapping[str, Any]]) -> None for user_data in users: user_profile_id = user_data['id'] user_event = dict(event_template) # shallow copy, but deep enough for our needs for key in user_data.keys(): if key != "id": user_event[key] = user_data[key] for client in get_client_descriptors_for_user(user_profile_id): if client.accepts_event(user_event): client.add_event(user_event) def process_notification(notice): # type: (Mapping[str, Any]) -> None event = notice['event'] # type: Mapping[str, Any] users = notice['users'] # type: Union[Iterable[int], Iterable[Mapping[str, Any]]] if event['type'] in ["update_message"]: process_userdata_event(event, cast(Iterable[Mapping[str, Any]], users)) elif event['type'] == "message": process_message_event(event, cast(Iterable[Mapping[str, Any]], users)) else: process_event(event, cast(Iterable[int], users)) # Runs in the Django process to send a notification to Tornado. # # We use JSON rather than bare form parameters, so that we can represent # different types and for compatibility with non-HTTP transports. def send_notification_http(data): # type: (Mapping[str, Any]) -> None if settings.TORNADO_SERVER and not settings.RUNNING_INSIDE_TORNADO: requests_client.post(settings.TORNADO_SERVER + '/notify_tornado', data=dict( data = ujson.dumps(data), secret = settings.SHARED_SECRET)) else: process_notification(data) def send_notification(data): # type: (Mapping[str, Any]) -> None queue_json_publish("notify_tornado", data, send_notification_http) def send_event(event, users): # type: (Mapping[str, Any], Union[Iterable[int], Iterable[Mapping[str, Any]]]) -> None """`users` is a list of user IDs, or in the case of `message` type events, a list of dicts describing the users and metadata about the user/message pair.""" queue_json_publish("notify_tornado", dict(event=event, users=users), send_notification_http)
apache-2.0
axbaretto/beam
sdks/python/.tox/docs/lib/python2.7/site-packages/tests/transport/compliance.py
6
3326
# Copyright 2016 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import flask import pytest from pytest_localserver.http import WSGIServer from six.moves import http_client from google.auth import exceptions # .invalid will never resolve, see https://tools.ietf.org/html/rfc2606 NXDOMAIN = 'test.invalid' class RequestResponseTests(object): @pytest.fixture(scope='module') def server(self): """Provides a test HTTP server. The test server is automatically created before a test and destroyed at the end. The server is serving a test application that can be used to verify requests. """ app = flask.Flask(__name__) app.debug = True # pylint: disable=unused-variable # (pylint thinks the flask routes are unusued.) @app.route('/basic') def index(): header_value = flask.request.headers.get('x-test-header', 'value') headers = {'X-Test-Header': header_value} return 'Basic Content', http_client.OK, headers @app.route('/server_error') def server_error(): return 'Error', http_client.INTERNAL_SERVER_ERROR # pylint: enable=unused-variable server = WSGIServer(application=app.wsgi_app) server.start() yield server server.stop() def test_request_basic(self, server): request = self.make_request() response = request(url=server.url + '/basic', method='GET') assert response.status == http_client.OK assert response.headers['x-test-header'] == 'value' assert response.data == b'Basic Content' def test_request_timeout(self, server): request = self.make_request() response = request(url=server.url + '/basic', method='GET', timeout=2) assert response.status == http_client.OK assert response.headers['x-test-header'] == 'value' assert response.data == b'Basic Content' def test_request_headers(self, server): request = self.make_request() response = request( url=server.url + '/basic', method='GET', headers={ 'x-test-header': 'hello world'}) assert response.status == http_client.OK assert response.headers['x-test-header'] == 'hello world' assert response.data == b'Basic Content' def test_request_error(self, server): request = self.make_request() response = request(url=server.url + '/server_error', method='GET') assert response.status == http_client.INTERNAL_SERVER_ERROR assert response.data == b'Error' def test_connection_error(self): request = self.make_request() with pytest.raises(exceptions.TransportError): request(url='http://{}'.format(NXDOMAIN), method='GET')
apache-2.0
TeachAtTUM/edx-platform
openedx/core/djangoapps/zendesk_proxy/apps.py
15
1254
""" Zendesk Proxy Configuration """ from django.apps import AppConfig from openedx.core.djangoapps.plugins.constants import ProjectType, SettingsType, PluginURLs, PluginSettings class ZendeskProxyConfig(AppConfig): """ AppConfig for zendesk proxy app """ name = 'openedx.core.djangoapps.zendesk_proxy' plugin_app = { PluginURLs.CONFIG: { ProjectType.CMS: { PluginURLs.NAMESPACE: u'', PluginURLs.REGEX: r'^zendesk_proxy/', PluginURLs.RELATIVE_PATH: u'urls', }, ProjectType.LMS: { PluginURLs.NAMESPACE: u'', PluginURLs.REGEX: r'^zendesk_proxy/', PluginURLs.RELATIVE_PATH: u'urls', } }, PluginSettings.CONFIG: { ProjectType.CMS: { SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: u'settings.common'}, SettingsType.AWS: {PluginSettings.RELATIVE_PATH: u'settings.aws'}, }, ProjectType.LMS: { SettingsType.COMMON: {PluginSettings.RELATIVE_PATH: u'settings.common'}, SettingsType.AWS: {PluginSettings.RELATIVE_PATH: u'settings.aws'}, } } }
agpl-3.0
damdam-s/OCB
addons/project_issue/project_issue.py
217
29319
#-*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from datetime import datetime from openerp import api from openerp import SUPERUSER_ID from openerp import tools from openerp.osv import fields, osv, orm from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools import html2plaintext from openerp.tools.translate import _ class project_issue_version(osv.Model): _name = "project.issue.version" _order = "name desc" _columns = { 'name': fields.char('Version Number', required=True), 'active': fields.boolean('Active', required=False), } _defaults = { 'active': 1, } class project_issue(osv.Model): _name = "project.issue" _description = "Project Issue" _order = "priority desc, create_date desc" _inherit = ['mail.thread', 'ir.needaction_mixin'] _mail_post_access = 'read' _track = { 'stage_id': { # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages 'project_issue.mt_issue_new': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence <= 1, 'project_issue.mt_issue_stage': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence > 1, }, 'user_id': { 'project_issue.mt_issue_assigned': lambda self, cr, uid, obj, ctx=None: obj.user_id and obj.user_id.id, }, 'kanban_state': { 'project_issue.mt_issue_blocked': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'blocked', 'project_issue.mt_issue_ready': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'done', }, } def _get_default_partner(self, cr, uid, context=None): project_id = self._get_default_project_id(cr, uid, context) if project_id: project = self.pool.get('project.project').browse(cr, uid, project_id, context=context) if project and project.partner_id: return project.partner_id.id return False def _get_default_project_id(self, cr, uid, context=None): """ Gives default project by checking if present in the context """ return self._resolve_project_id_from_context(cr, uid, context=context) def _get_default_stage_id(self, cr, uid, context=None): """ Gives default stage_id """ project_id = self._get_default_project_id(cr, uid, context=context) return self.stage_find(cr, uid, [], project_id, [('fold', '=', False)], context=context) def _resolve_project_id_from_context(self, cr, uid, context=None): """ Returns ID of project based on the value of 'default_project_id' context key, or None if it cannot be resolved to a single project. """ if context is None: context = {} if type(context.get('default_project_id')) in (int, long): return context.get('default_project_id') if isinstance(context.get('default_project_id'), basestring): project_name = context['default_project_id'] project_ids = self.pool.get('project.project').name_search(cr, uid, name=project_name, context=context) if len(project_ids) == 1: return int(project_ids[0][0]) return None def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None): access_rights_uid = access_rights_uid or uid stage_obj = self.pool.get('project.task.type') order = stage_obj._order # lame hack to allow reverting search, should just work in the trivial case if read_group_order == 'stage_id desc': order = "%s desc" % order # retrieve section_id from the context and write the domain # - ('id', 'in', 'ids'): add columns that should be present # - OR ('case_default', '=', True), ('fold', '=', False): add default columns that are not folded # - OR ('project_ids', 'in', project_id), ('fold', '=', False) if project_id: add project columns that are not folded search_domain = [] project_id = self._resolve_project_id_from_context(cr, uid, context=context) if project_id: search_domain += ['|', ('project_ids', '=', project_id)] search_domain += [('id', 'in', ids)] # perform search stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context) result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context) # restore order of the search result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0]))) fold = {} for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context): fold[stage.id] = stage.fold or False return result, fold def _compute_day(self, cr, uid, ids, fields, args, context=None): """ @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of Openday’s IDs @return: difference between current date and log date @param context: A standard dictionary for contextual values """ Calendar = self.pool['resource.calendar'] res = dict((res_id, {}) for res_id in ids) for issue in self.browse(cr, uid, ids, context=context): values = { 'day_open': 0.0, 'day_close': 0.0, 'working_hours_open': 0.0, 'working_hours_close': 0.0, 'days_since_creation': 0.0, 'inactivity_days': 0.0, } # if the working hours on the project are not defined, use default ones (8 -> 12 and 13 -> 17 * 5), represented by None calendar_id = None if issue.project_id and issue.project_id.resource_calendar_id: calendar_id = issue.project_id.resource_calendar_id.id dt_create_date = datetime.strptime(issue.create_date, DEFAULT_SERVER_DATETIME_FORMAT) if issue.date_open: dt_date_open = datetime.strptime(issue.date_open, DEFAULT_SERVER_DATETIME_FORMAT) values['day_open'] = (dt_date_open - dt_create_date).total_seconds() / (24.0 * 3600) values['working_hours_open'] = Calendar._interval_hours_get( cr, uid, calendar_id, dt_create_date, dt_date_open, timezone_from_uid=issue.user_id.id or uid, exclude_leaves=False, context=context) if issue.date_closed: dt_date_closed = datetime.strptime(issue.date_closed, DEFAULT_SERVER_DATETIME_FORMAT) values['day_close'] = (dt_date_closed - dt_create_date).total_seconds() / (24.0 * 3600) values['working_hours_close'] = Calendar._interval_hours_get( cr, uid, calendar_id, dt_create_date, dt_date_closed, timezone_from_uid=issue.user_id.id or uid, exclude_leaves=False, context=context) days_since_creation = datetime.today() - dt_create_date values['days_since_creation'] = days_since_creation.days if issue.date_action_last: inactive_days = datetime.today() - datetime.strptime(issue.date_action_last, DEFAULT_SERVER_DATETIME_FORMAT) elif issue.date_last_stage_update: inactive_days = datetime.today() - datetime.strptime(issue.date_last_stage_update, DEFAULT_SERVER_DATETIME_FORMAT) else: inactive_days = datetime.today() - datetime.strptime(issue.create_date, DEFAULT_SERVER_DATETIME_FORMAT) values['inactivity_days'] = inactive_days.days # filter only required values for field in fields: res[issue.id][field] = values[field] return res def _hours_get(self, cr, uid, ids, field_names, args, context=None): task_pool = self.pool.get('project.task') res = {} for issue in self.browse(cr, uid, ids, context=context): progress = 0.0 if issue.task_id: progress = task_pool._hours_get(cr, uid, [issue.task_id.id], field_names, args, context=context)[issue.task_id.id]['progress'] res[issue.id] = {'progress' : progress} return res def on_change_project(self, cr, uid, ids, project_id, context=None): if project_id: project = self.pool.get('project.project').browse(cr, uid, project_id, context=context) if project and project.partner_id: return {'value': {'partner_id': project.partner_id.id}} return {} def _get_issue_task(self, cr, uid, ids, context=None): issues = [] issue_pool = self.pool.get('project.issue') for task in self.pool.get('project.task').browse(cr, uid, ids, context=context): issues += issue_pool.search(cr, uid, [('task_id','=',task.id)]) return issues def _get_issue_work(self, cr, uid, ids, context=None): issues = [] issue_pool = self.pool.get('project.issue') for work in self.pool.get('project.task.work').browse(cr, uid, ids, context=context): if work.task_id: issues += issue_pool.search(cr, uid, [('task_id','=',work.task_id.id)]) return issues _columns = { 'id': fields.integer('ID', readonly=True), 'name': fields.char('Issue', required=True), 'active': fields.boolean('Active', required=False), 'create_date': fields.datetime('Creation Date', readonly=True, select=True), 'write_date': fields.datetime('Update Date', readonly=True), 'days_since_creation': fields.function(_compute_day, string='Days since creation date', \ multi='compute_day', type="integer", help="Difference in days between creation date and current date"), 'date_deadline': fields.date('Deadline'), 'section_id': fields.many2one('crm.case.section', 'Sales Team', \ select=True, help='Sales team to which Case belongs to.\ Define Responsible user and Email account for mail gateway.'), 'partner_id': fields.many2one('res.partner', 'Contact', select=1), 'company_id': fields.many2one('res.company', 'Company'), 'description': fields.text('Private Note'), 'kanban_state': fields.selection([('normal', 'Normal'),('blocked', 'Blocked'),('done', 'Ready for next stage')], 'Kanban State', track_visibility='onchange', help="A Issue's kanban state indicates special situations affecting it:\n" " * Normal is the default situation\n" " * Blocked indicates something is preventing the progress of this issue\n" " * Ready for next stage indicates the issue is ready to be pulled to the next stage", required=False), 'email_from': fields.char('Email', size=128, help="These people will receive email.", select=1), 'email_cc': fields.char('Watchers Emails', size=256, help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with a comma"), 'date_open': fields.datetime('Assigned', readonly=True, select=True), # Project Issue fields 'date_closed': fields.datetime('Closed', readonly=True, select=True), 'date': fields.datetime('Date'), 'date_last_stage_update': fields.datetime('Last Stage Update', select=True), 'channel': fields.char('Channel', help="Communication channel."), 'categ_ids': fields.many2many('project.category', string='Tags'), 'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority', select=True), 'version_id': fields.many2one('project.issue.version', 'Version'), 'stage_id': fields.many2one ('project.task.type', 'Stage', track_visibility='onchange', select=True, domain="[('project_ids', '=', project_id)]", copy=False), 'project_id': fields.many2one('project.project', 'Project', track_visibility='onchange', select=True), 'duration': fields.float('Duration'), 'task_id': fields.many2one('project.task', 'Task', domain="[('project_id','=',project_id)]"), 'day_open': fields.function(_compute_day, string='Days to Assign', multi='compute_day', type="float", store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}), 'day_close': fields.function(_compute_day, string='Days to Close', multi='compute_day', type="float", store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}), 'user_id': fields.many2one('res.users', 'Assigned to', required=False, select=1, track_visibility='onchange'), 'working_hours_open': fields.function(_compute_day, string='Working Hours to assign the Issue', multi='compute_day', type="float", store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}), 'working_hours_close': fields.function(_compute_day, string='Working Hours to close the Issue', multi='compute_day', type="float", store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}), 'inactivity_days': fields.function(_compute_day, string='Days since last action', multi='compute_day', type="integer", help="Difference in days between last action and current date"), 'color': fields.integer('Color Index'), 'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True), 'date_action_last': fields.datetime('Last Action', readonly=1), 'date_action_next': fields.datetime('Next Action', readonly=1), 'progress': fields.function(_hours_get, string='Progress (%)', multi='hours', group_operator="avg", help="Computed as: Time Spent / Total Time.", store = { 'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['task_id'], 10), 'project.task': (_get_issue_task, ['work_ids', 'remaining_hours', 'planned_hours', 'state', 'stage_id'], 10), 'project.task.work': (_get_issue_work, ['hours'], 10), }), } _defaults = { 'active': 1, 'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c), 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c), 'priority': '0', 'kanban_state': 'normal', 'date_last_stage_update': fields.datetime.now, 'user_id': lambda obj, cr, uid, context: uid, } _group_by_full = { 'stage_id': _read_group_stage_ids } def copy(self, cr, uid, id, default=None, context=None): issue = self.read(cr, uid, [id], ['name'], context=context)[0] if not default: default = {} default = default.copy() default.update(name=_('%s (copy)') % (issue['name'])) return super(project_issue, self).copy(cr, uid, id, default=default, context=context) def create(self, cr, uid, vals, context=None): context = dict(context or {}) if vals.get('project_id') and not context.get('default_project_id'): context['default_project_id'] = vals.get('project_id') if vals.get('user_id'): vals['date_open'] = fields.datetime.now() if 'stage_id' in vals: vals.update(self.onchange_stage_id(cr, uid, None, vals.get('stage_id'), context=context)['value']) # context: no_log, because subtype already handle this create_context = dict(context, mail_create_nolog=True) return super(project_issue, self).create(cr, uid, vals, context=create_context) def write(self, cr, uid, ids, vals, context=None): # stage change: update date_last_stage_update if 'stage_id' in vals: vals.update(self.onchange_stage_id(cr, uid, ids, vals.get('stage_id'), context=context)['value']) vals['date_last_stage_update'] = fields.datetime.now() if 'kanban_state' not in vals: vals['kanban_state'] = 'normal' # user_id change: update date_start if vals.get('user_id'): vals['date_open'] = fields.datetime.now() return super(project_issue, self).write(cr, uid, ids, vals, context) def onchange_task_id(self, cr, uid, ids, task_id, context=None): if not task_id: return {'value': {}} task = self.pool.get('project.task').browse(cr, uid, task_id, context=context) return {'value': {'user_id': task.user_id.id, }} def onchange_partner_id(self, cr, uid, ids, partner_id, context=None): """ This function returns value of partner email address based on partner :param part: Partner's id """ result = {} if partner_id: partner = self.pool['res.partner'].browse(cr, uid, partner_id, context) result['email_from'] = partner.email return {'value': result} def get_empty_list_help(self, cr, uid, help, context=None): context = dict(context or {}) context['empty_list_help_model'] = 'project.project' context['empty_list_help_id'] = context.get('default_project_id') context['empty_list_help_document_name'] = _("issues") return super(project_issue, self).get_empty_list_help(cr, uid, help, context=context) # ------------------------------------------------------- # Stage management # ------------------------------------------------------- def onchange_stage_id(self, cr, uid, ids, stage_id, context=None): if not stage_id: return {'value': {}} stage = self.pool['project.task.type'].browse(cr, uid, stage_id, context=context) if stage.fold: return {'value': {'date_closed': fields.datetime.now()}} return {'value': {'date_closed': False}} def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None): """ Override of the base.stage method Parameter of the stage search taken from the issue: - type: stage type must be the same or 'both' - section_id: if set, stages must belong to this section or be a default case """ if isinstance(cases, (int, long)): cases = self.browse(cr, uid, cases, context=context) # collect all section_ids section_ids = [] if section_id: section_ids.append(section_id) for task in cases: if task.project_id: section_ids.append(task.project_id.id) # OR all section_ids and OR with case_default search_domain = [] if section_ids: search_domain += [('|')] * (len(section_ids)-1) for section_id in section_ids: search_domain.append(('project_ids', '=', section_id)) search_domain += list(domain) # perform search, return the first found stage_ids = self.pool.get('project.task.type').search(cr, uid, search_domain, order=order, context=context) if stage_ids: return stage_ids[0] return False def case_escalate(self, cr, uid, ids, context=None): # FIXME rename this method to issue_escalate for issue in self.browse(cr, uid, ids, context=context): data = {} esc_proj = issue.project_id.project_escalation_id if not esc_proj: raise osv.except_osv(_('Warning!'), _('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!')) data['project_id'] = esc_proj.id if esc_proj.user_id: data['user_id'] = esc_proj.user_id.id issue.write(data) if issue.task_id: issue.task_id.write({'project_id': esc_proj.id, 'user_id': False}) return True # ------------------------------------------------------- # Mail gateway # ------------------------------------------------------- def message_get_reply_to(self, cr, uid, ids, context=None): """ Override to get the reply_to of the parent project. """ issues = self.browse(cr, SUPERUSER_ID, ids, context=context) project_ids = set([issue.project_id.id for issue in issues if issue.project_id]) aliases = self.pool['project.project'].message_get_reply_to(cr, uid, list(project_ids), context=context) return dict((issue.id, aliases.get(issue.project_id and issue.project_id.id or 0, False)) for issue in issues) def message_get_suggested_recipients(self, cr, uid, ids, context=None): recipients = super(project_issue, self).message_get_suggested_recipients(cr, uid, ids, context=context) try: for issue in self.browse(cr, uid, ids, context=context): if issue.partner_id: self._message_add_suggested_recipient(cr, uid, recipients, issue, partner=issue.partner_id, reason=_('Customer')) elif issue.email_from: self._message_add_suggested_recipient(cr, uid, recipients, issue, email=issue.email_from, reason=_('Customer Email')) except (osv.except_osv, orm.except_orm): # no read access rights -> just ignore suggested recipients because this imply modifying followers pass return recipients def message_new(self, cr, uid, msg, custom_values=None, context=None): """ Overrides mail_thread message_new that is called by the mailgateway through message_process. This override updates the document according to the email. """ if custom_values is None: custom_values = {} context = dict(context or {}, state_to='draft') defaults = { 'name': msg.get('subject') or _("No Subject"), 'email_from': msg.get('from'), 'email_cc': msg.get('cc'), 'partner_id': msg.get('author_id', False), 'user_id': False, } defaults.update(custom_values) res_id = super(project_issue, self).message_new(cr, uid, msg, custom_values=defaults, context=context) return res_id @api.cr_uid_ids_context def message_post(self, cr, uid, thread_id, body='', subject=None, type='notification', subtype=None, parent_id=False, attachments=None, context=None, content_subtype='html', **kwargs): """ Overrides mail_thread message_post so that we can set the date of last action field when a new message is posted on the issue. """ if context is None: context = {} res = super(project_issue, self).message_post(cr, uid, thread_id, body=body, subject=subject, type=type, subtype=subtype, parent_id=parent_id, attachments=attachments, context=context, content_subtype=content_subtype, **kwargs) if thread_id and subtype: self.write(cr, SUPERUSER_ID, thread_id, {'date_action_last': fields.datetime.now()}, context=context) return res class project(osv.Model): _inherit = "project.project" def _get_alias_models(self, cr, uid, context=None): return [('project.task', "Tasks"), ("project.issue", "Issues")] def _issue_count(self, cr, uid, ids, field_name, arg, context=None): Issue = self.pool['project.issue'] return { project_id: Issue.search_count(cr,uid, [('project_id', '=', project_id), ('stage_id.fold', '=', False)], context=context) for project_id in ids } _columns = { 'project_escalation_id': fields.many2one('project.project', 'Project Escalation', help='If any issue is escalated from the current Project, it will be listed under the project selected here.', states={'close': [('readonly', True)], 'cancelled': [('readonly', True)]}), 'issue_count': fields.function(_issue_count, type='integer', string="Issues",), 'issue_ids': fields.one2many('project.issue', 'project_id', domain=[('stage_id.fold', '=', False)]) } def _check_escalation(self, cr, uid, ids, context=None): project_obj = self.browse(cr, uid, ids[0], context=context) if project_obj.project_escalation_id: if project_obj.project_escalation_id.id == project_obj.id: return False return True _constraints = [ (_check_escalation, 'Error! You cannot assign escalation to the same project!', ['project_escalation_id']) ] class account_analytic_account(osv.Model): _inherit = 'account.analytic.account' _description = 'Analytic Account' _columns = { 'use_issues': fields.boolean('Issues', help="Check this field if this project manages issues"), } def on_change_template(self, cr, uid, ids, template_id, date_start=False, context=None): res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, date_start=date_start, context=context) if template_id and 'value' in res: template = self.browse(cr, uid, template_id, context=context) res['value']['use_issues'] = template.use_issues return res def _trigger_project_creation(self, cr, uid, vals, context=None): if context is None: context = {} res = super(account_analytic_account, self)._trigger_project_creation(cr, uid, vals, context=context) return res or (vals.get('use_issues') and not 'project_creation_in_progress' in context) class project_project(osv.Model): _inherit = 'project.project' _defaults = { 'use_issues': True } def _check_create_write_values(self, cr, uid, vals, context=None): """ Perform some check on values given to create or write. """ # Handle use_tasks / use_issues: if only one is checked, alias should take the same model if vals.get('use_tasks') and not vals.get('use_issues'): vals['alias_model'] = 'project.task' elif vals.get('use_issues') and not vals.get('use_tasks'): vals['alias_model'] = 'project.issue' def on_change_use_tasks_or_issues(self, cr, uid, ids, use_tasks, use_issues, context=None): values = {} if use_tasks and not use_issues: values['alias_model'] = 'project.task' elif not use_tasks and use_issues: values['alias_model'] = 'project.issue' return {'value': values} def create(self, cr, uid, vals, context=None): self._check_create_write_values(cr, uid, vals, context=context) return super(project_project, self).create(cr, uid, vals, context=context) def write(self, cr, uid, ids, vals, context=None): self._check_create_write_values(cr, uid, vals, context=context) return super(project_project, self).write(cr, uid, ids, vals, context=context) class res_partner(osv.osv): def _issue_count(self, cr, uid, ids, field_name, arg, context=None): Issue = self.pool['project.issue'] return { partner_id: Issue.search_count(cr,uid, [('partner_id', '=', partner_id)]) for partner_id in ids } """ Inherits partner and adds Issue information in the partner form """ _inherit = 'res.partner' _columns = { 'issue_count': fields.function(_issue_count, string='# Issues', type='integer'), } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Neurita/pelican-plugins
photos/test_photos.py
33
4885
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from pelican.generators import ArticlesGenerator from pelican.tests.support import unittest, get_settings from tempfile import mkdtemp from shutil import rmtree import photos CUR_DIR = os.path.dirname(__file__) class TestPhotos(unittest.TestCase): @classmethod def setUpClass(cls): cls.temp_path = mkdtemp(prefix='pelicantests.') cls.settings = get_settings(filenames={}) cls.settings['PATH'] = os.path.join(CUR_DIR, 'test_data') cls.settings['PHOTO_LIBRARY'] = os.path.join(CUR_DIR, 'test_data') cls.settings['DEFAULT_DATE'] = (1970, 1, 1) cls.settings['FILENAME_METADATA'] = '(?P<slug>[^.]+)' cls.settings['PLUGINS'] = [photos] cls.settings['CACHE_CONTENT'] = False cls.settings['OUTPUT_PATH'] = cls.temp_path photos.initialized(cls) cls.generator = ArticlesGenerator( context=cls.settings.copy(), settings=cls.settings, path=cls.settings['PATH'], theme=cls.settings['THEME'], output_path=cls.settings['OUTPUT_PATH']) photos.register() cls.generator.generate_context() photos.detect_gallery(cls.generator) photos.detect_image(cls.generator) @classmethod def tearDownClass(cls): rmtree(cls.temp_path) def test_image(self): for a in self.generator.articles: if 'image' in a.metadata: self.assertTrue( hasattr(a, 'photo_image'), msg="{} not recognized.".format(a.metadata['image'])) def test_gallery(self): for a in self.generator.articles: if 'gallety' in a.metadata: self.assertTrue( hasattr(a, 'photo_gallery'), msg="{} not recognized.".format(a.metadata['gallery'])) def get_article(self, slug): for a in self.generator.articles: if slug == a.slug: return a return None def test_photo_article_image(self): self.assertEqual(self.get_article('photo').photo_image, ('best.jpg', 'photos/agallery/besta.jpg', 'photos/agallery/bestt.jpg')) def test_photo_article_gallery(self): self.assertEqual(self.get_article('photo').photo_gallery[0], ('best.jpg', 'photos/agallery/best.jpg', 'photos/agallery/bestt.jpg', 'EXIF-best', 'Caption-best')) self.assertEqual(self.get_article('photo').photo_gallery[1], ('night.png', 'photos/agallery/night.jpg', 'photos/agallery/nightt.jpg', 'EXIF-night', '')) def test_photo_article_body(self): expected = ('<p>Here is my best photo, again.</p>\n' '<p><img alt="" src="/photos/agallery/besta.jpg" />.</p>') self.assertEqual(expected, self.get_article('photo').content) def test_filename_article_image(self): self.assertEqual( ('best.jpg', 'agallery/best.jpg', 'photos/agallery/bestt.jpg'), self.get_article('filename').photo_image) def test_filename_article_gallery(self): self.assertEqual(self.get_article('filename').photo_gallery[0], ('best.jpg', 'agallery/best.jpg', 'photos/agallery/bestt.jpg', 'EXIF-best', 'Caption-best')) self.assertEqual(self.get_article('filename').photo_gallery[1], ('night.png', 'agallery/night.png', 'photos/agallery/nightt.jpg', 'EXIF-night', '')) def test_filename_article_body(self): expected = ('<p>Here is my best photo, again.</p>\n' '<p><img alt="" src="{filename}agallery/best.jpg" />.</p>') self.assertEqual(expected, self.get_article('filename').content) def test_queue_resize(self): expected = [ ('photos/agallery/best.jpg', ('test_data/agallery/best.jpg', (1024, 768, 80))), ('photos/agallery/besta.jpg', ('test_data/agallery/best.jpg', (760, 506, 80))), ('photos/agallery/bestt.jpg', ('test_data/agallery/best.jpg', (192, 144, 60))), ('photos/agallery/night.jpg', ('test_data/agallery/night.png', (1024, 768, 80))), ('photos/agallery/nightt.jpg', ('test_data/agallery/night.png', (192, 144, 60)))] self.assertEqual(sorted(expected), sorted(photos.queue_resize.items())) if __name__ == '__main__': unittest.main()
agpl-3.0
GoogleCloudPlatform/python-compat-runtime
appengine-compat/exported_appengine_sdk/google/appengine/_internal/django/utils/numberformat.py
23
1676
from google.appengine._internal.django.conf import settings from google.appengine._internal.django.utils.safestring import mark_safe def format(number, decimal_sep, decimal_pos, grouping=0, thousand_sep=''): """ Gets a number (as a number or string), and returns it as a string, using formats definied as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator * thousand_sep: Thousand separator symbol (for example ",") """ use_grouping = settings.USE_L10N and settings.USE_THOUSAND_SEPARATOR and grouping # Make the common case fast: if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(unicode(number)) # sign if float(number) < 0: sign = '-' else: sign = '' str_number = unicode(number) if str_number[0] == '-': str_number = str_number[1:] # decimal part if '.' in str_number: int_part, dec_part = str_number.split('.') if decimal_pos: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, '' if decimal_pos: dec_part = dec_part + ('0' * (decimal_pos - len(dec_part))) if dec_part: dec_part = decimal_sep + dec_part # grouping if use_grouping: int_part_gd = '' for cnt, digit in enumerate(int_part[::-1]): if cnt and not cnt % grouping: int_part_gd += thousand_sep int_part_gd += digit int_part = int_part_gd[::-1] return sign + int_part + dec_part
apache-2.0