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
python-bugzilla/python-bugzilla
tests/test_api_externalbugs.py
1
1659
# # Copyright Red Hat, Inc. 2012 # # This work is licensed under the GNU GPLv2 or later. # See the COPYING file in the top-level directory. # """ Test miscellaneous API bits """ import tests import tests.mockbackend def test_externalbugs(): # Basic API testing of the ExternalBugs wrappers fakebz = tests.mockbackend.make_bz( externalbugs_add_args="data/mockargs/test_externalbugs_add.txt", externalbugs_add_return={}, externalbugs_update_args="data/mockargs/test_externalbugs_update.txt", externalbugs_update_return={}, externalbugs_remove_args="data/mockargs/test_externalbugs_remove.txt", externalbugs_remove_return={}) fakebz.add_external_tracker( bug_ids=[1234, 5678], ext_bz_bug_id="externalid", ext_type_id="launchpad", ext_type_description="some-bug-add-description", ext_type_url="https://example.com/launchpad/1234", ext_status="CLOSED", ext_description="link to launchpad", ext_priority="bigly") fakebz.update_external_tracker( ids=["external1", "external2"], ext_bz_bug_id="externalid-update", ext_type_id="mozilla", ext_type_description="some-bug-update", ext_type_url="https://mozilla.foo/bar/5678", ext_status="OPEN", bug_ids=["some", "bug", "id"], ext_description="link to mozilla", ext_priority="like, really bigly") fakebz.remove_external_tracker( ids="remove1", ext_bz_bug_id="99999", ext_type_id="footype", ext_type_description="foo-desc", ext_type_url="foo-url", bug_ids="blah")
gpl-2.0
nycholas/ask-undrgz
src/ask-undrgz/ask_undrgz/question/__init__.py
3
1681
# -*- coding: utf-8 -*- # # ask-undrgz system of questions uses data from underguiz. # Copyright (c) 2010, Nycholas de Oliveira e Oliveira <nycholas@gmail.com> # 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 the Nycholas de Oliveira e Oliveira 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 HOLDER 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.
bsd-3-clause
jinverar/Empire
lib/common/listeners.py
12
25600
""" Listener handling functionality for Empire. Handles listener startup from the database, listener shutdowns, and maintains the current listener configuration. """ import http import helpers from pydispatch import dispatcher import hashlib import sqlite3 class Listeners: def __init__(self, MainMenu, args=None): # pull out the controller objects self.mainMenu = MainMenu self.conn = MainMenu.conn self.agents = MainMenu.agents self.modules = None self.stager = None self.installPath = self.mainMenu.installPath # {listenerId : EmpireServer object} self.listeners = {} self.args = args # used to get a dict back from the query def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d # set the initial listener config to be the config defaults self.conn.row_factory = dict_factory cur = self.conn.cursor() cur.execute("SELECT staging_key,default_delay,default_jitter,default_profile,default_cert_path,default_port,default_lost_limit FROM config") defaults = cur.fetchone() cur.close() self.conn.row_factory = None # the current listener config options self.options = { 'Name' : { 'Description' : 'Listener name.', 'Required' : True, 'Value' : 'test' }, 'Host' : { 'Description' : 'Hostname/IP for staging.', 'Required' : True, 'Value' : "http://" + helpers.lhost() + ":" + defaults['default_port'] }, 'Type' : { 'Description' : 'Listener type (native, pivot, hop, foreign, meter).', 'Required' : True, 'Value' : "native" }, 'RedirectTarget' : { 'Description' : 'Listener target to redirect to for pivot/hop.', 'Required' : False, 'Value' : "" }, 'StagingKey' : { 'Description' : 'Staging key for initial agent negotiation.', 'Required' : True, 'Value' : defaults['staging_key'] }, 'DefaultDelay' : { 'Description' : 'Agent delay/reach back interval (in seconds).', 'Required' : True, 'Value' : defaults['default_delay'] }, 'DefaultJitter' : { 'Description' : 'Jitter in agent reachback interval (0.0-1.0).', 'Required' : True, 'Value' : defaults['default_jitter'] }, 'DefaultLostLimit' : { 'Description' : 'Number of missed checkins before exiting', 'Required' : True, 'Value' : defaults['default_lost_limit'] }, 'DefaultProfile' : { 'Description' : 'Default communication profile for the agent.', 'Required' : True, 'Value' : defaults['default_profile'] }, 'CertPath' : { 'Description' : 'Certificate path for https listeners.', 'Required' : False, 'Value' : defaults['default_cert_path'] }, 'Port' : { 'Description' : 'Port for the listener.', 'Required' : True, 'Value' : defaults['default_port'] }, 'KillDate' : { 'Description' : 'Date for the listener to exit (MM/dd/yyyy).', 'Required' : False, 'Value' : '' }, 'WorkingHours' : { 'Description' : 'Hours for the agent to operate (09:00-17:00).', 'Required' : False, 'Value' : '' } } def start_existing_listeners(self): """ Startup any listeners that are current in the database. """ cur = self.conn.cursor() cur.execute("SELECT id,name,host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,default_lost_limit FROM listeners") results = cur.fetchall() cur.close() # for each listener in the database, add it to the cache for result in results: # don't start the listener unless it's a native one if result[11] != "native": self.listeners[result[0]] = None else: port = result[3] # if cert_path is empty, no ssl is used cert_path = result[4] # build the handler server and kick if off server = http.EmpireServer(self.agents, port=port, cert=cert_path) # check if the listener started correctly if server.success: server.start() if (server.base_server()): # store off this servers in the "[id] : server" object array # only if the server starts up correctly self.listeners[result[0]] = server def set_listener_option(self, option, value): """ Set a listener option in the listener dictionary. """ # parse and auto-set some host parameters if option == "Host": if not value.startswith("http"): # if there's a current ssl cert path set, assume this is https if self.options['CertPath']['Value'] != "": self.options['Host']['Value'] = "https://"+str(value) else: # otherwise assume it's http self.options['Host']['Value'] = "http://"+str(value) # if there's a port specified, set that as well parts = value.split(":") if len(parts) > 1: self.options['Host']['Value'] = self.options['Host']['Value'] + ":" + str(parts[1]) self.options['Port']['Value'] = parts[1] elif value.startswith("https"): self.options['Host']['Value'] = value if self.options['CertPath']['Value'] == "": print helpers.color("[!] Error: Please specify a SSL cert path first") else: parts = value.split(":") # check if we have a port to extract if len(parts) == 3: # in case there's a resource uri at the end parts = parts[2].split("/") self.options['Port']['Value'] = parts[0] else: self.options['Port']['Value'] = "443" pass elif value.startswith("http"): self.options['Host']['Value'] = value parts = value.split(":") # check if we have a port to extract if len(parts) == 3: # in case there's a resource uri at the end parts = parts[2].split("/") self.options['Port']['Value'] = parts[0] else: self.options['Port']['Value'] = "80" elif option == "CertPath": self.options[option]['Value'] = value host = self.options["Host"]['Value'] # if we're setting a SSL cert path, but the host is specific at http if host.startswith("http:"): self.options["Host"]['Value'] = self.options["Host"]['Value'].replace("http:", "https:") elif option == "Port": self.options[option]['Value'] = value # set the port in the Host configuration as well host = self.options["Host"]['Value'] parts = host.split(":") if len(parts) == 2 or len(parts) == 3: self.options["Host"]['Value'] = parts[0] + ":" + parts[1] + ":" + str(value) elif option == "StagingKey": # if the staging key isn't 32 characters, assume we're md5 hashing it if len(value) != 32: self.options[option]['Value'] = hashlib.md5(value).hexdigest() elif option in self.options: self.options[option]['Value'] = value if option.lower() == "type": if value.lower() == "hop": # set the profile for hop.php for hop parts = self.options['DefaultProfile']['Value'].split("|") self.options['DefaultProfile']['Value'] = "/hop.php|" + "|".join(parts[1:]) else: print helpers.color("[!] Error: invalid option name") def get_listener_options(self): """ Return all currently set listener options. """ return self.options.keys() def kill_listener(self, listenerId): """ Shut a listener down and remove it from the database. """ self.shutdown_listener(listenerId) self.delete_listener(listenerId) def delete_listener(self, listenerId): """ Shut down the server associated with a listenerId and delete the listener from the database. """ # see if we were passed a name instead of an ID nameid = self.get_listener_id(listenerId) if nameid : listenerId = nameid # shut the listener down and remove it from the cache self.shutdown_listener(listenerId) # remove the listener from the database cur = self.conn.cursor() cur.execute("DELETE FROM listeners WHERE id=?", [listenerId]) cur.close() def shutdown_listener(self, listenerId): """ Shut down the server associated with a listenerId/name, but DON'T delete it from the database. If the listener is a pivot, task the associated agent to kill the redirector. """ try: # get the listener information [ID,name,host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,default_lost_limit] = self.get_listener(listenerId) listenerId = int(ID) if listenerId in self.listeners: # can't shut down hop, foreign, or meter listeners if listener_type == "hop" or listener_type == "foreign" or listener_type == "meter": pass # if this listener is a pivot, task the associated agent to shut it down elif listener_type == "pivot": print helpers.color("[*] Tasking pivot listener to shut down on agent " + name) killCmd = "netsh interface portproxy reset" self.agents.add_agent_task(name, "TASK_SHELL", killCmd) else: # otherwise get the server object associated with this listener and shut it down self.listeners[listenerId].shutdown() # remove the listener object from the internal cache del self.listeners[listenerId] except Exception as e: dispatcher.send("[!] Error shutting down listener " + str(listenerId), sender="Listeners") def get_listener(self, listenerId): """ Get the a specific listener from the database. """ # see if we were passed a name instead of an ID nameid = self.get_listener_id(listenerId) if nameid : listenerId = nameid cur = self.conn.cursor() cur.execute("SELECT id,name,host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,default_lost_limit FROM listeners WHERE id=?", [listenerId]) listener = cur.fetchone() cur.close() return listener def get_listeners(self): """ Return all listeners in the database. """ cur = self.conn.cursor() cur.execute("SELECT * FROM listeners") results = cur.fetchall() cur.close() return results def get_listener_names(self): """ Return all listener names in the database. """ cur = self.conn.cursor() cur.execute("SELECT name FROM listeners") results = cur.fetchall() cur.close() results = [str(n[0]) for n in results] return results def get_listener_ids(self): """ Return all listener IDs in the database. """ cur = self.conn.cursor() cur.execute("SELECT id FROM listeners") results = cur.fetchall() cur.close() results = [str(n[0]) for n in results] return results def is_listener_valid(self, listenerID): """ Check if this listener name or ID is valid/exists. """ cur = self.conn.cursor() cur.execute('SELECT * FROM listeners WHERE id=? or name=? limit 1', [listenerID, listenerID]) results = cur.fetchall() cur.close() return len(results) > 0 def is_listener_empire(self, listenerID): """ Check if this listener name is for Empire (otherwise for meter). """ cur = self.conn.cursor() cur.execute('SELECT listener_type FROM listeners WHERE id=? or name=? limit 1', [listenerID, listenerID]) results = cur.fetchall() cur.close() if results: if results[0][0].lower() == "meter": return False else: return True else: return None def get_listener_id(self, name): """ Resolve a name or port to listener ID. """ cur = self.conn.cursor() cur.execute('SELECT id FROM listeners WHERE name=?', [name]) results = cur.fetchone() cur.close() if results: return results[0] else: return None def get_staging_information(self, listenerId=None, port=None, host=None): """ Resolve a name or port to a agent staging information staging_key, default_delay, default_jitter, default_profile """ stagingInformation = None if(listenerId): cur = self.conn.cursor() cur.execute('SELECT host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,default_lost_limit FROM listeners WHERE id=? or name=? limit 1', [listenerID, listenerID]) stagingInformation = cur.fetchone() cur.close() elif(port): cur = self.conn.cursor() cur.execute("SELECT host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,default_lost_limit FROM listeners WHERE port=?", [port]) stagingInformation = cur.fetchone() cur.close() # used to get staging info for hop.php relays elif(host): cur = self.conn.cursor() cur.execute("SELECT host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,default_lost_limit FROM listeners WHERE host=?", [host]) stagingInformation = cur.fetchone() cur.close() return stagingInformation def get_stager_config(self, listenerID): """ Returns the (host, pivotServer, hop) information for this listener. Used in stagers.py to generate the various stagers. """ listener = self.get_listener(listenerID) if listener: # TODO: redo this SQL query so it's done by dict values name = listener[1] host = listener[2] port = listener[3] certPath = listener[4] stagingKey = listener[5] listenerType = listener[-2] redirectTarget = listener[-1] hop = False # if we have a pivot listener pivotServer = "" if listenerType == "pivot": # get the internal agent IP for this agent temp = self.agents.get_agent_internal_ip(name) if(temp): internalIP = temp[0] else: print helpers.color("[!] Agent for pivot listener no longer active.") return "" if certPath != "": pivotServer = "https://" else: pivotServer = "http://" pivotServer += internalIP + ":" + str(port) elif listenerType == "hop": hop = True return (host, stagingKey, pivotServer, hop) else: print helpers.color("[!] Error in listeners.get_stager_config(): no listener information returned") return None def validate_listener_options(self): """ Validate all currently set listener options. """ # make sure all options are set for option,values in self.options.iteritems(): if values['Required'] and (values['Value'] == ''): return False # make sure the name isn't already taken if self.is_listener_valid(self.options['Name']['Value']): for x in xrange(1,20): self.options['Name']['Value'] = self.options['Name']['Value'] + str(x) if not self.is_listener_valid(self.options['Name']['Value']): break if self.is_listener_valid(self.options['Name']['Value']): print helpers.color("[!] Listener name already used.") return False # if this is a pivot or hop listener, make sure we have a redirect listener target if self.options['Type']['Value'] == "pivot" or self.options['Type']['Value'] == "hop": if self.options['RedirectTarget']['Value'] == '': return False return True def add_listener_from_config(self): """ Start up a new listener with the internal config information. """ name = self.options['Name']['Value'] host = self.options['Host']['Value'] port = self.options['Port']['Value'] certPath = self.options['CertPath']['Value'] stagingKey = self.options['StagingKey']['Value'] defaultDelay = self.options['DefaultDelay']['Value'] defaultJitter = self.options['DefaultJitter']['Value'] defaultProfile = self.options['DefaultProfile']['Value'] killDate = self.options['KillDate']['Value'] workingHours = self.options['WorkingHours']['Value'] listenerType = self.options['Type']['Value'] redirectTarget = self.options['RedirectTarget']['Value'] defaultLostLimit = self.options['DefaultLostLimit']['Value'] # validate all of the options if self.validate_listener_options(): # if the listener name already exists, iterate the name # until we have a valid one if self.is_listener_valid(name): baseName = name for x in xrange(1,20): name = str(baseName) + str(x) if not self.is_listener_valid(name): break if self.is_listener_valid(name): print helpers.color("[!] Listener name already used.") return False # don't actually start a pivot/hop listener, foreign listeners, or meter listeners if listenerType == "pivot" or listenerType == "hop" or listenerType == "foreign" or listenerType == "meter": # double-check that the host ends in .php for hop listeners if listenerType == "hop" and not host.endswith(".php"): choice = raw_input(helpers.color("[!] Host does not end with .php continue? [y/N] ")) if choice.lower() == "" or choice.lower()[0] == "n": return False cur = self.conn.cursor() results = cur.execute("INSERT INTO listeners (name, host, port, cert_path, staging_key, default_delay, default_jitter, default_profile, kill_date, working_hours, listener_type, redirect_target,default_lost_limit) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", [name, host, port, certPath, stagingKey, defaultDelay, defaultJitter, defaultProfile, killDate, workingHours, listenerType, redirectTarget,defaultLostLimit] ) # get the ID for the listener cur.execute("SELECT id FROM listeners where name=?", [name]) result = cur.fetchone() cur.close() self.listeners[result[0]] = None else: # start up the server object server = http.EmpireServer(self.agents, port=port, cert=certPath) # check if the listener started correctly if server.success: server.start() if (server.base_server()): # add the listener to the database if start up cur = self.conn.cursor() results = cur.execute("INSERT INTO listeners (name, host, port, cert_path, staging_key, default_delay, default_jitter, default_profile, kill_date, working_hours, listener_type, redirect_target, default_lost_limit) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", [name, host, port, certPath, stagingKey, defaultDelay, defaultJitter, defaultProfile, killDate, workingHours, listenerType, redirectTarget,defaultLostLimit] ) # get the ID for the listener cur.execute("SELECT id FROM listeners where name=?", [name]) result = cur.fetchone() cur.close() # store off this server in the "[id] : server" object array # only if the server starts up correctly self.listeners[result[0]] = server else: print helpers.color("[!] Required listener option missing.") def add_pivot_listener(self, listenerName, sessionID, listenPort): """ Add a pivot listener associated with the sessionID agent on listenPort. This doesn't actually start a server, but rather clones the config for listenerName and sets everything in the database as appropriate. """ # get the internal agent IP for this agent internalIP = self.agents.get_agent_internal_ip(sessionID)[0] if internalIP == "": print helpers.color("[!] Invalid internal IP retrieved for "+sessionID+", not adding as pivot listener.") # make sure there isn't already a pivot listener on this agent elif self.is_listener_valid(sessionID): print helpers.color("[!] Pivot listener already exists on this agent.") else: # get the existing listener options [ID,name,host,port,cert_path,staging_key,default_delay,default_jitter,default_profile,kill_date,working_hours,listener_type,redirect_target,defaultLostLimit] = self.get_listener(listenerName) cur = self.conn.cursor() if cert_path != "": pivotHost = "https://" else: pivotHost = "http://" pivotHost += internalIP + ":" + str(listenPort) # insert the pivot listener with name=sessionID for the pivot agent cur.execute("INSERT INTO listeners (name, host, port, cert_path, staging_key, default_delay, default_jitter, default_profile, kill_date, working_hours, listener_type, redirect_target,default_lost_limit) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", [sessionID, pivotHost, listenPort, cert_path, staging_key, default_delay, default_jitter, default_profile, kill_date, working_hours, "pivot", name,defaultLostLimit] ) # get the ID for the listener cur.execute("SELECT id FROM listeners where name=?", [sessionID]) result = cur.fetchone() cur.close() # we don't actually have a server object, so just store None self.listeners[result[0]] = None def killall(self): """ Kill all active listeners and remove them from the database. """ # get all the listener IDs from the cache and delete each for listenerId in self.listeners.keys(): self.kill_listener(listenerId) def shutdownall(self): """ Shut down all active listeners but don't clear them from the database. Don't shut down pivot/hop listeners. """ # get all the listener IDs from the cache and delete each for listenerId in self.listeners.keys(): # skip pivot/hop listeners if self.listeners[listenerId]: self.shutdown_listener(listenerId)
bsd-3-clause
xsynergy510x/android_external_chromium_org
native_client_sdk/src/build_tools/nacl-mono-buildbot.py
130
7586
#!/usr/bin/env python # Copyright (c) 2012 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. import hashlib import json import os import sys import buildbot_common import build_version from build_paths import SCRIPT_DIR GS_MANIFEST_PATH = 'gs://nativeclient-mirror/nacl/nacl_sdk/' SDK_MANIFEST = 'naclsdk_manifest2.json' MONO_MANIFEST = 'naclmono_manifest.json' def build_and_upload_mono(sdk_revision, pepper_revision, sdk_url, upload_path, args): install_dir = 'naclmono' buildbot_common.RemoveDir(install_dir) revision_opt = ['--sdk-revision', sdk_revision] if sdk_revision else [] url_opt = ['--sdk-url', sdk_url] if sdk_url else [] buildbot_common.Run([sys.executable, 'nacl-mono-builder.py', '--arch', 'x86-32', '--install-dir', install_dir] + revision_opt + url_opt + args) buildbot_common.Run([sys.executable, 'nacl-mono-builder.py', '--arch', 'x86-64', '--install-dir', install_dir] + revision_opt + url_opt + args) buildbot_common.Run([sys.executable, 'nacl-mono-builder.py', '--arch', 'arm', '--install-dir', install_dir] + revision_opt + url_opt + args) buildbot_common.Run([sys.executable, 'nacl-mono-archive.py', '--upload-path', upload_path, '--pepper-revision', pepper_revision, '--install-dir', install_dir] + args) def get_sdk_build_info(): '''Returns a list of dictionaries for versions of NaCl Mono to build which are out of date compared to the SDKs available to naclsdk''' # Get a copy of the naclsdk manifest file buildbot_common.Run([buildbot_common.GetGsutil(), 'cp', GS_MANIFEST_PATH + SDK_MANIFEST, '.']) manifest_file = open(SDK_MANIFEST, 'r') sdk_manifest = json.loads(manifest_file.read()) manifest_file.close() pepper_infos = [] for key, value in sdk_manifest.items(): if key == 'bundles': stabilities = ['stable', 'beta', 'dev', 'post_stable'] # Pick pepper_* bundles, need pepper_19 or greater to build Mono bundles = filter(lambda b: (b['stability'] in stabilities and 'pepper_' in b['name']) and b['version'] >= 19, value) for b in bundles: newdict = {} newdict['pepper_revision'] = str(b['version']) linux_arch = filter(lambda u: u['host_os'] == 'linux', b['archives']) newdict['sdk_url'] = linux_arch[0]['url'] newdict['sdk_revision'] = b['revision'] newdict['stability'] = b['stability'] newdict['naclmono_name'] = 'naclmono_' + newdict['pepper_revision'] pepper_infos.append(newdict) # Get a copy of the naclmono manifest file buildbot_common.Run([buildbot_common.GetGsutil(), 'cp', GS_MANIFEST_PATH + MONO_MANIFEST, '.']) manifest_file = open(MONO_MANIFEST, 'r') mono_manifest = json.loads(manifest_file.read()) manifest_file.close() ret = [] mono_manifest_dirty = False # Check to see if we need to rebuild mono based on sdk revision for key, value in mono_manifest.items(): if key == 'bundles': for info in pepper_infos: bundle = filter(lambda b: b['name'] == info['naclmono_name'], value) if len(bundle) == 0: info['naclmono_rev'] = '1' ret.append(info) else: if info['sdk_revision'] != bundle[0]['sdk_revision']: # This bundle exists in the mono manifest, bump the revision # for the new build we're about to make. info['naclmono_rev'] = str(bundle[0]['revision'] + 1) ret.append(info) elif info['stability'] != bundle[0]['stability']: # If all that happened was the SDK bundle was promoted in stability, # change only that and re-write the manifest mono_manifest_dirty = True bundle[0]['stability'] = info['stability'] # re-write the manifest here because there are no bundles to build but # the manifest has changed if mono_manifest_dirty and len(ret) == 0: manifest_file = open(MONO_MANIFEST, 'w') manifest_file.write(json.dumps(mono_manifest, sort_keys=False, indent=2)) manifest_file.close() buildbot_common.Run([buildbot_common.GetGsutil(), 'cp', '-a', 'public-read', MONO_MANIFEST, GS_MANIFEST_PATH + MONO_MANIFEST]) return ret def update_mono_sdk_json(infos): '''Update the naclmono manifest with the newly built packages''' if len(infos) == 0: return manifest_file = open(MONO_MANIFEST, 'r') mono_manifest = json.loads(manifest_file.read()) manifest_file.close() for info in infos: bundle = {} bundle['name'] = info['naclmono_name'] bundle['description'] = 'Mono for Native Client' bundle['stability'] = info['stability'] bundle['recommended'] = 'no' bundle['version'] = 'experimental' archive = {} sha1_hash = hashlib.sha1() f = open(info['naclmono_name'] + '.bz2', 'rb') sha1_hash.update(f.read()) archive['size'] = f.tell() f.close() archive['checksum'] = { 'sha1': sha1_hash.hexdigest() } archive['host_os'] = 'all' archive['url'] = ('https://storage.googleapis.com/' 'nativeclient-mirror/nacl/nacl_sdk/%s/%s/%s.bz2' % (info['naclmono_name'], info['naclmono_rev'], info['naclmono_name'])) bundle['archives'] = [archive] bundle['revision'] = int(info['naclmono_rev']) bundle['sdk_revision'] = int(info['sdk_revision']) # Insert this new bundle into the manifest, # probably overwriting an existing bundle. for key, value in mono_manifest.items(): if key == 'bundles': existing = filter(lambda b: b['name'] == info['naclmono_name'], value) if len(existing) > 0: loc = value.index(existing[0]) value[loc] = bundle else: value.append(bundle) # Write out the file locally, then upload to its known location. manifest_file = open(MONO_MANIFEST, 'w') manifest_file.write(json.dumps(mono_manifest, sort_keys=False, indent=2)) manifest_file.close() buildbot_common.Run([buildbot_common.GetGsutil(), 'cp', '-a', 'public-read', MONO_MANIFEST, GS_MANIFEST_PATH + MONO_MANIFEST]) def main(args): args = args[1:] # Delete global configs that would override the mono builders' configuration. if 'AWS_CREDENTIAL_FILE' in os.environ: del os.environ['AWS_CREDENTIAL_FILE'] if 'BOTO_CONFIG' in os.environ: del os.environ['BOTO_CONFIG'] buildbot_revision = os.environ.get('BUILDBOT_REVISION', '') buildername = os.environ.get('BUILDBOT_BUILDERNAME', '') os.chdir(SCRIPT_DIR) if buildername == 'linux-sdk-mono32': assert buildbot_revision sdk_revision = buildbot_revision.split(':')[0] pepper_revision = build_version.ChromeMajorVersion() build_and_upload_mono(sdk_revision, pepper_revision, None, 'trunk.' + sdk_revision, args) elif buildername == 'linux-sdk-mono64': infos = get_sdk_build_info() for info in infos: # This will put the file in naclmono_19/1/naclmono_19.bz2 for example. upload_path = info['naclmono_name'] + '/' + info['naclmono_rev'] build_and_upload_mono(None, info['pepper_revision'], info['sdk_url'], upload_path, args) update_mono_sdk_json(infos) if __name__ == '__main__': sys.exit(main(sys.argv))
bsd-3-clause
Sapphirine/Stock-price-Movement-Prediction
pydoop/predict_new.py
1
4729
__author__ = 'arkilic' import csv import numpy as np from sklearn.linear_model import SGDRegressor import random import pprint raise NotImplementedError('This is the non-pydoop version, please see predict_new_map_red.py for the application') print "Prediction on IBM 30 year data:" f = open('HD-1984-2014-d.csv') tmp_data = csv.reader(f) my_data = list() for item in tmp_data: tmp_item = list() for i in item: tmp_item.append(i) my_data.append(tmp_item) data = my_data[1:] X = list() training_indices = list() for i in xrange(int(len(data)*0.8)): training_indices.append(i) test_indices = list() for i in xrange(int(len(data))): if i in training_indices: pass else: if i == 0: pass else: test_indices.append(i) for s_data in data: X.append(map(float, s_data[1:5])) y = list() y2 = list() for s_data in data: y.append(float(s_data[4])) y2.append(float(s_data[1])) pprint.pprint('Training the supervised learning model... Fit on training data') print('=========================================') try: clf = SGDRegressor(loss="huber") pprint.pprint(clf.fit(X, y)) except: raise try: clf2 = SGDRegressor(loss="huber") pprint.pprint(clf2.fit(X, y2)) except: raise print('=========================================') print 'Model testing itself! Confidence score on the training data used to construct:', clf.score(X, y) pprint.pprint('Ready to predict') print('=========================================') pprint.pprint('Testing with test data...') test_data = list() test_diff = list() predict_diff = list() for index in test_indices: tmp = data[index][1:5] my_tmp = list() for item in tmp: my_tmp.append(float(item)) test_data.append(my_tmp) test_diff.append(float(data[index][4]) - float(data[index][1])) # # prediction_results_close = clf.predict(test_data) prediction_results_open = clf2.predict(test_data) for i in xrange(len(prediction_results_close)): p_diff = prediction_results_close[i] - prediction_results_open[i] predict_diff.append(p_diff) print test_diff print predict_diff test_inc =0 for diff in test_diff: if diff > 0: test_inc += 1 p_inc =0 total_diff = 0 s = 0 for diff in predict_diff: total_diff += diff s += 1 if diff > -0.22: p_inc += 1 pprint.pprint(total_diff/float(s)) print "The accuracy of the stock price prediction with 30 years of data ..: ", (p_inc/float(test_inc))*100 print "=========================================================================================\n" print "Prediction on IBM 10 year data:" f = open('HD-2004-2014-d.csv') tmp_data = csv.reader(f) my_data = list() for item in tmp_data: tmp_item = list() for i in item: tmp_item.append(i) my_data.append(tmp_item) data = my_data[1:] X = list() training_indices = list() for i in xrange(int(len(data)*0.8)): training_indices.append(i) test_indices = list() for i in xrange(int(len(data))): if i in training_indices: pass else: if i == 0: pass else: test_indices.append(i) for s_data in data: X.append(map(float, s_data[1:5])) y = list() y2 = list() for s_data in data: y.append(float(s_data[4])) y2.append(float(s_data[1])) pprint.pprint('Training the supervised learning model... Fit on training data') print('=========================================') try: clf = SGDRegressor(loss="huber") pprint.pprint(clf.fit(X, y)) except: raise try: clf2 = SGDRegressor(loss="huber") pprint.pprint(clf2.fit(X, y2)) except: raise print('=========================================') print 'Model testing itself! Confidence score on the training data used to construct:', clf.score(X, y) pprint.pprint('Ready to predict') print('=========================================') pprint.pprint('Testing with test data...') test_data = list() test_diff = list() predict_diff = list() for index in test_indices: tmp = data[index][1:5] my_tmp = list() for item in tmp: my_tmp.append(float(item)) test_data.append(my_tmp) test_diff.append(float(data[index][4]) - float(data[index][1])) # # prediction_results_close = clf.predict(test_data) prediction_results_open = clf2.predict(test_data) for i in xrange(len(prediction_results_close)): p_diff = prediction_results_close[i] - prediction_results_open[i] predict_diff.append(p_diff) print test_diff print predict_diff p = 0 for entry in test_diff: if entry > 0: p += 1 k=0 for entry in predict_diff: if entry>-0.77: k += 1 print "The accuracy of the stock price prediction with 10 years of data ..: ", (p/float(k))*100
apache-2.0
worsht/antlr4
runtime/Python2/src/antlr4/BufferedTokenStream.py
9
11937
# # [The "BSD license"] # Copyright (c) 2012 Terence Parr # Copyright (c) 2012 Sam Harwell # Copyright (c) 2014 Eric Vergnaud # 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. # 3. The name of the author may not be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. # This implementation of {@link TokenStream} loads tokens from a # {@link TokenSource} on-demand, and places the tokens in a buffer to provide # access to any previous token by index. # # <p> # This token stream ignores the value of {@link Token#getChannel}. If your # parser requires the token stream filter tokens to only those on a particular # channel, such as {@link Token#DEFAULT_CHANNEL} or # {@link Token#HIDDEN_CHANNEL}, use a filtering token stream such a # {@link CommonTokenStream}.</p> from io import StringIO from antlr4.Token import Token from antlr4.error.Errors import IllegalStateException # this is just to keep meaningful parameter types to Parser class TokenStream(object): pass class BufferedTokenStream(TokenStream): def __init__(self, tokenSource): # The {@link TokenSource} from which tokens for this stream are fetched. self.tokenSource = tokenSource # A collection of all tokens fetched from the token source. The list is # considered a complete view of the input once {@link #fetchedEOF} is set # to {@code true}. self.tokens = [] # The index into {@link #tokens} of the current token (next token to # {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be # {@link #LT LT(1)}. # # <p>This field is set to -1 when the stream is first constructed or when # {@link #setTokenSource} is called, indicating that the first token has # not yet been fetched from the token source. For additional information, # see the documentation of {@link IntStream} for a description of # Initializing Methods.</p> self.index = -1 # Indicates whether the {@link Token#EOF} token has been fetched from # {@link #tokenSource} and added to {@link #tokens}. This field improves # performance for the following cases: # # <ul> # <li>{@link #consume}: The lookahead check in {@link #consume} to prevent # consuming the EOF symbol is optimized by checking the values of # {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> # <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into # {@link #tokens} is trivial with this field.</li> # <ul> self.fetchedEOF = False def mark(self): return 0 def release(self, marker): # no resources to release pass def reset(self): self.seek(0) def seek(self, index): self.lazyInit() self.index = self.adjustSeekIndex(index) def get(self, index): self.lazyInit() return self.tokens[index] def consume(self): skipEofCheck = False if self.index >= 0: if self.fetchedEOF: # the last token in tokens is EOF. skip check if p indexes any # fetched token except the last. skipEofCheck = self.index < len(self.tokens) - 1 else: # no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = self.index < len(self.tokens) else: # not yet initialized skipEofCheck = False if not skipEofCheck and self.LA(1) == Token.EOF: raise IllegalStateException("cannot consume EOF") if self.sync(self.index + 1): self.index = self.adjustSeekIndex(self.index + 1) # Make sure index {@code i} in tokens has a token. # # @return {@code true} if a token is located at index {@code i}, otherwise # {@code false}. # @see #get(int i) #/ def sync(self, i): n = i - len(self.tokens) + 1 # how many more elements we need? if n > 0 : fetched = self.fetch(n) return fetched >= n return True # Add {@code n} elements to buffer. # # @return The actual number of elements added to the buffer. #/ def fetch(self, n): if self.fetchedEOF: return 0 for i in range(0, n): t = self.tokenSource.nextToken() t.tokenIndex = len(self.tokens) self.tokens.append(t) if t.type==Token.EOF: self.fetchedEOF = True return i + 1 return n # Get all tokens from start..stop inclusively#/ def getTokens(self, start, stop, types=None): if start<0 or stop<0: return None self.lazyInit() subset = [] if stop >= len(self.tokens): stop = len(self.tokens)-1 for i in range(start, stop): t = self.tokens[i] if t.type==Token.EOF: break if types is None or t.type in types: subset.append(t) return subset def LA(self, i): return self.LT(i).type def LB(self, k): if (self.index-k) < 0: return None return self.tokens[self.index-k] def LT(self, k): self.lazyInit() if k==0: return None if k < 0: return self.LB(-k) i = self.index + k - 1 self.sync(i) if i >= len(self.tokens): # return EOF token # EOF must be last token return self.tokens[len(self.tokens)-1] return self.tokens[i] # Allowed derived classes to modify the behavior of operations which change # the current stream position by adjusting the target token index of a seek # operation. The default implementation simply returns {@code i}. If an # exception is thrown in this method, the current stream index should not be # changed. # # <p>For example, {@link CommonTokenStream} overrides this method to ensure that # the seek target is always an on-channel token.</p> # # @param i The target token index. # @return The adjusted target token index. def adjustSeekIndex(self, i): return i def lazyInit(self): if self.index == -1: self.setup() def setup(self): self.sync(0) self.index = self.adjustSeekIndex(0) # Reset this token stream by setting its token source.#/ def setTokenSource(self, tokenSource): self.tokenSource = tokenSource self.tokens = [] self.index = -1 # Given a starting index, return the index of the next token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and EOF. #/ def nextTokenOnChannel(self, i, channel): self.sync(i) if i>=len(self.tokens): return -1 token = self.tokens[i] while token.channel!=channel: if token.type==Token.EOF: return -1 i += 1 self.sync(i) token = self.tokens[i] return i # Given a starting index, return the index of the previous token on channel. # Return i if tokens[i] is on channel. Return -1 if there are no tokens # on channel between i and 0. def previousTokenOnChannel(self, i, channel): while i>=0 and self.tokens[i].channel!=channel: i -= 1 return i # Collect all tokens on specified channel to the right of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or # EOF. If channel is -1, find any non default channel token. def getHiddenTokensToRight(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer nextOnChannel = self.nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) from_ = tokenIndex+1 # if none onchannel to right, nextOnChannel=-1 so set to = last token to = (len(self.tokens)-1) if nextOnChannel==-1 else nextOnChannel return self.filterForChannel(from_, to, channel) # Collect all tokens on specified channel to the left of # the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. # If channel is -1, find any non default channel token. def getHiddenTokensToLeft(self, tokenIndex, channel=-1): self.lazyInit() if tokenIndex<0 or tokenIndex>=len(self.tokens): raise Exception(str(tokenIndex) + " not in 0.." + str(len(self.tokens)-1)) from antlr4.Lexer import Lexer prevOnChannel = self.previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1: return None # if none on channel to left, prevOnChannel=-1 then from=0 from_ = prevOnChannel+1 to = tokenIndex-1 return self.filterForChannel(from_, to, channel) def filterForChannel(self, left, right, channel): hidden = [] for i in range(left, right+1): t = self.tokens[i] if channel==-1: from antlr4.Lexer import Lexer if t.channel!= Lexer.DEFAULT_TOKEN_CHANNEL: hidden.append(t) elif t.channel==channel: hidden.append(t) if len(hidden)==0: return None return hidden def getSourceName(self): return self.tokenSource.getSourceName() # Get the text of all tokens in this buffer.#/ def getText(self, interval=None): self.lazyInit() self.fill() if interval is None: interval = (0, len(self.tokens)-1) start = interval[0] if isinstance(start, Token): start = start.tokenIndex stop = interval[1] if isinstance(stop, Token): stop = stop.tokenIndex if start is None or stop is None or start<0 or stop<0: return "" if stop >= len(self.tokens): stop = len(self.tokens)-1 with StringIO() as buf: for i in range(start, stop+1): t = self.tokens[i] if t.type==Token.EOF: break buf.write(t.text) return buf.getvalue() # Get all tokens from lexer until EOF#/ def fill(self): self.lazyInit() while self.fetch(1000)==1000: pass
bsd-3-clause
Ingenico-ePayments/connect-sdk-python2
ingenico/connect/sdk/domain/payment/definitions/customer_approve_payment.py
2
1375
# -*- coding: utf-8 -*- # # This class was auto-generated from the API references found at # https://epayments-api.developer-ingenico.com/s2sapi/v1/ # from ingenico.connect.sdk.data_object import DataObject class CustomerApprovePayment(DataObject): __account_type = None @property def account_type(self): """ | Type of the customer account that is used to place this order. Can have one of the following values: * none - The account that was used to place the order is a guest account or no account was used at all * created - The customer account was created during this transaction * existing - The customer account was an already existing account prior to this transaction Type: str """ return self.__account_type @account_type.setter def account_type(self, value): self.__account_type = value def to_dictionary(self): dictionary = super(CustomerApprovePayment, self).to_dictionary() if self.account_type is not None: dictionary['accountType'] = self.account_type return dictionary def from_dictionary(self, dictionary): super(CustomerApprovePayment, self).from_dictionary(dictionary) if 'accountType' in dictionary: self.account_type = dictionary['accountType'] return self
mit
turbomanage/training-data-analyst
courses/machine_learning/deepdive2/structured/labs/serving/application/lib/pyasn1_modules/rfc7191.py
13
7062
# This file is being contributed to of pyasn1-modules software. # # Created by Russ Housley without assistance from the asn1ate tool. # Modified by Russ Housley to add support for opentypes. # # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # # CMS Key Package Receipt and Error Content Types # # ASN.1 source from: # https://www.rfc-editor.org/rfc/rfc7191.txt from pyasn1.type import constraint from pyasn1.type import namedtype from pyasn1.type import namedval from pyasn1.type import opentype from pyasn1.type import tag from pyasn1.type import univ from pyasn1_modules import rfc5280 from pyasn1_modules import rfc5652 MAX = float('inf') DistinguishedName = rfc5280.DistinguishedName # SingleAttribute is the same as Attribute in RFC 5652, except that the # attrValues SET must have one and only one member class AttributeValue(univ.Any): pass class AttributeValues(univ.SetOf): pass AttributeValues.componentType = AttributeValue() AttributeValues.sizeSpec = univ.Set.sizeSpec + constraint.ValueSizeConstraint(1, 1) class SingleAttribute(univ.Sequence): pass SingleAttribute.componentType = namedtype.NamedTypes( namedtype.NamedType('attrType', univ.ObjectIdentifier()), namedtype.NamedType('attrValues', AttributeValues(), openType=opentype.OpenType('attrType', rfc5652.cmsAttributesMap) ) ) # SIR Entity Name class SIREntityNameType(univ.ObjectIdentifier): pass class SIREntityNameValue(univ.Any): pass class SIREntityName(univ.Sequence): pass SIREntityName.componentType = namedtype.NamedTypes( namedtype.NamedType('sirenType', SIREntityNameType()), namedtype.NamedType('sirenValue', univ.OctetString()) # CONTAINING the DER-encoded SIREntityNameValue ) class SIREntityNames(univ.SequenceOf): pass SIREntityNames.componentType = SIREntityName() SIREntityNames.sizeSpec=constraint.ValueSizeConstraint(1, MAX) id_dn = univ.ObjectIdentifier('2.16.840.1.101.2.1.16.0') class siren_dn(SIREntityName): def __init__(self): SIREntityName.__init__(self) self['sirenType'] = id_dn # Key Package Error CMS Content Type class EnumeratedErrorCode(univ.Enumerated): pass # Error codes with values <= 33 are aligned with RFC 5934 EnumeratedErrorCode.namedValues = namedval.NamedValues( ('decodeFailure', 1), ('badContentInfo', 2), ('badSignedData', 3), ('badEncapContent', 4), ('badCertificate', 5), ('badSignerInfo', 6), ('badSignedAttrs', 7), ('badUnsignedAttrs', 8), ('missingContent', 9), ('noTrustAnchor', 10), ('notAuthorized', 11), ('badDigestAlgorithm', 12), ('badSignatureAlgorithm', 13), ('unsupportedKeySize', 14), ('unsupportedParameters', 15), ('signatureFailure', 16), ('insufficientMemory', 17), ('incorrectTarget', 23), ('missingSignature', 29), ('resourcesBusy', 30), ('versionNumberMismatch', 31), ('revokedCertificate', 33), ('ambiguousDecrypt', 60), ('noDecryptKey', 61), ('badEncryptedData', 62), ('badEnvelopedData', 63), ('badAuthenticatedData', 64), ('badAuthEnvelopedData', 65), ('badKeyAgreeRecipientInfo', 66), ('badKEKRecipientInfo', 67), ('badEncryptContent', 68), ('badEncryptAlgorithm', 69), ('missingCiphertext', 70), ('decryptFailure', 71), ('badMACAlgorithm', 72), ('badAuthAttrs', 73), ('badUnauthAttrs', 74), ('invalidMAC', 75), ('mismatchedDigestAlg', 76), ('missingCertificate', 77), ('tooManySigners', 78), ('missingSignedAttributes', 79), ('derEncodingNotUsed', 80), ('missingContentHints', 81), ('invalidAttributeLocation', 82), ('badMessageDigest', 83), ('badKeyPackage', 84), ('badAttributes', 85), ('attributeComparisonFailure', 86), ('unsupportedSymmetricKeyPackage', 87), ('unsupportedAsymmetricKeyPackage', 88), ('constraintViolation', 89), ('ambiguousDefaultValue', 90), ('noMatchingRecipientInfo', 91), ('unsupportedKeyWrapAlgorithm', 92), ('badKeyTransRecipientInfo', 93), ('other', 127) ) class ErrorCodeChoice(univ.Choice): pass ErrorCodeChoice.componentType = namedtype.NamedTypes( namedtype.NamedType('enum', EnumeratedErrorCode()), namedtype.NamedType('oid', univ.ObjectIdentifier()) ) class KeyPkgID(univ.OctetString): pass class KeyPkgIdentifier(univ.Choice): pass KeyPkgIdentifier.componentType = namedtype.NamedTypes( namedtype.NamedType('pkgID', KeyPkgID()), namedtype.NamedType('attribute', SingleAttribute()) ) class KeyPkgVersion(univ.Integer): pass KeyPkgVersion.namedValues = namedval.NamedValues( ('v1', 1), ('v2', 2) ) KeyPkgVersion.subtypeSpec = constraint.ValueRangeConstraint(1, 65535) id_ct_KP_keyPackageError = univ.ObjectIdentifier('2.16.840.1.101.2.1.2.78.6') class KeyPackageError(univ.Sequence): pass KeyPackageError.componentType = namedtype.NamedTypes( namedtype.DefaultedNamedType('version', KeyPkgVersion().subtype(value='v2')), namedtype.OptionalNamedType('errorOf', KeyPkgIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0))), namedtype.NamedType('errorBy', SIREntityName()), namedtype.NamedType('errorCode', ErrorCodeChoice()) ) # Key Package Receipt CMS Content Type id_ct_KP_keyPackageReceipt = univ.ObjectIdentifier('2.16.840.1.101.2.1.2.78.3') class KeyPackageReceipt(univ.Sequence): pass KeyPackageReceipt.componentType = namedtype.NamedTypes( namedtype.DefaultedNamedType('version', KeyPkgVersion().subtype(value='v2')), namedtype.NamedType('receiptOf', KeyPkgIdentifier()), namedtype.NamedType('receivedBy', SIREntityName()) ) # Key Package Receipt Request Attribute class KeyPkgReceiptReq(univ.Sequence): pass KeyPkgReceiptReq.componentType = namedtype.NamedTypes( namedtype.DefaultedNamedType('encryptReceipt', univ.Boolean().subtype(value=0)), namedtype.OptionalNamedType('receiptsFrom', SIREntityNames().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))), namedtype.NamedType('receiptsTo', SIREntityNames()) ) id_aa_KP_keyPkgIdAndReceiptReq = univ.ObjectIdentifier('2.16.840.1.101.2.1.5.65') class KeyPkgIdentifierAndReceiptReq(univ.Sequence): pass KeyPkgIdentifierAndReceiptReq.componentType = namedtype.NamedTypes( namedtype.NamedType('pkgID', KeyPkgID()), namedtype.OptionalNamedType('receiptReq', KeyPkgReceiptReq()) ) # Map of Attribute Type OIDs to Attributes are added to # the ones that are in rfc5652.py _cmsAttributesMapUpdate = { id_aa_KP_keyPkgIdAndReceiptReq: KeyPkgIdentifierAndReceiptReq(), } rfc5652.cmsAttributesMap.update(_cmsAttributesMapUpdate) # Map of CMC Content Type OIDs to CMC Content Types are added to # the ones that are in rfc5652.py _cmsContentTypesMapUpdate = { id_ct_KP_keyPackageError: KeyPackageError(), id_ct_KP_keyPackageReceipt: KeyPackageReceipt(), } rfc5652.cmsContentTypesMap.update(_cmsContentTypesMapUpdate)
apache-2.0
veger/ansible
lib/ansible/utils/module_docs_fragments/eos.py
58
6957
# # (c) 2015, Peter Sprygada <psprygada@ansible.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/>. class ModuleDocFragment(object): # Standard files documentation fragment DOCUMENTATION = """ options: authorize: description: - B(Deprecated) - "Starting with Ansible 2.5 we recommend using C(connection: network_cli) and C(become: yes)." - This option is only required if you are using eAPI. - For more information please see the L(EOS Platform Options guide, ../network/user_guide/platform_eos.html). - HORIZONTALLINE - Instructs the module to enter privileged mode on the remote device before sending any commands. If not specified, the device will attempt to execute all commands in non-privileged mode. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_AUTHORIZE) will be used instead. type: bool default: 'no' auth_pass: description: - B(Deprecated) - "Starting with Ansible 2.5 we recommend using C(connection: network_cli) and C(become: yes) with C(become_pass)." - This option is only required if you are using eAPI. - For more information please see the L(EOS Platform Options guide, ../network/user_guide/platform_eos.html). - HORIZONTALLINE - Specifies the password to use if required to enter privileged mode on the remote device. If I(authorize) is false, then this argument does nothing. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead. provider: description: - B(Deprecated) - "Starting with Ansible 2.5 we recommend using C(connection: network_cli)." - This option is only required if you are using eAPI. - For more information please see the L(EOS Platform Options guide, ../network/user_guide/platform_eos.html). - HORIZONTALLINE - A dict object containing connection details. suboptions: host: description: - Specifies the DNS host name or address for connecting to the remote device over the specified transport. The value of host is used as the destination address for the transport. required: true port: description: - Specifies the port to use when building the connection to the remote device. This value applies to either I(cli) or I(eapi). The port value will default to the appropriate transport common port if none is provided in the task. (cli=22, http=80, https=443). default: 0 (use common port) username: description: - Configures the username to use to authenticate the connection to the remote device. This value is used to authenticate either the CLI login or the eAPI authentication depending on which transport is used. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_USERNAME) will be used instead. password: description: - Specifies the password to use to authenticate the connection to the remote device. This is a common argument used for either I(cli) or I(eapi) transports. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_PASSWORD) will be used instead. timeout: description: - Specifies the timeout in seconds for communicating with the network device for either connecting or sending commands. If the timeout is exceeded before the operation is completed, the module will error. default: 10 ssh_keyfile: description: - Specifies the SSH keyfile to use to authenticate the connection to the remote device. This argument is only used for I(cli) transports. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_SSH_KEYFILE) will be used instead. authorize: description: - Instructs the module to enter privileged mode on the remote device before sending any commands. If not specified, the device will attempt to execute all commands in non-privileged mode. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_AUTHORIZE) will be used instead. type: bool default: 'no' auth_pass: description: - Specifies the password to use if required to enter privileged mode on the remote device. If I(authorize) is false, then this argument does nothing. If the value is not specified in the task, the value of environment variable C(ANSIBLE_NET_AUTH_PASS) will be used instead. transport: description: - Configures the transport connection to use when connecting to the remote device. required: true choices: - eapi - cli default: cli use_ssl: description: - Configures the I(transport) to use SSL if set to true only when the C(transport=eapi). If the transport argument is not eapi, this value is ignored. type: bool default: 'yes' validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. If the transport argument is not eapi, this value is ignored. type: bool use_proxy: description: - If C(no), the environment variables C(http_proxy) and C(https_proxy) will be ignored. type: bool default: 'yes' version_added: "2.5" notes: - For information on using CLI, eAPI and privileged mode see the :ref:`EOS Platform Options guide <eos_platform_options>` - For more information on using Ansible to manage network devices see the :ref:`Ansible Network Guide <network_guide>` - For more information on using Ansible to manage Arista EOS devices see the `Arista integration page <https://www.ansible.com/ansible-arista-networks>`_. """
gpl-3.0
luis-rr/nest-simulator
pynest/nest/tests/test_quantal_stp_synapse.py
13
4049
# -*- coding: utf-8 -*- # # test_quantal_stp_synapse.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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. # # NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. # This script compares the two variants of the Tsodyks/Markram synapse in NEST. import nest import numpy import unittest @nest.check_stack class QuantalSTPSynapseTestCase(unittest.TestCase): """Compare quantal_stp_synapse with its deterministic equivalent.""" def test_QuantalSTPSynapse(self): """Compare quantal_stp_synapse with its deterministic equivalent""" nest.ResetKernel() nest.set_verbosity(100) n_syn = 12 # number of synapses in a connection n_trials = 50 # number of measurement trials # parameter set for facilitation fac_params = {"U": 0.03, "u": 0.03, "tau_fac": 500., "tau_rec": 200., "weight": 1.} # Here we assign the parameter set to the synapse models t1_params = fac_params # for tsodyks2_synapse t2_params = t1_params.copy() # for furhmann_synapse t2_params['n'] = n_syn t2_params['weight'] = 1. / n_syn nest.SetDefaults("tsodyks2_synapse", t1_params) nest.SetDefaults("quantal_stp_synapse", t2_params) nest.SetDefaults("iaf_psc_exp", {"tau_syn_ex": 3., 'tau_m': 70.}) source = nest.Create('spike_generator') nest.SetStatus( source, { 'spike_times': [ 30., 60., 90., 120., 150., 180., 210., 240., 270., 300., 330., 360., 390., 900.] } ) parrot = nest.Create('parrot_neuron') neuron = nest.Create("iaf_psc_exp", 2) # We must send spikes via parrot because devices cannot # connect through plastic synapses # See #478. nest.Connect(source, parrot) nest.Connect(parrot, neuron[:1], syn_spec="tsodyks2_synapse") nest.Connect(parrot, neuron[1:], syn_spec="quantal_stp_synapse") voltmeter = nest.Create("voltmeter", 2) nest.SetStatus(voltmeter, {"withgid": False, "withtime": True}) t_tot = 1500. # the following is a dry run trial so that the synapse dynamics is # idential in all subsequent trials. nest.Simulate(t_tot) # Now we connect the voltmeters nest.Connect([voltmeter[0]], [neuron[0]]) nest.Connect([voltmeter[1]], [neuron[1]]) for t in range(n_trials): t_net = nest.GetKernelStatus('time') nest.SetStatus(source, {'origin': t_net}) nest.Simulate(t_tot) nest.Simulate(.1) # flush the last voltmeter events from the queue vm = numpy.array(nest.GetStatus([voltmeter[1]], 'events')[0]['V_m']) vm_reference = numpy.array(nest.GetStatus( [voltmeter[0]], 'events')[0]['V_m']) assert(len(vm) % n_trials == 0) n_steps = int(len(vm) / n_trials) vm.shape = (n_trials, n_steps) vm_reference.shape = (n_trials, n_steps) vm_mean = numpy.mean(vm, axis=0) vm_ref_mean = numpy.mean(vm_reference, axis=0) error = numpy.sqrt((vm_ref_mean - vm_mean)**2) self.assertTrue(numpy.max(error) < 4.0e-4) def suite(): suite = unittest.makeSuite(QuantalSTPSynapseTestCase, 'test') return suite def run(): runner = unittest.TextTestRunner(verbosity=2) runner.run(suite()) if __name__ == "__main__": run()
gpl-2.0
ashokrajbathu/boabrock
frappe/model/delete_doc.py
12
7003
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import frappe import frappe.model.meta import frappe.defaults from frappe.utils.file_manager import remove_all from frappe import _ from rename_doc import dynamic_link_queries from frappe.model.naming import revert_series_if_last def delete_doc(doctype=None, name=None, force=0, ignore_doctypes=None, for_reload=False, ignore_permissions=False, flags=None, ignore_on_trash=False): """ Deletes a doc(dt, dn) and validates if it is not submitted and not linked in a live record """ if not ignore_doctypes: ignore_doctypes = [] # get from form if not doctype: doctype = frappe.form_dict.get('dt') name = frappe.form_dict.get('dn') names = name if isinstance(name, basestring): names = [name] for name in names or []: # already deleted..? if not frappe.db.exists(doctype, name): return # delete attachments remove_all(doctype, name) doc = None if doctype=="DocType": if for_reload: try: doc = frappe.get_doc(doctype, name) except frappe.DoesNotExistError: pass else: doc.run_method("before_reload") else: frappe.db.sql("delete from `tabCustom Field` where dt = %s", name) frappe.db.sql("delete from `tabCustom Script` where dt = %s", name) frappe.db.sql("delete from `tabProperty Setter` where doc_type = %s", name) frappe.db.sql("delete from `tabReport` where ref_doctype=%s", name) delete_from_table(doctype, name, ignore_doctypes, None) else: doc = frappe.get_doc(doctype, name) if not for_reload: if ignore_permissions: if not flags: flags = {} flags["ignore_permissions"] = ignore_permissions if flags: doc.flags.update(flags) check_permission_and_not_submitted(doc) if not ignore_on_trash: doc.run_method("on_trash") delete_linked_todos(doc) delete_linked_comments(doc) delete_linked_communications(doc) delete_shared(doc) # check if links exist if not force: check_if_doc_is_linked(doc) check_if_doc_is_dynamically_linked(doc) update_naming_series(doc) delete_from_table(doctype, name, ignore_doctypes, doc) if doc: try: insert_feed(doc) except ImportError: pass # delete user_permissions frappe.defaults.clear_default(parenttype="User Permission", key=doctype, value=name) def update_naming_series(doc): if doc.meta.autoname: if doc.meta.autoname.startswith("naming_series:") \ and getattr(doc, "naming_series", None): revert_series_if_last(doc.naming_series, doc.name) elif doc.meta.autoname.split(":")[0] not in ("Prompt", "field", "hash"): revert_series_if_last(doc.meta.autoname, doc.name) def delete_from_table(doctype, name, ignore_doctypes, doc): if doctype!="DocType" and doctype==name: frappe.db.sql("delete from `tabSingles` where doctype=%s", name) else: frappe.db.sql("delete from `tab%s` where name=%s" % (doctype, "%s"), (name,)) # get child tables if doc: tables = [d.options for d in doc.meta.get_table_fields()] else: def get_table_fields(field_doctype): return frappe.db.sql_list("""select options from `tab{}` where fieldtype='Table' and parent=%s""".format(field_doctype), doctype) tables = get_table_fields("DocField") if not frappe.flags.in_install=="frappe": tables += get_table_fields("Custom Field") # delete from child tables for t in list(set(tables)): if t not in ignore_doctypes: frappe.db.sql("delete from `tab%s` where parenttype=%s and parent = %s" % (t, '%s', '%s'), (doctype, name)) def check_permission_and_not_submitted(doc): # permission if frappe.session.user!="Administrator" and not doc.has_permission("delete"): frappe.msgprint(_("User not allowed to delete {0}: {1}").format(doc.doctype, doc.name), raise_exception=True) # check if submitted if doc.docstatus == 1: frappe.msgprint(_("{0} {1}: Submitted Record cannot be deleted.").format(doc.doctype, doc.name), raise_exception=True) def check_if_doc_is_linked(doc, method="Delete"): """ Raises excption if the given doc(dt, dn) is linked in another record. """ from frappe.model.rename_doc import get_link_fields link_fields = get_link_fields(doc.doctype) link_fields = [[lf['parent'], lf['fieldname'], lf['issingle']] for lf in link_fields] for link_dt, link_field, issingle in link_fields: if not issingle: item = frappe.db.get_value(link_dt, {link_field:doc.name}, ["name", "parent", "parenttype", "docstatus"], as_dict=True) if item and item.parent != doc.name and ((method=="Delete" and item.docstatus<2) or (method=="Cancel" and item.docstatus==1)): frappe.throw(_("Cannot delete or cancel because {0} {1} is linked with {2} {3}").format(doc.doctype, doc.name, item.parenttype if item.parent else link_dt, item.parent or item.name), frappe.LinkExistsError) def check_if_doc_is_dynamically_linked(doc): for query in dynamic_link_queries: for df in frappe.db.sql(query, as_dict=True): if frappe.get_meta(df.parent).issingle: # dynamic link in single doc refdoc = frappe.db.get_singles_dict(df.parent) if refdoc.get(df.options)==doc.doctype and refdoc.get(df.fieldname)==doc.name: frappe.throw(_("Cannot delete or cancel because {0} {1} is linked with {2} {3}").format(doc.doctype, doc.name, df.parent, ""), frappe.LinkExistsError) else: # dynamic link in table for name in frappe.db.sql_list("""select name from `tab{parent}` where {options}=%s and {fieldname}=%s""".format(**df), (doc.doctype, doc.name)): frappe.throw(_("Cannot delete or cancel because {0} {1} is linked with {2} {3}").format(doc.doctype, doc.name, df.parent, name), frappe.LinkExistsError) def delete_linked_todos(doc): delete_doc("ToDo", frappe.db.sql_list("""select name from `tabToDo` where reference_type=%s and reference_name=%s""", (doc.doctype, doc.name))) def delete_linked_comments(doc): """Delete comments from the document""" delete_doc("Comment", frappe.db.sql_list("""select name from `tabComment` where comment_doctype=%s and comment_docname=%s""", (doc.doctype, doc.name)), ignore_on_trash=True) def delete_linked_communications(doc): delete_doc("Communication", frappe.db.sql_list("""select name from `tabCommunication` where reference_doctype=%s and reference_name=%s""", (doc.doctype, doc.name))) def insert_feed(doc): from frappe.utils import get_fullname if frappe.flags.in_install or frappe.flags.in_import or getattr(doc, "no_feed_on_delete", False): return frappe.get_doc({ "doctype": "Feed", "feed_type": "Label", "doc_type": doc.doctype, "doc_name": doc.name, "subject": _("Deleted"), "full_name": get_fullname(doc.owner) }).insert(ignore_permissions=True) def delete_shared(doc): delete_doc("DocShare", frappe.db.sql_list("""select name from `tabDocShare` where share_doctype=%s and share_name=%s""", (doc.doctype, doc.name)), ignore_on_trash=True)
mit
IntegralDefense/integralutils
integralutils/WildfireParser.py
1
15599
import os import sys import requests import logging import sys import base64 # Make sure the current directory is in the # path so that we can run this from anywhere. this_dir = os.path.dirname(__file__) if this_dir not in sys.path: sys.path.insert(0, this_dir) from BaseSandboxParser import * class WildfireParser(BaseSandboxParser): def __init__(self, config, json_report_path, whitelister=None): # Run the super init to inherit attributes and load the config. super().__init__(config, json_report_path, whitelister=whitelister) # Try and load this report from cache. if not self.load_from_cache(): # Read some items the config file. self.sandbox_display_name = self.config["WildfireParser"]["sandbox_display_name"] # Fail if we can't parse the MD5. This is used as a sanity check when # figuring out which of the sandbox parsers you should use on your JSON. self.md5 = self.parse(self.report, "wildfire", "file_info", "md5") if not self.md5: self.logger.critical("Unable to parse Wildfire MD5 from: " + str(json_report_path)) return None self.logger.debug("Parsing Wildfire sample " + self.md5) # Most Wildfire values depend on this. self.reports_json = self.parse(self.report, "wildfire", "task_info", "report") # In case there was only a single report, make it a list anyway. if isinstance(self.reports_json, dict): self.reports_json = [self.reports_json] # Parse some basic info directly from the report. self.filename = "sample" self.sha1 = self.parse(self.report, "wildfire", "file_info", "sha1") self.sha256 = self.parse(self.report, "wildfire", "file_info", "sha256") # The rest of the info requires a bit more parsing. self.sandbox_url = self.parse_sandbox_url() self.contacted_hosts = self.parse_contacted_hosts() self.dropped_files = self.parse_dropped_files() self.http_requests = self.parse_http_requests() self.dns_requests = self.parse_dns_requests() self.process_tree = self.parse_process_tree() self.decoded_process_tree = self.decode_process_tree() self.process_tree_urls = self.parse_process_tree_urls() self.mutexes = self.parse_mutexes() #self.json_urls = self.parse_json_urls() self.all_urls = self.get_all_urls() # Extract the IOCs. self.extract_indicators() # Get rid of the JSON report to save space. self.report = None # Cache the report. self.save_to_cache() def __getstate__(self): d = dict(self.__dict__) if "logger" in d: del d["logger"] if "strings" in d: del d["strings"] if "whitelister" in d: del d["whitelister"] return d def __setstate__(self, d): self.__dict__.update(d) def parse_sandbox_url(self): if self.sha256: return "https://wildfire.paloaltonetworks.com/wildfire/reportlist?search=" + self.sha256 else: return "" def parse_http_requests(self): self.logger.debug("Parsing HTTP requests") # We use a set instead of a list since there are multiple Wildfire reports. # This prevents any duplicate requests being returned. http_requests = set() # Loop over each Wildfire report (usually should be 2). for report in self.reports_json: try: requests = report["network"]["url"] if isinstance(requests, dict): requests = [requests] for request in requests: r = HttpRequest() try: r.host = request["@host"] except KeyError: pass try: r.uri = request["@uri"] except KeyError: pass try: r.method = request["@method"] except KeyError: pass try: r.user_agent = request["@user_agent"] except KeyError: pass http_requests.add(r) except KeyError: pass except TypeError: pass return list(http_requests) def parse_dns_requests(self): self.logger.debug("Parsing DNS requests") # We use a set instead of a list since there are multiple Wildfire reports. # This prevents any duplicate requests being returned. dns_requests = set() # Loop over each Wildfire report (usually should be 2). for report in self.reports_json: try: requests = report["network"]["dns"] if isinstance(requests, dict): requests = [requests] for request in requests: r = DnsRequest() try: r.request = request["@query"] except KeyError: pass try: r.type = request["@type"] except KeyError: pass try: r.answer = request["@response"] except KeyError: pass try: r.user_agent = request["@user_agent"] except KeyError: pass dns_requests.add(r) except KeyError: pass except TypeError: pass return list(dns_requests) def parse_dropped_files(self): self.logger.debug("Parsing dropped files") # We use a set instead of a list since there are multiple Wildfire reports. # This prevents any duplicate requests being returned. dropped_files = set() # Loop over each Wildfire report (usually should be 2). for report in self.reports_json: try: process_list = report["process_list"]["process"] if isinstance(process_list, dict): process_list = [process_list] for process in process_list: try: created_files = process["file"]["Create"] if isinstance(created_files, dict): created_files = [created_files] for file in created_files: d = DroppedFile() try: d.filename = file["@name"].split("\\")[-1] except KeyError: pass try: d.type = file["@type"] except KeyError: pass try: d.path = file["@name"] except KeyError: pass try: d.size = file["@size"] except KeyError: pass try: d.md5 = file["@md5"] except KeyError: pass try: d.sha1 = file["@sha1"] except KeyError: pass try: d.sha256 = file["@sha256"] except KeyError: pass dropped_files.add(d) self.logger.debug("Adding dropped file: " + d.filename) except KeyError: pass except TypeError: pass except KeyError: pass except TypeError: pass return list(dropped_files) def parse_contacted_hosts(self): self.logger.debug("Parsing contacted hosts") # We use a set instead of a list since there are multiple Wildfire reports. # This prevents any duplicate hosts being returned. contacted_hosts = set() # Loop over each Wildfire report (usually should be 2). for report in self.reports_json: try: hosts = report["network"]["TCP"] if isinstance(hosts, dict): hosts = [hosts] for host in hosts: h = ContactedHost() try: h.ipv4 = host["@ip"] except KeyError: pass try: h.port = host["@port"] except KeyError: pass try: h.protocol = "TCP" except KeyError: pass try: h.location = host["@country"] except KeyError: pass contacted_hosts.add(h) except KeyError: pass except TypeError: pass try: hosts = report["network"]["UDP"] if isinstance(hosts, dict): hosts = [hosts] for host in hosts: h = ContactedHost() try: h.ipv4 = host["@ip"] except KeyError: pass try: h.port = host["@port"] except KeyError: pass try: h.protocol = "UDP" except KeyError: pass try: h.location = host["@country"] except KeyError: pass contacted_hosts.add(h) except KeyError: pass except TypeError: pass return list(contacted_hosts) def parse_process_tree_urls(self): self.logger.debug("Looking for URLs in process tree") urls = RegexHelpers.find_urls(str(self.parse_process_tree())) urls += RegexHelpers.find_urls(self.decode_process_tree()) return urls def parse_process_tree(self): self.logger.debug("Parsing process tree") def walk_tree(process_json=None, process_list=None, previous_pid=0): if not process_list: process_list = ProcessList() if isinstance(process_json, dict): process_json = [process_json] if process_json: for process in process_json: command = process["@text"] pid = process["@pid"] parent_pid = previous_pid new_process = Process(command, pid, parent_pid) process_list.add_process(new_process) try: process_list = walk_tree(process["child"]["process"], process_list, pid) except KeyError: pass except TypeError: pass return process_list process_tree_to_use = None process_tree_to_use_size = 0 for report in self.reports_json: try: process_tree = report["process_tree"]["process"] process_tree_size = len(str(process_tree)) if process_tree_size > process_tree_to_use_size: process_tree_to_use = process_tree process_tree_to_use_size = process_tree_size except KeyError: pass except TypeError: pass return walk_tree(process_json=process_tree_to_use) def decode_process_tree(self): process_tree = str(self.parse_process_tree()) decoded_process_tree = process_tree # Try to decode base64 chunks. for chunk in process_tree.split(): try: decoded_chunk = base64.b64decode(chunk).decode('utf-8') if '\x00' in decoded_chunk: decoded_chunk = base64.b64decode(chunk).decode('utf-16') decoded_process_tree = decoded_process_tree.replace(chunk, decoded_chunk) except: pass # Try to decode int arrays. try: int_array_regex = re.compile(r"\(((\s*\d+\s*,?)+)\)") matches = int_array_regex.findall(decoded_process_tree) for match in matches: orig_int_array = match[0] clean_int_array = ''.join(orig_int_array.split()).split(',') chars = ''.join([chr(int(num)) for num in clean_int_array]) decoded_process_tree = decoded_process_tree.replace(orig_int_array, chars) except: pass # Try to decode split+int arrays. try: split_int_array_regex = re.compile(r"\(\s*'((\s*\d+.)+)\s*'") matches = split_int_array_regex.findall(decoded_process_tree) for match in matches: orig_int_array = match[0] int_regex = re.compile(r"\d+") int_array = int_regex.findall(orig_int_array) chars = ''.join([chr(int(num)) for num in int_array]) decoded_process_tree = decoded_process_tree.replace(orig_int_array, chars) except: pass if decoded_process_tree != process_tree: return decoded_process_tree else: return '' def parse_mutexes(self): self.logger.debug("Parsing mutexes") # We use a set instead of a list since there are multiple Wildfire reports. # This prevents any duplicate mutexes being returned. mutexes = set() # Loop over each Wildfire report (usually should be 2). for report in self.reports_json: try: process_list = report["process_list"]["process"] if isinstance(process_list, dict): process_list = [process_list] for process in process_list: try: mutexes_created = process["mutex"]["CreateMutex"] if isinstance(mutexes_created, dict): mutexes_created = [mutexes_created] for mutex in mutexes_created: if mutex["@name"] != "<NULL>": mutexes.add(mutex["@name"]) except KeyError: pass except TypeError: pass except KeyError: pass except TypeError: pass return sorted(list(mutexes))
apache-2.0
andymason/istheansweryes
lib/werkzeug/contrib/jsrouting.py
318
8534
# -*- coding: utf-8 -*- """ werkzeug.contrib.jsrouting ~~~~~~~~~~~~~~~~~~~~~~~~~~ Addon module that allows to create a JavaScript function from a map that generates rules. :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ try: from simplejson import dumps except ImportError: try: from json import dumps except ImportError: def dumps(*args): raise RuntimeError('simplejson required for jsrouting') from inspect import getmro from werkzeug.routing import NumberConverter from werkzeug._compat import iteritems def render_template(name_parts, rules, converters): result = u'' if name_parts: for idx in xrange(0, len(name_parts) - 1): name = u'.'.join(name_parts[:idx + 1]) result += u"if (typeof %s === 'undefined') %s = {}\n" % (name, name) result += '%s = ' % '.'.join(name_parts) result += """(function (server_name, script_name, subdomain, url_scheme) { var converters = %(converters)s; var rules = $rules; function in_array(array, value) { if (array.indexOf != undefined) { return array.indexOf(value) != -1; } for (var i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } function array_diff(array1, array2) { array1 = array1.slice(); for (var i = array1.length-1; i >= 0; i--) { if (in_array(array2, array1[i])) { array1.splice(i, 1); } } return array1; } function split_obj(obj) { var names = []; var values = []; for (var name in obj) { if (typeof(obj[name]) != 'function') { names.push(name); values.push(obj[name]); } } return {names: names, values: values, original: obj}; } function suitable(rule, args) { var default_args = split_obj(rule.defaults || {}); var diff_arg_names = array_diff(rule.arguments, default_args.names); for (var i = 0; i < diff_arg_names.length; i++) { if (!in_array(args.names, diff_arg_names[i])) { return false; } } if (array_diff(rule.arguments, args.names).length == 0) { if (rule.defaults == null) { return true; } for (var i = 0; i < default_args.names.length; i++) { var key = default_args.names[i]; var value = default_args.values[i]; if (value != args.original[key]) { return false; } } } return true; } function build(rule, args) { var tmp = []; var processed = rule.arguments.slice(); for (var i = 0; i < rule.trace.length; i++) { var part = rule.trace[i]; if (part.is_dynamic) { var converter = converters[rule.converters[part.data]]; var data = converter(args.original[part.data]); if (data == null) { return null; } tmp.push(data); processed.push(part.name); } else { tmp.push(part.data); } } tmp = tmp.join(''); var pipe = tmp.indexOf('|'); var subdomain = tmp.substring(0, pipe); var url = tmp.substring(pipe+1); var unprocessed = array_diff(args.names, processed); var first_query_var = true; for (var i = 0; i < unprocessed.length; i++) { if (first_query_var) { url += '?'; } else { url += '&'; } first_query_var = false; url += encodeURIComponent(unprocessed[i]); url += '='; url += encodeURIComponent(args.original[unprocessed[i]]); } return {subdomain: subdomain, path: url}; } function lstrip(s, c) { while (s && s.substring(0, 1) == c) { s = s.substring(1); } return s; } function rstrip(s, c) { while (s && s.substring(s.length-1, s.length) == c) { s = s.substring(0, s.length-1); } return s; } return function(endpoint, args, force_external) { args = split_obj(args); var rv = null; for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (rule.endpoint != endpoint) continue; if (suitable(rule, args)) { rv = build(rule, args); if (rv != null) { break; } } } if (rv == null) { return null; } if (!force_external && rv.subdomain == subdomain) { return rstrip(script_name, '/') + '/' + lstrip(rv.path, '/'); } else { return url_scheme + '://' + (rv.subdomain ? rv.subdomain + '.' : '') + server_name + rstrip(script_name, '/') + '/' + lstrip(rv.path, '/'); } }; })""" % {'converters': u', '.join(converters)} return result def generate_map(map, name='url_map'): """ Generates a JavaScript function containing the rules defined in this map, to be used with a MapAdapter's generate_javascript method. If you don't pass a name the returned JavaScript code is an expression that returns a function. Otherwise it's a standalone script that assigns the function with that name. Dotted names are resolved (so you an use a name like 'obj.url_for') In order to use JavaScript generation, simplejson must be installed. Note that using this feature will expose the rules defined in your map to users. If your rules contain sensitive information, don't use JavaScript generation! """ from warnings import warn warn(DeprecationWarning('This module is deprecated')) map.update() rules = [] converters = [] for rule in map.iter_rules(): trace = [{ 'is_dynamic': is_dynamic, 'data': data } for is_dynamic, data in rule._trace] rule_converters = {} for key, converter in iteritems(rule._converters): js_func = js_to_url_function(converter) try: index = converters.index(js_func) except ValueError: converters.append(js_func) index = len(converters) - 1 rule_converters[key] = index rules.append({ u'endpoint': rule.endpoint, u'arguments': list(rule.arguments), u'converters': rule_converters, u'trace': trace, u'defaults': rule.defaults }) return render_template(name_parts=name and name.split('.') or [], rules=dumps(rules), converters=converters) def generate_adapter(adapter, name='url_for', map_name='url_map'): """Generates the url building function for a map.""" values = { u'server_name': dumps(adapter.server_name), u'script_name': dumps(adapter.script_name), u'subdomain': dumps(adapter.subdomain), u'url_scheme': dumps(adapter.url_scheme), u'name': name, u'map_name': map_name } return u'''\ var %(name)s = %(map_name)s( %(server_name)s, %(script_name)s, %(subdomain)s, %(url_scheme)s );''' % values def js_to_url_function(converter): """Get the JavaScript converter function from a rule.""" if hasattr(converter, 'js_to_url_function'): data = converter.js_to_url_function() else: for cls in getmro(type(converter)): if cls in js_to_url_functions: data = js_to_url_functions[cls](converter) break else: return 'encodeURIComponent' return '(function(value) { %s })' % data def NumberConverter_js_to_url(conv): if conv.fixed_digits: return u'''\ var result = value.toString(); while (result.length < %s) result = '0' + result; return result;''' % conv.fixed_digits return u'return value.toString();' js_to_url_functions = { NumberConverter: NumberConverter_js_to_url }
apache-2.0
rooshilp/CMPUT410W15-project
testenv/lib/python2.7/site-packages/PIL/ImageDraw2.py
26
3199
# # The Python Imaging Library # $Id$ # # WCK-style drawing interface operations # # History: # 2003-12-07 fl created # 2005-05-15 fl updated; added to PIL as ImageDraw2 # 2005-05-15 fl added text support # 2005-05-20 fl added arc/chord/pieslice support # # Copyright (c) 2003-2005 by Secret Labs AB # Copyright (c) 2003-2005 by Fredrik Lundh # # See the README file for information on usage and redistribution. # from PIL import Image, ImageColor, ImageDraw, ImageFont, ImagePath class Pen: def __init__(self, color, width=1, opacity=255): self.color = ImageColor.getrgb(color) self.width = width class Brush: def __init__(self, color, opacity=255): self.color = ImageColor.getrgb(color) class Font: def __init__(self, color, file, size=12): # FIXME: add support for bitmap fonts self.color = ImageColor.getrgb(color) self.font = ImageFont.truetype(file, size) class Draw: def __init__(self, image, size=None, color=None): if not hasattr(image, "im"): image = Image.new(image, size, color) self.draw = ImageDraw.Draw(image) self.image = image self.transform = None def flush(self): return self.image def render(self, op, xy, pen, brush=None): # handle color arguments outline = fill = None width = 1 if isinstance(pen, Pen): outline = pen.color width = pen.width elif isinstance(brush, Pen): outline = brush.color width = brush.width if isinstance(brush, Brush): fill = brush.color elif isinstance(pen, Brush): fill = pen.color # handle transformation if self.transform: xy = ImagePath.Path(xy) xy.transform(self.transform) # render the item if op == "line": self.draw.line(xy, fill=outline, width=width) else: getattr(self.draw, op)(xy, fill=fill, outline=outline) def settransform(self, offset): (xoffset, yoffset) = offset self.transform = (1, 0, xoffset, 0, 1, yoffset) def arc(self, xy, start, end, *options): self.render("arc", xy, start, end, *options) def chord(self, xy, start, end, *options): self.render("chord", xy, start, end, *options) def ellipse(self, xy, *options): self.render("ellipse", xy, *options) def line(self, xy, *options): self.render("line", xy, *options) def pieslice(self, xy, start, end, *options): self.render("pieslice", xy, start, end, *options) def polygon(self, xy, *options): self.render("polygon", xy, *options) def rectangle(self, xy, *options): self.render("rectangle", xy, *options) def symbol(self, xy, symbol, *options): raise NotImplementedError("not in this version") def text(self, xy, text, font): if self.transform: xy = ImagePath.Path(xy) xy.transform(self.transform) self.draw.text(xy, text, font=font.font, fill=font.color) def textsize(self, text, font): return self.draw.textsize(text, font=font.font)
gpl-2.0
Evervolv/android_external_chromium_org
tools/idl_parser/idl_ppapi_lexer.py
23
1872
#!/usr/bin/env python # Copyright (c) 2013 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. """ Lexer for PPAPI IDL The lexer uses the PLY library to build a tokenizer which understands both WebIDL and Pepper tokens. WebIDL, and WebIDL regular expressions can be found at: http://www.w3.org/TR/2012/CR-WebIDL-20120419/ PLY can be found at: http://www.dabeaz.com/ply/ """ from idl_lexer import IDLLexer import optparse import os.path import sys # # IDL PPAPI Lexer # class IDLPPAPILexer(IDLLexer): # Special multi-character operators def t_LSHIFT(self, t): r'<<' return t; def t_RSHIFT(self, t): r'>>' return t; def t_INLINE(self, t): r'\#inline (.|\n)*?\#endinl.*' self.AddLines(t.value.count('\n')) return t # Return a "preprocessor" inline block def __init__(self): IDLLexer.__init__(self) self._AddTokens(['INLINE', 'LSHIFT', 'RSHIFT']) self._AddKeywords(['label', 'struct']) # Add number types self._AddKeywords(['char', 'int8_t', 'int16_t', 'int32_t', 'int64_t']); self._AddKeywords(['uint8_t', 'uint16_t', 'uint32_t', 'uint64_t']); self._AddKeywords(['double_t', 'float_t']); # Add handle types self._AddKeywords(['handle_t', 'PP_FileHandle']); # Add pointer types (void*, char*, const char*, const void*) self._AddKeywords(['mem_t', 'str_t', 'cstr_t', 'interface_t']); # Remove JS types self._DelKeywords(['boolean', 'byte', 'Date', 'DOMString', 'double', 'float', 'long', 'object', 'octet', 'short', 'unsigned']) # If run by itself, attempt to build the lexer if __name__ == '__main__': lexer = IDLPPAPILexer() lexer.Tokenize(open('test_parser/inline_ppapi.idl').read()) for tok in lexer.GetTokens(): print '\n' + str(tok)
bsd-3-clause
keithlee/shakeAppPyDev
django/contrib/gis/gdal/prototypes/generation.py
321
3766
""" This module contains functions that generate ctypes prototypes for the GDAL routines. """ from ctypes import c_char_p, c_double, c_int, c_void_p from django.contrib.gis.gdal.prototypes.errcheck import \ check_arg_errcode, check_errcode, check_geom, check_geom_offset, \ check_pointer, check_srs, check_str_arg, check_string, check_const_string class gdal_char_p(c_char_p): pass def double_output(func, argtypes, errcheck=False, strarg=False): "Generates a ctypes function that returns a double value." func.argtypes = argtypes func.restype = c_double if errcheck: func.errcheck = check_arg_errcode if strarg: func.errcheck = check_str_arg return func def geom_output(func, argtypes, offset=None): """ Generates a function that returns a Geometry either by reference or directly (if the return_geom keyword is set to True). """ # Setting the argument types func.argtypes = argtypes if not offset: # When a geometry pointer is directly returned. func.restype = c_void_p func.errcheck = check_geom else: # Error code returned, geometry is returned by-reference. func.restype = c_int def geomerrcheck(result, func, cargs): return check_geom_offset(result, func, cargs, offset) func.errcheck = geomerrcheck return func def int_output(func, argtypes): "Generates a ctypes function that returns an integer value." func.argtypes = argtypes func.restype = c_int return func def srs_output(func, argtypes): """ Generates a ctypes prototype for the given function with the given C arguments that returns a pointer to an OGR Spatial Reference System. """ func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_srs return func def const_string_output(func, argtypes, offset=None): func.argtypes = argtypes if offset: func.restype = c_int else: func.restype = c_char_p def _check_const(result, func, cargs): return check_const_string(result, func, cargs, offset=offset) func.errcheck = _check_const return func def string_output(func, argtypes, offset=-1, str_result=False): """ Generates a ctypes prototype for the given function with the given argument types that returns a string from a GDAL pointer. The `const` flag indicates whether the allocated pointer should be freed via the GDAL library routine VSIFree -- but only applies only when `str_result` is True. """ func.argtypes = argtypes if str_result: # Use subclass of c_char_p so the error checking routine # can free the memory at the pointer's address. func.restype = gdal_char_p else: # Error code is returned func.restype = c_int # Dynamically defining our error-checking function with the # given offset. def _check_str(result, func, cargs): return check_string(result, func, cargs, offset=offset, str_result=str_result) func.errcheck = _check_str return func def void_output(func, argtypes, errcheck=True): """ For functions that don't only return an error code that needs to be examined. """ if argtypes: func.argtypes = argtypes if errcheck: # `errcheck` keyword may be set to False for routines that # return void, rather than a status code. func.restype = c_int func.errcheck = check_errcode else: func.restype = None return func def voidptr_output(func, argtypes): "For functions that return c_void_p." func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_pointer return func
bsd-3-clause
wholebiome/MetaPathways_Python_Koonkie.3.0
libs/python_modules/utils/metapathways_utils.py
2
34426
#!/usr/bin/env python __author__ = "Kishori M Konwar" __copyright__ = "Copyright 2013, MetaPathways" __credits__ = ["r"] __version__ = "1.0" __maintainer__ = "Kishori M Konwar" __status__ = "Release" """Contains general utility code for the metapaths project""" from shutil import rmtree from StringIO import StringIO from os import getenv, makedirs, _exit from operator import itemgetter from os.path import split, splitext, abspath, exists, dirname, join, isdir from collections import defaultdict from optparse import make_option from datetime import datetime from optparse import OptionParser import sys, os, traceback, math, re, time from libs.python_modules.utils.utils import * from libs.python_modules.utils.errorcodes import error_message, get_error_list, insert_error def halt_process(secs=4, verbose =False): time.sleep(secs) errors=get_error_list() if len(errors)>1: insert_error(200) if verbose: for errorcode in errors.keys(): eprintf("ERROR:\t%d\t%s\n",errorcode, errors[errorcode]) if len(errors.keys())>1: errorcode = 200 _exit(errorcode) elif len(errors.keys())==1: errorcode = errors.keys()[0] _exit(errorcode) _exit(0) def exit_process(message = None, delay = 0, logger = None): if message != None: eprintf("ERROR\t%s", message+ "\n") eprintf('ERROR\tExiting the Python code\n') if logger: logger.printf('ERROR\tExiting the Python code\n') logger.printf('ERROR\t' + message + '\n') time.sleep(delay) _exit(0) def exit_step(message = None): if message != None: eprintf("%s", message+ "\n") eprintf("INFO: Exiting the Python code\n") eprintf("ERROR\t" + str(traceback.format_exc(10)) + "\n") time.sleep(4) _exit(0) def getShortORFId(orfname) : #return orfname orfNameRegEx = re.compile(r'(\d+_\d+)$') pos = orfNameRegEx.search(orfname) shortORFname = "" if pos: shortORFname = pos.group(1) return shortORFname def getShortContigId(contigname): contigNameRegEx = re.compile(r'(\d+)$') shortContigname = "" pos = contigNameRegEx.search(contigname) if pos: shortContigname = pos.group(1) return shortContigname def ContigID(contigname): contigNameRegEx = re.compile(r'^(\S+_\d+)_\d+$') shortContigname = "" pos = contigNameRegEx.search(contigname) if pos: shortContigname = pos.group(1) return shortContigname def getSampleNameFromContig(contigname): contigNameRegEx = re.compile(r'(.*)_(\d+)$') sampleName = "" pos = contigNameRegEx.search(contigname) if pos: sampleName = pos.group(1) return sampleName def strip_taxonomy(product): func = re.sub(r'\[[^\[\]]+\]', '', product) return func def getSamFiles(readdir, sample_name): '''This function finds the set of fastq files that has the reads''' samFiles = [] _samFiles = glob(readdir + PATHDELIM + sample_name + '.sam') if _samFiles: samFiles = _samFiles return samFiles def getReadFiles(readdir, sample_name): '''This function finds the set of fastq files that has the reads''' fastqFiles = [] _fastqfiles = glob(readdir + PATHDELIM + sample_name + '*.[fF][aA][Ss][Tt][qQ]') fastqfiles =[] for _f in _fastqfiles: f = re.sub(r'^.*[//]','', _f) fastqfiles.append(f) readfiles = [] samPATT=re.compile(sample_name+".fastq") samPATT1=re.compile(sample_name+"[.]b\d+.fastq") samPATT2=re.compile(sample_name+"_[1-2].fastq") samPATT3=re.compile(sample_name+"_r[1-2].fastq") samPATT4=re.compile(sample_name+"_[1-2][.](b\d+).fastq") batch = {} for f in fastqfiles: res = samPATT.search(f) if res: readfiles.append( [readdir + PATHDELIM +f] ) continue res = samPATT1.search(f) if res: readfiles.append( [readdir + PATHDELIM +f] ) continue res = samPATT2.search(f) if res: readfiles.append( [readdir + PATHDELIM +f] ) continue res = samPATT3.search(f) if res: if not 'r' in batch: batch['r'] = [] batch['r'].append( readdir + PATHDELIM +f ) continue res = samPATT4.search(f) if res: if not res.group(1) in batch: batch[res.group(1)] = [] batch[res.group(1)].append( readdir + PATHDELIM +f ) continue eprintf("ERROR\tPossible error in read file naming \"%s\". Ignoring for now!\n", f) for values in batch.values(): readfiles.append(values) return readfiles def deprecated____getReadFiles(readdir, sample_name): '''This function finds the set of fastq files that has the reads''' fastqFiles = [] _fastqfiles = glob(readdir + PATHDELIM + sample_name + '_[12].[fF][aA][Ss][Tt][qQ]') if _fastqfiles: fastqFiles = _fastqfiles _fastqfiles = glob(readdir + PATHDELIM + sample_name + '_[12].[fF][qQ]') if _fastqfiles: fastqFiles = _fastqfiles _fastqfiles = glob(readdir + PATHDELIM + sample_name + '.[fF][aA][Ss][Tt][qQ]') if _fastqfiles: fastqFiles = _fastqfiles _fastqfiles = glob(readdir + PATHDELIM + sample_name + '.[fF][qQ]') if _fastqfiles: fastqFiles = _fastqfiles return fastqFiles class GffFileParser(object): def __init__(self, gff_filename): self.Size = 10000 self.i=0 self.orf_dictionary = {} self.gff_beg_pattern = re.compile("^#") self.lines= [] self.size=0 try: self.gff_file = open( gff_filename,'r') except AttributeError: print "Cannot read the map file for database :" + dbname sys.exit(0) def __iter__(self): return self def refillBuffer(self): self.orf_dictionary = {} i = 0 while i < self.Size: line=self.gff_file.readline() if not line: break if self.gff_beg_pattern.search(line): continue self.insert_orf_into_dict(line, self.orf_dictionary) i += 1 self.orfs = self.orf_dictionary.keys() self.size = len(self.orfs) self.i = 0 def next(self): if self.i == self.size: self.refillBuffer() if self.size==0: self.gff_file.close() raise StopIteration() #print self.i if self.i < self.size: self.i = self.i + 1 return self.orfs[self.i-1] def insert_orf_into_dict(self, line, contig_dict): rawfields = re.split('\t', line) fields = [] for field in rawfields: fields.append(field.strip()); if( len(fields) != 9): return attributes = {} attributes['seqname'] = fields[0] # this is a bit of a duplication attributes['source'] = fields[1] attributes['feature'] = fields[2] attributes['start'] = int(fields[3]) attributes['end'] = int(fields[4]) try: attributes['score'] = float(fields[5]) except: attributes['score'] = fields[5] attributes['strand'] = fields[6] attributes['frame'] = fields[7] self.split_attributes(fields[8], attributes) if not fields[0] in contig_dict : contig_dict[fields[0]] = [] contig_dict[fields[0]].append(attributes) def insert_attribute(self, attributes, attribStr): rawfields = re.split('=', attribStr) if len(rawfields) == 2: attributes[rawfields[0].strip().lower()] = rawfields[1].strip() def split_attributes(self, str, attributes): rawattributes = re.split(';', str) for attribStr in rawattributes: self.insert_attribute(attributes, attribStr) return attributes class Performance: def __init__(self): self.sum = {} self.sqsum = {} self.num = {} def getAverageDelay(self, server= None): if server==None: avg = 0 num = 0 for server in self.sum: avg += self.sum[server] num += self.num[server] if num > 0: return avg/num else: return 0 if self.num[server]==0: return 0 avg = self.sum[server]/self.num[server] return avg def getStdDeviationDelay(self, server= None): if server==None: avg = 0 avgsq = 0 num = 0 for server in self.sum: avg += self.sum[server] avgsq += self.sqsum[server] num += self.num[server] if num == 0: return 0 var = avgsq/num - avg*avg/(num*num) std = math.sqrt(var) return std def addPerformanceData(self, server, data): if not server in self.sum: self.sum[server] = 0 self.sqsum[server] = 0 self.num[server] = 0 self.sum[server] += data self.sqsum[server] += data*data self.num[server] += 1 return True def getExpectedDelay(self): return 20 class Job: def __init__(self, S, d, a, m, server=None): self.S = S # sample self.d = d # database self.a = a # split self.m = m # algorithm self.server = None # server return None def setValues(self, S, d, a, m, t, server=None): self.S = S self.d = d self.a = a self.m = m self.submission_time = t self.server=server return True def parse_command_line_parameters(script_info, argv): print script_info print argv opts = [] return opts class TreeMissingError(IOError): """Exception for missing tree file""" pass class OtuMissingError(IOError): """Exception for missing OTU file""" pass class AlignmentMissingError(IOError): """Exception for missing alignment file""" pass class MissingFileError(IOError): pass def make_safe_f(f, allowed_params): """Make version of f that ignores extra named params.""" def inner(*args, **kwargs): if kwargs: new_kwargs = {} for k, v in kwargs.items(): if k in allowed_params: new_kwargs[k] = v return f(*args, **new_kwargs) return f(*args, **kwargs) return inner class FunctionWithParams(object): """A FunctionWithParams is a replacement for the function factory. Specifically, the params that will be used in the __call__ method are available in a dict so you can keep track of them with the object itself. """ Application = None Algorithm = None Citation = None Params = {} Name = 'FunctionWithParams' #override in subclasses _tracked_properties = [] #properties tracked like params def __init__(self, params): """Return new FunctionWithParams object with specified params. Note: expect params to contain both generic and per-method (e.g. for cdhit) params, so leaving it as a dict rather than setting attributes. Some standard entries in params are: [fill in on a per-application basis] """ self.Params.update(params) self._tracked_properties.extend(['Application','Algorithm','Citation']) def __str__(self): """Returns formatted key-value pairs from params.""" res = [self.Name + ' parameters:'] for t in self._tracked_properties: res.append(t + ':' + str(getattr(self, t))) for k, v in sorted(self.Params.items()): res.append(str(k) + ':' + str(v)) return '\n'.join(res) def writeLog(self, log_path): """Writes self.Params and other relevant info to supplied path.""" f=open(log_path, 'w') f.write(str(self)) f.close() def getResult(self, *args, **kwargs): """Gets result in __call__. Override in subclasses.""" return None def formatResult(self, result): """Formats result as string (for whatever "result" means).""" return str(result) def writeResult(self, result_path, result): """Writes result to result_path. May need to format in subclasses.""" f = open(result_path, 'w') f.write(self.formatResult(result)) f.close() def getOtuTable(self, otu_source): """Returns parsed OTU table from putative OTU source.""" #if we have a string starting with #, assume it's an OTU file, #otherwise assume it's a path # if 4-tuple, just return it if type(otu_source) == type((1,3,4,44)): return otu_source if hasattr(otu_source, 'startswith') and otu_source.startswith('#'): try: return parse_otu_table(StringIO(otu_source)) except (TypeError, ValueError), e: raise OtuMissingError, \ "Tried to read OTUs from string starting with # but got "+e else: try: otu_file = open(otu_source, 'U') except (TypeError, IOError): raise OtuMissingError, \ "Couldn't read OTU file at path: %s" % otu_source result = parse_otu_table(otu_file) otu_file.close() return result def getTree(self, tree_source): """Returns parsed tree from putative tree source""" if isinstance(tree_source, PhyloNode): tree = tree_source #accept tree object directly for tests elif tree_source: try: f = open(tree_source, 'U') except (TypeError, IOError): raise TreeMissingError, \ "Couldn't read tree file at path: %s" % tree_source tree = parse_newick(f, PhyloNode) f.close() else: raise TreeMissingError, str(self.Name) + \ " is a phylogenetic metric, but no tree was supplied." return tree def getData(self, data_source): """Returns data from putative source, which could be a path""" if isinstance(data_source, str): try: return eval(data_source) except (NameError, SyntaxError): try: data_f = open(data_source, 'U') data = data_f.read() data_f.close() try: return eval(data) except (NameError, SyntaxError, TypeError): pass return data except (IOError, NameError, TypeError): pass #if we got here, either we didn't get a string or we couldn't read #the data source into any other kind of object return data_source def getAlignment(self, aln_source): """Returns parsed alignment from putative alignment source""" if isinstance(aln_source, Alignment): aln = aln_source elif aln_source: try: aln = LoadSeqs(aln_source, Aligned=True) except (TypeError, IOError, AssertionError): raise AlignmentMissingError, \ "Couldn't read alignment file at path: %s" % aln_source else: raise AlignmentMissingError, str(self.Name) + \ " requires an alignment, but no alignment was supplied." return aln def __call__ (self, result_path=None, log_path=None,\ *args, **kwargs): """Returns the result of calling the function using the params dict. Parameters: [fill in on a per-application basis] """ print """Function with parameters""" result = self.getResult(*args, **kwargs) if log_path: self.writeLog(log_path) if result_path: self.writeResult(result_path, result) else: return result def get_qiime_project_dir(): """ Returns the top-level QIIME directory """ # Get the full path of util.py current_file_path = abspath(__file__) # Get the directory containing util.py current_dir_path = dirname(current_file_path) # Return the directory containing the directory containing util.py return dirname(current_dir_path) def get_qiime_scripts_dir(): """ Returns the QIIME scripts directory This value must be stored in qiime_config if the user has installed qiime using setup.py. If it is not in qiime_config, it is inferred from the qiime_project_dir. """ qiime_config = load_qiime_config() qiime_config_value = qiime_config['qiime_scripts_dir'] if qiime_config_value != None: result = qiime_config_value else: result = join(get_qiime_project_dir(),'scripts') #assert exists(result),\ # "qiime_scripts_dir does not exist: %s." % result +\ # " Have you defined it correctly in your qiime_config?" return result def load_qiime_config(): """Return default parameters read in from file""" qiime_config_filepaths = [] qiime_project_dir = get_qiime_project_dir() qiime_config_filepaths.append(\ qiime_project_dir + '/qiime/support_files/qiime_config') qiime_config_env_filepath = getenv('QIIME_CONFIG_FP') if qiime_config_env_filepath: qiime_config_filepaths.append(qiime_config_env_filepath) home_dir = getenv('HOME') if home_dir: qiime_config_home_filepath = home_dir + '/.qiime_config' qiime_config_filepaths.append(qiime_config_home_filepath) qiime_config_files = [] for qiime_config_filepath in qiime_config_filepaths: if exists(qiime_config_filepath): qiime_config_files.append(open(qiime_config_filepath)) return parse_qiime_config_files(qiime_config_files) # The qiime_blast_seqs function should evetually move to PyCogent, # but I want to test that it works for all of the QIIME functionality that # I need first. -Greg def extract_seqs_by_sample_id(seqs, sample_ids, negate=False): """ Returns (seq id, seq) pairs if sample_id is in sample_ids """ sample_ids = {}.fromkeys(sample_ids) if not negate: def f(s): return s in sample_ids else: def f(s): return s not in sample_ids for seq_id, seq in seqs: sample_id = seq_id.split('_')[0] if f(sample_id): yield seq_id, seq def split_fasta_on_sample_ids(seqs): """ yields (sample_id, seq_id, seq) for each entry in seqs seqs: (seq_id,seq) pairs, as generated by MinimalFastaParser """ for seq_id, seq in seqs: yield (seq_id.split()[0].rsplit('_',1)[0], seq_id, seq) return def split_fasta_on_sample_ids_to_dict(seqs): """ return split_fasta_on_sample_ids as {sample_id: [(seq_id, seq), ], } seqs: (seq_id,seq) pairs, as generated by MinimalFastaParser """ result = {} for sample_id,seq_id,seq in split_fasta_on_sample_ids(seqs): try: result[sample_id].append((seq_id,seq)) except KeyError: result[sample_id] = [(seq_id,seq)] return result def split_fasta_on_sample_ids_to_files(seqs,output_dir): """ output of split_fasta_on_sample_ids to fasta in specified output_dir seqs: (seq_id,seq) pairs, as generated by MinimalFastaParser output_dir: string defining directory where output should be written, will be created if it doesn't exist """ create_dir(output_dir) file_lookup = {} for sample_id,seq_id,seq in split_fasta_on_sample_ids(seqs): try: file_lookup[sample_id].write('>%s\n%s\n' % (seq_id,seq)) except KeyError: file_lookup[sample_id] = open('%s/%s.fasta' % (output_dir,sample_id),'w') file_lookup[sample_id].write('>%s\n%s\n' % (seq_id,seq)) for file_handle in file_lookup.values(): file_handle.close() return None def raise_error_on_parallel_unavailable(qiime_config=None): """Raise error if no parallel QIIME bc user hasn't set jobs_to_start """ if qiime_config == None: qiime_config = load_qiime_config() if 'jobs_to_start' not in qiime_config or \ int(qiime_config['jobs_to_start']) < 2: raise RuntimeError,\ "Parallel QIIME is not available. (Have you set"+\ " jobs_to_start to greater than 1 in your qiime_config?" def matrix_stats(headers_list, distmats): """does, mean, median, stdev on a series of (dis)similarity matrices takes a series of parsed matrices (list of headers, list of numpy 2d arrays) headers must are either row or colunm headers (those must be identical) outputs headers (list), means, medians, stdevs (all numpy 2d arrays) """ if len(set(map(tuple,headers_list))) > 1: raise ValueError("error, not all input matrices have"+\ " identical column/row headers") all_mats = numpy.array(distmats) # 3d numpy array: mtx, row, col means = numpy.mean(all_mats, axis=0) medians = numpy.median(all_mats, axis=0) stdevs = numpy.std(all_mats, axis=0) return deepcopy(headers_list[0]), means, medians, stdevs def _flip_vectors(jn_matrix, m_matrix): """transforms PCA vectors so that signs are correct""" m_matrix_trans = m_matrix.transpose() jn_matrix_trans = jn_matrix.transpose() new_matrix= zeros(jn_matrix_trans.shape, float) for i, m_vector in enumerate(m_matrix_trans): jn_vector = jn_matrix_trans[i] disT = list(m_vector - jn_vector) disT = sum(map(abs, disT)) jn_flip = jn_vector*[-1] disF = list(m_vector - jn_flip) disF = sum(map(abs, disF)) if disT > disF: new_matrix[i] = jn_flip else: new_matrix[i] = jn_vector return new_matrix.transpose() def IQR(x): """calculates the interquartile range of x x can be a list or an array returns min_val and max_val of the IQR""" x.sort() #split values into lower and upper portions at the median odd = len(x) % 2 midpoint = int(len(x)/2) if odd: low_vals = x[:midpoint] high_vals = x[midpoint+1:] else: #if even low_vals = x[:midpoint] high_vals = x[midpoint:] #find the median of the low and high values min_val = median(low_vals) max_val = median(high_vals) return min_val, max_val def matrix_IQR(x): """calculates the IQR for each column in an array """ num_cols = x.shape[1] min_vals = zeros(num_cols) max_vals = zeros(num_cols) for i in range(x.shape[1]): col = x[:, i] min_vals[i], max_vals[i] = IQR(col) return min_vals, max_vals def idealfourths(data, axis=None): """This function returns an estimate of the lower and upper quartiles of the data along the given axis, as computed with the ideal fourths. This function was taken from scipy.stats.mstat_extra.py (http://projects.scipy.org/scipy/browser/trunk/scipy/stats/mstats_extras.py?rev=6392) """ def _idf(data): x = data.compressed() n = len(x) if n < 3: return [numpy.nan,numpy.nan] (j,h) = divmod(n/4. + 5/12.,1) qlo = (1-h)*x[j-1] + h*x[j] k = n - j qup = (1-h)*x[k] + h*x[k-1] return [qlo, qup] data = numpy.sort(data, axis=axis).view(MaskedArray) if (axis is None): return _idf(data) else: return apply_along_axis(_idf, axis, data) def isarray(a): """ This function tests whether an object is an array """ try: validity=isinstance(a,ndarray) except: validity=False return validity def degap_fasta_aln(seqs): """degap a Fasta aligment. seqs: list of label,seq pairs """ for (label,seq) in seqs: degapped_seq = Sequence(moltype=DNA_with_more_gaps, seq=seq, name=label).degap() degapped_seq.Name = label yield degapped_seq def write_degapped_fasta_to_file(seqs, tmp_dir="/tmp/"): """ write degapped seqs to temp fasta file.""" tmp_filename = get_tmp_filename(tmp_dir=tmp_dir, prefix="degapped_", suffix=".fasta") fh = open(tmp_filename,"w") for seq in degap_fasta_aln(seqs): fh.write(seq.toFasta()+"\n") fh.close() return tmp_filename # remove the string "/pathway-tools" to infer the pathway tools dir def create_pathway_tools_dir_path_From_executable(pathway_tools_executable): return( pathway_tools_executable.replace('pathway-tools/pathway-tools', 'pathway-tools')) #removes an existing pgdb from the ptools-local/pgdbs/user directory under the #pathway tools directory def remove_existing_pgdb( sample_name, pathway_tools_exec): suffix_to_remove = "" # crete the pathway tools dir pathway_tools_dir = create_pathway_tools_dir_path_From_executable(pathway_tools_exec) sample_pgdb_dir = pathway_tools_dir + "/" + "ptools-local/pgdbs/user/" + sample_name + "cyc" if os.path.exists(sample_pgdb_dir): return rmtree(sample_pgdb_dir) def generate_log_fp(output_dir, basefile_name='', suffix='txt', timestamp_pattern=''): filename = '%s.%s' % (basefile_name,suffix) return join(output_dir,filename) class WorkflowError(Exception): pass def contract_key_value_file(fileName): file = open(fileName,'r') lines = file.readlines() if len(lines) < 20: file.close() return keyValuePairs = {} for line in lines: fields = [ x.strip() for x in line.split('\t') ] if len(fields) == 2: keyValuePairs[fields[0]] = fields[1] file.close() file = open(fileName,'w') for key, value in keyValuePairs.iteritems(): fprintf(file, "%s\t%s\n",key, value) file.close() class FastaRecord(object): def __init__(self, name, sequence): self.name = name self.sequence = sequence # return FastaRecord(title, sequence) def read_fasta_records(input_file): records = [] sequence="" while 1: line = input_file.readline() if line == "": if sequence!="" and name!="": records.append(FastaRecord(name, sequence)) return records if line=='\n': continue line = line.rstrip() if line.startswith(">") : if sequence!="" and name!="": records.append(FastaRecord(name, sequence)) name = line.rstrip() sequence ="" else: sequence = sequence + line.rstrip() return records class WorkflowLogger(object): def __init__(self,log_fp=None,params=None,metapaths_config=None,open_mode='w'): if log_fp: self._filename = log_fp #contract the file if we have to if open_mode=='c': try: contract_key_value_file(log_fp) except: pass open_mode='a' self._f = open(self._filename, open_mode) self._f.close() else: self._f = None #start_time = datetime.now().strftime('%H:%M:%S on %d %b %Y') self.writemetapathsConfig(metapaths_config) self.writeParams(params) def get_log_filename(self): return self._filename def printf(self, fmt, *args): self._f = open(self._filename,'a') if self._f: self._f.write(fmt % args) self._f.flush() else: pass self._f.close() def write(self, s): self._f = open(self._filename,'a') if self._f: self._f.write(s) # Flush here so users can see what step they're # on after each write, since some steps can take # a long time, and a relatively small amount of # data is being written to the log files. self._f.flush() else: pass self._f.close() def writemetapathsConfig(self,metapaths_config): if metapaths_config == None: #self.write('#No metapaths config provided.\n') pass else: self.write('#metapaths_config values:\n') for k,v in metapaths_config.items(): if v: self.write('%s\t%s\n' % (k,v)) self.write('\n') def writeParams(self,params): if params == None: #self.write('#No params provided.\n') pass else: self.write('#parameter file values:\n') for k,v in params.items(): for inner_k,inner_v in v.items(): val = inner_v or 'True' self.write('%s:%s\t%s\n' % (k,inner_k,val)) self.write('\n') def close(self): end_time = datetime.now().strftime('%H:%M:%S on %d %b %Y') self.write('\nLogging stopped at %s\n' % end_time) if self._f: self._f.close() else: pass def ShortenORFId(_orfname, RNA=False) : ORFIdPATT = re.compile("(\\d+_\\d+)$") RNAPATT = re.compile("(\\d+_\\d+_[tr]RNA)$") if RNA: result = RNAPATT.search(_orfname) else: result = ORFIdPATT.search(_orfname) if result: shortORFname = result.group(1) else: return "" return shortORFname def ShortentRNAId(_orfname) : ORFIdPATT = re.compile("(\\d+_\\d+_tRNA)$") result = ORFIdPATT.search(_orfname) if result: shortORFname = result.group(1) else: return "" return shortORFname def ShortenrRNAId(_orfname) : ORFIdPATT = re.compile("(\\d+_\\d+_rRNA)$") result = ORFIdPATT.search(_orfname) if result: shortORFname = result.group(1) else: return "" return shortORFname def ShortenContigId(_contigname) : ContigIdPATT = re.compile("(\\d+)$") result = ContigIdPATT.search(_contigname) if result: shortContigname = result.group(1) else: return "" return shortContigname def create_metapaths_parameters(filename, folder): """ creates a parameters file from the default """ default_filename = folder + PATHDELIM + 'resources'+ PATHDELIM + "template_param.txt" try: filep = open(default_filename, 'r') except: eprintf("ERROR: cannot open the default parameter file " + sQuote(default_filename) ) exit_process("ERROR: cannot open the default parameter file " + sQuote(default_filename), errorCode = 0 ) lines = filep.readlines() with open(filename, 'w') as newfile: for line in lines: fprintf(newfile, "%s", line); filep.close() #result['filename'] = filename return True def touch(fname, times=None): with open(fname, 'a'): os.utime(fname, times) def create_metapaths_configuration(filename, folder): """ creates a cofiguration file from the default """ variablePATT = re.compile(r'<([a-zA-Z0-9_]*)>') default_filename = folder + PATHDELIM + 'resources'+ PATHDELIM + "template_config.txt" try: filep = open(default_filename, 'r') except: eprintf("ERROR: cannot open the default config file " + sQuote(default_filename) ) exit_process("ERROR: cannot open the default config file " + sQuote(default_filename), errorCode = 0 ) setVariables = {} lines = filep.readlines() with open(filename, 'w') as newfile: for line in lines: line = line.strip() result = variablePATT.search(line) if result: VARIABLE=result.group(1) CONFIG_VARIABLE =[ x for x in line.split(' ') if x.strip() ][0] if VARIABLE in setVariables: line =line.replace( '<'+ VARIABLE + '>', setVariables[VARIABLE]) elif VARIABLE in os.environ: line =line.replace( '<'+ VARIABLE + '>', os.environ[VARIABLE]) else: default ="" if VARIABLE=='METAPATHWAYS_PATH': default = folder + PATHDELIM if VARIABLE=='METAPATHWAYS_DB': if 'METAPATHWAYS_PATH' in os.environ: default = os.environ['METAPATHWAYS_PATH'] + PATHDELIM + 'databases/' else: eprintf("%-10s:\tSet required environment variable METAPATHWAYS_DB as 'export METAPATHWAYS_DB=<path>'\n" %('INFO')) if VARIABLE=='PTOOLS_DIR': if 'METAPATHWAYS_PATH' in os.environ: default = os.environ['METAPATHWAYS_PATH'] + PATHDELIM + '/regtests' target = default + PATHDELIM + 'pathway-tools' print target if not os.path.exists(target): print 'create' os.mkdir(target) target = target + PATHDELIM + 'pathway-tools' if not os.path.exists(target): touch(target) print CONFIG_VARIABLE else: eprintf("%-10%:\tSet shell essential variable PTOOLS_DIR as 'export PTOOLS_DIR=<path>'\n" %('INFO') ) setVariables[VARIABLE]= default line = line.replace('<' + VARIABLE + '>', default) print line eprintf("INFO: Setting default value for \"%s\" as \"%s\"\n" %( CONFIG_VARIABLE, line)) eprintf(" To set other values :\n") eprintf(" 1. remove file \"%s\"\n" %(filename)) eprintf(" 2. set the shell variable \"%s\"\n" %(VARIABLE)) eprintf(" 3. rerun command\n") fprintf(newfile, "%s\n", line); filep.close() #result['filename'] = filename return True
mit
Tithen-Firion/youtube-dl
youtube_dl/extractor/ccc.py
50
2839
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( int_or_none, parse_iso8601, ) class CCCIE(InfoExtractor): IE_NAME = 'media.ccc.de' _VALID_URL = r'https?://(?:www\.)?media\.ccc\.de/v/(?P<id>[^/?#&]+)' _TESTS = [{ 'url': 'https://media.ccc.de/v/30C3_-_5443_-_en_-_saal_g_-_201312281830_-_introduction_to_processor_design_-_byterazor#video', 'md5': '3a1eda8f3a29515d27f5adb967d7e740', 'info_dict': { 'id': '1839', 'ext': 'mp4', 'title': 'Introduction to Processor Design', 'description': 'md5:df55f6d073d4ceae55aae6f2fd98a0ac', 'thumbnail': r're:^https?://.*\.jpg$', 'upload_date': '20131228', 'timestamp': 1388188800, 'duration': 3710, } }, { 'url': 'https://media.ccc.de/v/32c3-7368-shopshifting#download', 'only_matching': True, }] def _real_extract(self, url): display_id = self._match_id(url) webpage = self._download_webpage(url, display_id) event_id = self._search_regex(r"data-id='(\d+)'", webpage, 'event id') event_data = self._download_json('https://media.ccc.de/public/events/%s' % event_id, event_id) formats = [] for recording in event_data.get('recordings', []): recording_url = recording.get('recording_url') if not recording_url: continue language = recording.get('language') folder = recording.get('folder') format_id = None if language: format_id = language if folder: if language: format_id += '-' + folder else: format_id = folder vcodec = 'h264' if 'h264' in folder else ( 'none' if folder in ('mp3', 'opus') else None ) formats.append({ 'format_id': format_id, 'url': recording_url, 'width': int_or_none(recording.get('width')), 'height': int_or_none(recording.get('height')), 'filesize': int_or_none(recording.get('size'), invscale=1024 * 1024), 'language': language, 'vcodec': vcodec, }) self._sort_formats(formats) return { 'id': event_id, 'display_id': display_id, 'title': event_data['title'], 'description': event_data.get('description'), 'thumbnail': event_data.get('thumb_url'), 'timestamp': parse_iso8601(event_data.get('date')), 'duration': int_or_none(event_data.get('length')), 'tags': event_data.get('tags'), 'formats': formats, }
unlicense
prhod/navitia
source/jormungandr/jormungandr/timezone.py
11
2283
# encoding: utf-8 # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility and open public transport: # a non ending quest to the responsive locomotion way of traveling! # # LICENCE: 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/>. # # Stay tuned using # twitter @navitia # IRC #navitia on freenode # https://groups.google.com/d/forum/navitia # www.navitia.io import logging import pytz from flask import g from jormungandr.exceptions import TechnicalError, RegionNotFound from jormungandr import i_manager def set_request_timezone(region): logger = logging.getLogger(__name__) instance = i_manager.instances.get(region, None) if not instance: raise RegionNotFound(region) if not instance.timezone: logger.warn("region {} has no timezone".format(region)) g.timezone = None return tz = pytz.timezone(instance.timezone) if not tz: logger.warn("impossible to find timezone: '{}' for region {}".format(instance.timezone, region)) g.timezone = tz def get_timezone(): """ return the time zone associated with the query Note: for the moment ONLY ONE time zone is used for a region (a kraken instances) It is this default timezone that is returned in this method """ if not hasattr(g, 'timezone'): raise TechnicalError("No timezone set for this API") # the set_request_timezone has to be called at init return g.timezone
agpl-3.0
archf/ansible
lib/ansible/modules/storage/infinidat/infini_host.py
29
3823
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Gregory Shulov (gregory.shulov@gmail.com) # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: infini_host version_added: 2.3 short_description: Create, Delete and Modify Hosts on Infinibox description: - This module creates, deletes or modifies hosts on Infinibox. author: Gregory Shulov (@GR360RY) options: name: description: - Host Name required: true state: description: - Creates/Modifies Host when present or removes when absent required: false default: present choices: [ "present", "absent" ] wwns: description: - List of wwns of the host required: false volume: description: - Volume name to map to the host required: false extends_documentation_fragment: - infinibox ''' EXAMPLES = ''' - name: Create new new host infini_host: name: foo.example.com user: admin password: secret system: ibox001 - name: Make sure host bar is available with wwn ports infini_host: name: bar.example.com wwns: - "00:00:00:00:00:00:00" - "11:11:11:11:11:11:11" system: ibox01 user: admin password: secret - name: Map host foo.example.com to volume bar infini_host: name: foo.example.com volume: bar system: ibox01 user: admin password: secret ''' RETURN = ''' ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.infinibox import HAS_INFINISDK, api_wrapper, get_system, infinibox_argument_spec @api_wrapper def get_host(module, system): host = None for h in system.hosts.to_list(): if h.get_name() == module.params['name']: host = h break return host @api_wrapper def create_host(module, system): changed = True if not module.check_mode: host = system.hosts.create(name=module.params['name']) if module.params['wwns']: for p in module.params['wwns']: host.add_fc_port(p) if module.params['volume']: host.map_volume(system.volumes.get(name=module.params['volume'])) module.exit_json(changed=changed) @api_wrapper def update_host(module, host): changed = False module.exit_json(changed=changed) @api_wrapper def delete_host(module, host): changed = True if not module.check_mode: host.delete() module.exit_json(changed=changed) def main(): argument_spec = infinibox_argument_spec() argument_spec.update( dict( name = dict(required=True), state = dict(default='present', choices=['present', 'absent']), wwns = dict(type='list'), volume = dict() ) ) module = AnsibleModule(argument_spec, supports_check_mode=True) if not HAS_INFINISDK: module.fail_json(msg='infinisdk is required for this module') state = module.params['state'] system = get_system(module) host = get_host(module, system) if module.params['volume']: try: system.volumes.get(name=module.params['volume']) except: module.fail_json(msg='Volume {} not found'.format(module.params['volume'])) if host and state == 'present': update_host(module, host) elif host and state == 'absent': delete_host(module, host) elif host is None and state == 'absent': module.exit_json(changed=False) else: create_host(module, system) if __name__ == '__main__': main()
gpl-3.0
esvitech/linux-2
scripts/gdb/linux/proc.py
189
8604
# # gdb helper commands and functions for Linux kernel debugging # # Kernel proc information reader # # Copyright (c) 2016 Linaro Ltd # # Authors: # Kieran Bingham <kieran.bingham@linaro.org> # # This work is licensed under the terms of the GNU GPL version 2. # import gdb from linux import constants from linux import utils from linux import tasks from linux import lists from struct import * class LxCmdLine(gdb.Command): """ Report the Linux Commandline used in the current kernel. Equivalent to cat /proc/cmdline on a running target""" def __init__(self): super(LxCmdLine, self).__init__("lx-cmdline", gdb.COMMAND_DATA) def invoke(self, arg, from_tty): gdb.write(gdb.parse_and_eval("saved_command_line").string() + "\n") LxCmdLine() class LxVersion(gdb.Command): """ Report the Linux Version of the current kernel. Equivalent to cat /proc/version on a running target""" def __init__(self): super(LxVersion, self).__init__("lx-version", gdb.COMMAND_DATA) def invoke(self, arg, from_tty): # linux_banner should contain a newline gdb.write(gdb.parse_and_eval("linux_banner").string()) LxVersion() # Resource Structure Printers # /proc/iomem # /proc/ioports def get_resources(resource, depth): while resource: yield resource, depth child = resource['child'] if child: for res, deep in get_resources(child, depth + 1): yield res, deep resource = resource['sibling'] def show_lx_resources(resource_str): resource = gdb.parse_and_eval(resource_str) width = 4 if resource['end'] < 0x10000 else 8 # Iterate straight to the first child for res, depth in get_resources(resource['child'], 0): start = int(res['start']) end = int(res['end']) gdb.write(" " * depth * 2 + "{0:0{1}x}-".format(start, width) + "{0:0{1}x} : ".format(end, width) + res['name'].string() + "\n") class LxIOMem(gdb.Command): """Identify the IO memory resource locations defined by the kernel Equivalent to cat /proc/iomem on a running target""" def __init__(self): super(LxIOMem, self).__init__("lx-iomem", gdb.COMMAND_DATA) def invoke(self, arg, from_tty): return show_lx_resources("iomem_resource") LxIOMem() class LxIOPorts(gdb.Command): """Identify the IO port resource locations defined by the kernel Equivalent to cat /proc/ioports on a running target""" def __init__(self): super(LxIOPorts, self).__init__("lx-ioports", gdb.COMMAND_DATA) def invoke(self, arg, from_tty): return show_lx_resources("ioport_resource") LxIOPorts() # Mount namespace viewer # /proc/mounts def info_opts(lst, opt): opts = "" for key, string in lst.items(): if opt & key: opts += string return opts FS_INFO = {constants.LX_MS_SYNCHRONOUS: ",sync", constants.LX_MS_MANDLOCK: ",mand", constants.LX_MS_DIRSYNC: ",dirsync", constants.LX_MS_NOATIME: ",noatime", constants.LX_MS_NODIRATIME: ",nodiratime"} MNT_INFO = {constants.LX_MNT_NOSUID: ",nosuid", constants.LX_MNT_NODEV: ",nodev", constants.LX_MNT_NOEXEC: ",noexec", constants.LX_MNT_NOATIME: ",noatime", constants.LX_MNT_NODIRATIME: ",nodiratime", constants.LX_MNT_RELATIME: ",relatime"} mount_type = utils.CachedType("struct mount") mount_ptr_type = mount_type.get_type().pointer() class LxMounts(gdb.Command): """Report the VFS mounts of the current process namespace. Equivalent to cat /proc/mounts on a running target An integer value can be supplied to display the mount values of that process namespace""" def __init__(self): super(LxMounts, self).__init__("lx-mounts", gdb.COMMAND_DATA) # Equivalent to proc_namespace.c:show_vfsmnt # However, that has the ability to call into s_op functions # whereas we cannot and must make do with the information we can obtain. def invoke(self, arg, from_tty): argv = gdb.string_to_argv(arg) if len(argv) >= 1: try: pid = int(argv[0]) except: raise gdb.GdbError("Provide a PID as integer value") else: pid = 1 task = tasks.get_task_by_pid(pid) if not task: raise gdb.GdbError("Couldn't find a process with PID {}" .format(pid)) namespace = task['nsproxy']['mnt_ns'] if not namespace: raise gdb.GdbError("No namespace for current process") for vfs in lists.list_for_each_entry(namespace['list'], mount_ptr_type, "mnt_list"): devname = vfs['mnt_devname'].string() devname = devname if devname else "none" pathname = "" parent = vfs while True: mntpoint = parent['mnt_mountpoint'] pathname = utils.dentry_name(mntpoint) + pathname if (parent == parent['mnt_parent']): break parent = parent['mnt_parent'] if (pathname == ""): pathname = "/" superblock = vfs['mnt']['mnt_sb'] fstype = superblock['s_type']['name'].string() s_flags = int(superblock['s_flags']) m_flags = int(vfs['mnt']['mnt_flags']) rd = "ro" if (s_flags & constants.LX_MS_RDONLY) else "rw" gdb.write( "{} {} {} {}{}{} 0 0\n" .format(devname, pathname, fstype, rd, info_opts(FS_INFO, s_flags), info_opts(MNT_INFO, m_flags))) LxMounts() class LxFdtDump(gdb.Command): """Output Flattened Device Tree header and dump FDT blob to the filename specified as the command argument. Equivalent to 'cat /proc/fdt > fdtdump.dtb' on a running target""" def __init__(self): super(LxFdtDump, self).__init__("lx-fdtdump", gdb.COMMAND_DATA, gdb.COMPLETE_FILENAME) def fdthdr_to_cpu(self, fdt_header): fdt_header_be = ">IIIIIII" fdt_header_le = "<IIIIIII" if utils.get_target_endianness() == 1: output_fmt = fdt_header_le else: output_fmt = fdt_header_be return unpack(output_fmt, pack(fdt_header_be, fdt_header['magic'], fdt_header['totalsize'], fdt_header['off_dt_struct'], fdt_header['off_dt_strings'], fdt_header['off_mem_rsvmap'], fdt_header['version'], fdt_header['last_comp_version'])) def invoke(self, arg, from_tty): if not constants.LX_CONFIG_OF: raise gdb.GdbError("Kernel not compiled with CONFIG_OF\n") if len(arg) == 0: filename = "fdtdump.dtb" else: filename = arg py_fdt_header_ptr = gdb.parse_and_eval( "(const struct fdt_header *) initial_boot_params") py_fdt_header = py_fdt_header_ptr.dereference() fdt_header = self.fdthdr_to_cpu(py_fdt_header) if fdt_header[0] != constants.LX_OF_DT_HEADER: raise gdb.GdbError("No flattened device tree magic found\n") gdb.write("fdt_magic: 0x{:02X}\n".format(fdt_header[0])) gdb.write("fdt_totalsize: 0x{:02X}\n".format(fdt_header[1])) gdb.write("off_dt_struct: 0x{:02X}\n".format(fdt_header[2])) gdb.write("off_dt_strings: 0x{:02X}\n".format(fdt_header[3])) gdb.write("off_mem_rsvmap: 0x{:02X}\n".format(fdt_header[4])) gdb.write("version: {}\n".format(fdt_header[5])) gdb.write("last_comp_version: {}\n".format(fdt_header[6])) inf = gdb.inferiors()[0] fdt_buf = utils.read_memoryview(inf, py_fdt_header_ptr, fdt_header[1]).tobytes() try: f = open(filename, 'wb') except: raise gdb.GdbError("Could not open file to dump fdt") f.write(fdt_buf) f.close() gdb.write("Dumped fdt blob to " + filename + "\n") LxFdtDump()
gpl-2.0
google-research/remixmatch
pi_model.py
1
4872
# Copyright 2019 Google LLC # # 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 # # https://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. """Temporal Ensembling for Semi-Supervised Learning. Pi-model reimplementation of https://arxiv.org/abs/1610.02242 """ import functools import os import tensorflow as tf from absl import app from absl import flags from libml import models, utils from libml.data import PAIR_DATASETS from libml.utils import EasyDict FLAGS = flags.FLAGS class PiModel(models.MultiModel): def model(self, batch, lr, wd, ema, warmup_pos, consistency_weight, **kwargs): hwc = [self.dataset.height, self.dataset.width, self.dataset.colors] xt_in = tf.placeholder(tf.float32, [batch] + hwc, 'xt') # For training x_in = tf.placeholder(tf.float32, [None] + hwc, 'x') y_in = tf.placeholder(tf.float32, [batch, 2] + hwc, 'y') l_in = tf.placeholder(tf.int32, [batch], 'labels') l = tf.one_hot(l_in, self.nclass) wd *= lr warmup = tf.clip_by_value(tf.to_float(self.step) / (warmup_pos * (FLAGS.train_kimg << 10)), 0, 1) classifier = lambda x, **kw: self.classifier(x, **kw, **kwargs).logits logits_x = classifier(xt_in, training=True) post_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) # Take only first call to update batch norm. y = tf.reshape(tf.transpose(y_in, [1, 0, 2, 3, 4]), [-1] + hwc) y_1, y_2 = tf.split(y, 2) logits_y = classifier(y_1, training=True) logits_teacher = tf.stop_gradient(logits_y) logits_student = classifier(y_2, training=True) loss_pm = tf.reduce_mean((tf.nn.softmax(logits_teacher) - tf.nn.softmax(logits_student)) ** 2, -1) loss_pm = tf.reduce_mean(loss_pm) loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=l, logits=logits_x) loss = tf.reduce_mean(loss) tf.summary.scalar('losses/xe', loss) tf.summary.scalar('losses/pm', loss_pm) ema = tf.train.ExponentialMovingAverage(decay=ema) ema_op = ema.apply(utils.model_vars()) ema_getter = functools.partial(utils.getter_ema, ema) post_ops.append(ema_op) post_ops.extend([tf.assign(v, v * (1 - wd)) for v in utils.model_vars('classify') if 'kernel' in v.name]) train_op = tf.train.AdamOptimizer(lr).minimize(loss + loss_pm * warmup * consistency_weight, colocate_gradients_with_ops=True) with tf.control_dependencies([train_op]): train_op = tf.group(*post_ops) return EasyDict( xt=xt_in, x=x_in, y=y_in, label=l_in, train_op=train_op, classify_raw=tf.nn.softmax(classifier(x_in, training=False)), # No EMA, for debugging. classify_op=tf.nn.softmax(classifier(x_in, getter=ema_getter, training=False))) def main(argv): utils.setup_main() del argv # Unused. dataset = PAIR_DATASETS()[FLAGS.dataset]() log_width = utils.ilog2(dataset.width) model = PiModel( os.path.join(FLAGS.train_dir, dataset.name), dataset, lr=FLAGS.lr, wd=FLAGS.wd, arch=FLAGS.arch, warmup_pos=FLAGS.warmup_pos, batch=FLAGS.batch, nclass=dataset.nclass, ema=FLAGS.ema, smoothing=FLAGS.smoothing, consistency_weight=FLAGS.consistency_weight, scales=FLAGS.scales or (log_width - 2), filters=FLAGS.filters, repeat=FLAGS.repeat) model.train(FLAGS.train_kimg << 10, FLAGS.report_kimg << 10) if __name__ == '__main__': utils.setup_tf() flags.DEFINE_float('consistency_weight', 10., 'Consistency weight.') flags.DEFINE_float('warmup_pos', 0.4, 'Relative position at which constraint loss warmup ends.') flags.DEFINE_float('wd', 0.02, 'Weight decay.') flags.DEFINE_float('ema', 0.999, 'Exponential moving average of params.') flags.DEFINE_float('smoothing', 0.1, 'Label smoothing.') flags.DEFINE_integer('scales', 0, 'Number of 2x2 downscalings in the classifier.') flags.DEFINE_integer('filters', 32, 'Filter size of convolutions.') flags.DEFINE_integer('repeat', 4, 'Number of residual layers per stage.') FLAGS.set_default('augment', 'd.d.d') FLAGS.set_default('dataset', 'cifar10.3@250-5000') FLAGS.set_default('batch', 64) FLAGS.set_default('lr', 0.002) FLAGS.set_default('train_kimg', 1 << 16) app.run(main)
apache-2.0
altenia/taskmator
taskmator/context.py
1
5235
import datetime import re import logging from taskmator.factory import TaskFactory class TaskContainer: """ In this context a Task is an instance of a task loaded in memory. The task template is called task specification. """ logger = logging.getLogger(__name__) def __init__(self, task_ast): """ Constructor @type task_ast: dict abstract syntax tree that represents a task specification """ self.task_ast = task_ast self.task_root = None self.task_factory = TaskFactory() # Load the root task self.task_root = self.task_factory.instantiate('core.Composite', 'root', None) if (self.task_ast): self.task_factory.load(self.task_root, self.task_ast) def get_task_spec(self, name_path): """ Returns the task specification which is a pointer to an internal node in the AST @type name_path :array of names starting with root. E.g.: ['root', 'name1', ..] """ # names represent the namespace hierarchy node = self.task_ast for name in name_path: if (name in node): node = node[name] else: raise Exception('Nonexistent task with name [' + '.'.join(name_path) + '].') return (name_path[len(name_path) - 1], node) def get_root(self): return self.task_root def get_task(self, task_fqn): """ Returns the task given its fully qualified name. Instantiates tasks if not found but exists in the spec. @type task_fqn: basestring """ name_path = task_fqn.split('.') if (len(name_path) == 1 and name_path[0] == u'root'): return self.task_root # traverse starting from the root's child name_path = name_path[1:] task_node = self.task_root for name in name_path: if (task_node.hasChild(name)): task_node = task_node.getChild(name) else: # Cache lookup failed, create one based on the AST task_name, task_spec = self.get_task_spec(name_path) #task = self.instantiate_task(task_name, task_spec, task_node) task = self.task_factory.create(task_name, task_spec, task_node) return task_node def iteritems(self): """ Return iteritems @PENDING """ pass # Private methods def _get_fq_typename(self, task, typeName): """ Lookups the typeName form the alias and return the fully qualified type name """ currTask = task # get the closest alias matching the typeName while currTask: aliases = currTask.aliases if (aliases): if (typeName in aliases): return aliases[typeName] currTask = currTask.parent #print ("%%-chk alias-a:" + str(currTask)) # Fall back to the original typeName return typeName class ExecutionContext: logger = logging.getLogger(__name__) def __init__(self, task_container): self.exec_start_time = None self.exec_stop_time = None self.task_container = task_container self.execution_trace = [] def mark_start(self): self.exec_start_time = datetime.datetime.now() def mark_stop(self): """ Mark this context as terminated """ self.exec_stop_time = datetime.datetime.now() def get_task_container(self): """ Returns the task container @rtype: TaskContainer """ return self.task_container def lookup_task(self, task_fqn): return self.task_container.get_task(task_fqn) def register_trace(self, task_ref, context_path, start_time, end_time, exit_code, output): """ Registers a task execution trace @param context_path -- the task call context path (e.g: root/test/) remember this may differ from namespace because of branching """ trace_entry = { "task_ref": task_ref, "context_path": context_path, "start_time": start_time, "end_time": end_time, "exit_code": exit_code, "output": output } self.execution_trace.append(trace_entry) def traces(self, namePattern=None, exit_code=None): """ Returns a list of tasks that matches specified criteria @param namePattern -- the name pattern to search @param exit_code -- the task state """ result = [] for trace_entry in self.execution_trace: match = True if (exit_code): if (trace_entry['exit_code'] == exit_code): match = True if (match): try: match = True if namePattern is None else (re.search(namePattern, trace_entry['context_path']) is not None) except: self.logger.warn("Error on pattern: " + namePattern) if (match): result.append(trace_entry) return result
mit
google/rekall
rekall-core/rekall/plugins/windows/malware/cmdhistory.py
1
40811
# Rekall Memory Forensics # # Copyright 2013 Google Inc. All Rights Reserved. # # Authors: # Michael Hale Ligh <michael.ligh@mnin.org> # # Contributors/References: # Richard Stevens and Eoghan Casey # Extracting Windows Cmd Line Details from Physical Memory. # http://ww.dfrws.org/2010/proceedings/stevens.pdf # Michael Cohen <scudette@gmail.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. # # 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # pylint: disable=protected-access from builtins import bytes from rekall import obj from rekall.plugins.overlays import basic from rekall.plugins.windows import common from rekall.plugins.windows import vadinfo from rekall.plugins.overlays.windows import pe_vtypes from rekall_lib import utils MAX_HISTORY_DEFAULT = 50 HISTORY_BUFFERS_DEFAULTS = 4 # The following all use these standard types. common_types = { '_LIST_ENTRY' : [0x8, { 'Flink' : [0x0, ['pointer', ['_LIST_ENTRY']]], 'Blink' : [0x4, ['pointer', ['_LIST_ENTRY']]], }]} common_types_64 = { '_LIST_ENTRY' : [0x10, { 'Flink' : [0x0, ['pointer', ['_LIST_ENTRY']]], 'Blink' : [0x8, ['pointer', ['_LIST_ENTRY']]], }]} # Windows 7 Types from conhost.exe conhost_types_x86 = { '_COMMAND': [None, { 'CmdLength': [0x00, ['unsigned short']], 'Cmd' : [0x02, ['UnicodeString', dict( encoding='utf16', length=lambda x: x.CmdLength )]], }], '_COMMAND_HISTORY': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'Flags' : [0x08, ['Flags', dict( bitmap={ 'Allocated': 0, 'Reset': 1 } )]], 'Application': [0x0C, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=256 ) )]], 'CommandCount': [0x10, ['short']], 'LastAdded': [0x12, ['short']], 'LastDisplayed': [0x14, ['short']], 'FirstCommand': [0x16, ['short']], 'CommandCountMax': [0x18, ['short']], 'ProcessHandle': [0x1C, ['unsigned int']], 'PopupList': [0x20, ['_LIST_ENTRY']], 'CommandBucket': [0x28, ['Array', dict( count=lambda x: x.CommandCount, target='Pointer', target_args=dict( target='_COMMAND' ) )]], }], '_ALIAS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'SourceLength': [0x08, ['unsigned short']], 'TargetLength': [0x0A, ['unsigned short']], 'Source': [0x0C, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=lambda x: x.SourceLength * 2 ) )]], 'Target': [0x10, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=lambda x: x.TargetLength * 2 ) )]], }], '_EXE_ALIAS_LIST' : [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ExeLength': [0x08, ['unsigned short']], 'ExeName': [0x0C, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=lambda x: x.ExeLength * 2 ) )]], 'AliasList': [0x10, ['_LIST_ENTRY']], }], '_POPUP_LIST' : [None, { 'ListEntry' : [0x00, ['_LIST_ENTRY']], }], '_CONSOLE_INFORMATION': [None, { 'CurrentScreenBuffer': [0x98, ['pointer', ['_SCREEN_INFORMATION']]], 'ScreenBuffer': [0x9C, ['pointer', ['_SCREEN_INFORMATION']]], 'HistoryList': [0xD4, ['_LIST_ENTRY']], 'ProcessList': [0x18, ['_LIST_ENTRY']], # SrvGetConsoleProcessList() 'ExeAliasList': [0xDC, ['_LIST_ENTRY']], # GetConsoleAliasExes() # GetConsoleHistoryInfo() 'HistoryBufferCount': [0xE4, ['unsigned short']], # GetConsoleHistoryInfo() 'HistoryBufferMax': [0xE6, ['unsigned short']], 'CommandHistorySize': [0xE8, ['unsigned short']], 'OriginalTitle': [0xEC, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=256 ) )]], # GetConsoleOriginalTitle() 'Title': [0xF0, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=256 ) )]], # GetConsoleTitle() }], '_CONSOLE_PROCESS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ProcessHandle': [0x8, ['unsigned int']], }], '_SCREEN_INFORMATION': [None, { 'ScreenX': [0x08, ['short']], 'ScreenY': [0x0A, ['short']], 'Rows': [0x3C, ['Pointer', dict( target='Array', target_args=dict( count=lambda x: x.ScreenY, target='_ROW' ) )]], 'Next': [0xDC, ['Pointer', dict(target='_SCREEN_INFORMATION')]], }], '_ROW': [0x1C, { 'Chars': [0x08, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=lambda x: x.obj_parent.ScreenX * 2, ) )]], }], } # Windows 7 Types from conhost.exe conhost_types_x64 = { '_COMMAND': [None, { 'CmdLength': [0x00, ['unsigned short']], 'Cmd' : [0x02, ['UnicodeString', dict( encoding='utf16', length=lambda x: x.CmdLength)]], }], '_COMMAND_HISTORY': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], # AllocateCommandHistory() 'Flags' : [0x10, ['Flags', {'bitmap': {'Allocated': 0, 'Reset': 1}}]], # AllocateCommandHistory() 'Application': [0x18, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=256 ) )]], 'CommandCount': [0x20, ['short']], 'LastAdded': [0x22, ['short']], 'LastDisplayed': [0x24, ['short']], 'FirstCommand': [0x26, ['short']], 'CommandCountMax': [0x28, ['short']], # AllocateCommandHistory() 'ProcessHandle': [0x30, ['address']], # AllocateCommandHistory() 'PopupList': [0x38, ['_LIST_ENTRY']], # AllocateCommandHistory() 'CommandBucket': [0x48, ['Array', dict( count=lambda x: x.CommandCount, target='Pointer', target_args=dict( target='_COMMAND') )]], }], '_ALIAS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'SourceLength': [0x10, ['unsigned short']], # AddAlias() 'TargetLength': [0x12, ['unsigned short']], # AddAlias() # reversed from AddAlias() 'Source': [0x18, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.SourceLength * 2)]]], 'Target': [0x20, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.TargetLength * 2 )]]], # AddAlias() }], '_EXE_ALIAS_LIST' : [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ExeLength': [0x10, ['unsigned short']], # AddExeAliasList() # AddExeAliasList() 'ExeName': [0x18, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.ExeLength * 2)]]], 'AliasList': [0x20, ['_LIST_ENTRY']], # AddExeAliasList() }], '_POPUP_LIST' : [None, { 'ListEntry' : [0x00, ['_LIST_ENTRY']], }], '_CONSOLE_INFORMATION': [None, { # MOV RCX, [RIP+0x25bb5] conhost!gConsoleInformation+0x28 'ProcessList': [0x28, ['_LIST_ENTRY']], 'CurrentScreenBuffer': [0xE0, ['Pointer', dict( target='_SCREEN_INFORMATION' )]], # AllocateConsole() 'ScreenBuffer': [0xE8, ['Pointer', dict( target='_SCREEN_INFORMATION' )]], # AllocateConsole() 'HistoryList': [0x148, ['_LIST_ENTRY']], # AllocateCommandHistory() 'ExeAliasList': [0x148, ['_LIST_ENTRY']], # SrvGetConsoleAliasExes() 'HistoryBufferCount': [0x168, ['unsigned short']], # AllocateConsole() 'HistoryBufferMax': [0x16A, ['unsigned short']], # AllocateConsole() 'CommandHistorySize': [0x16C, ['unsigned short']], # AllocateConsole() 'OriginalTitle': [0x170, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=256 ) )]], # SrvGetConsoleTitle() 'Title': [0x178, ['Pointer', dict( target='UnicodeString', target_args=dict( encoding='utf16', length=256 ) )]], # SrvGetConsoleTitle() }], '_CONSOLE_PROCESS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ProcessHandle': [0x10, ['unsigned int']], # FindProcessInList() }], '_SCREEN_INFORMATION': [None, { 'ScreenX': [8, ['short']], 'ScreenY': [10, ['short']], 'Rows': [0x48, ['Pointer', dict( target="Array", target_args=dict( count=lambda x: x.ScreenY, target='_ROW' ) )]], 'Next': [0x128, ['pointer', ['_SCREEN_INFORMATION']]], }], '_ROW': [0x28, { 'Chars': [0x08, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.obj_parent.obj_parent.ScreenX * 2, )]]], }], } # Windows XP, 2003, 2008, Vista from winsrv.dll winsrv_types_x86 = { '_COMMAND': [None, { 'CmdLength': [0x00, ['unsigned short']], 'Cmd' : [0x02, ['UnicodeString', dict( encoding='utf16', length=lambda x: x.CmdLength )]], }], '_COMMAND_HISTORY': [None, { 'Flags' : [0x00, ['Flags', { 'bitmap': { 'Allocated': 0, 'Reset': 1 } }]], 'ListEntry': [0x04, ['_LIST_ENTRY']], 'Application': [0x0C, ['pointer', ['UnicodeString', dict( encoding='utf16', length=256)]]], 'CommandCount': [0x10, ['short']], 'LastAdded': [0x12, ['short']], 'LastDisplayed': [0x14, ['short']], 'FirstCommand': [0x16, ['short']], 'CommandCountMax': [0x18, ['short']], 'ProcessHandle': [0x1C, ['unsigned int']], 'PopupList': [0x20, ['_LIST_ENTRY']], 'CommandBucket': [0x28, ['Array', dict( count=lambda x: x.CommandCount, target='Pointer', target_args=dict( target='_COMMAND' ) )]], }], '_ALIAS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'SourceLength': [0x08, ['unsigned short']], 'TargetLength': [0x0A, ['unsigned short']], 'Source': [0x0C, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.SourceLength * 2 )]]], 'Target': [0x10, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.TargetLength * 2)]]], }], '_EXE_ALIAS_LIST' : [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ExeLength': [0x08, ['unsigned short']], 'ExeName': [0x0C, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=lambda x: x.ExeLength * 2)]]], 'AliasList': [0x10, ['_LIST_ENTRY']], }], '_POPUP_LIST' : [None, { 'ListEntry' : [0x00, ['_LIST_ENTRY']], }], '_CONSOLE_INFORMATION': [None, { 'CurrentScreenBuffer': [0xB0, ['pointer', ['_SCREEN_INFORMATION']]], 'ScreenBuffer': [0xB4, ['pointer', ['_SCREEN_INFORMATION']]], 'HistoryList': [0x108, ['_LIST_ENTRY']], 'ProcessList': [0x100, ['_LIST_ENTRY']], 'ExeAliasList': [0x110, ['_LIST_ENTRY']], 'HistoryBufferCount': [0x118, ['unsigned short']], 'HistoryBufferMax': [0x11A, ['unsigned short']], 'CommandHistorySize': [0x11C, ['unsigned short']], 'OriginalTitle': [0x124, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256)]]], 'Title': [0x128, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256 )]]], }], '_CONSOLE_PROCESS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ProcessHandle': [0x08, ['unsigned int']], 'Process': [0x0C, ['pointer', ['_CSR_PROCESS']]], }], '_SCREEN_INFORMATION': [None, { 'Console': [0x00, ['pointer', ['_CONSOLE_INFORMATION']]], 'ScreenX': [0x24, ['short']], 'ScreenY': [0x26, ['short']], 'Rows': [0x58, ['pointer', [ 'array', lambda x: x.ScreenY, ['_ROW']]]], 'Next': [0xF8, ['pointer', ['_SCREEN_INFORMATION']]], }], '_ROW': [0x1C, { 'Chars': [0x08, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256 )]]], }], # this is a public PDB '_CSR_PROCESS' : [0x60, { 'ClientId' : [0x0, ['_CLIENT_ID']], 'ListLink' : [0x8, ['_LIST_ENTRY']], 'ThreadList' : [0x10, ['_LIST_ENTRY']], 'NtSession' : [0x18, ['pointer', ['_CSR_NT_SESSION']]], 'ClientPort' : [0x1c, ['pointer', ['void']]], 'ClientViewBase' : [0x20, ['pointer', ['unsigned char']]], 'ClientViewBounds' : [0x24, ['pointer', ['unsigned char']]], 'ProcessHandle' : [0x28, ['pointer', ['void']]], 'SequenceNumber' : [0x2c, ['unsigned long']], 'Flags' : [0x30, ['unsigned long']], 'DebugFlags' : [0x34, ['unsigned long']], 'ReferenceCount' : [0x38, ['unsigned long']], 'ProcessGroupId' : [0x3c, ['unsigned long']], 'ProcessGroupSequence' : [0x40, ['unsigned long']], 'LastMessageSequence' : [0x44, ['unsigned long']], 'NumOutstandingMessages' : [0x48, ['unsigned long']], 'ShutdownLevel' : [0x4c, ['unsigned long']], 'ShutdownFlags' : [0x50, ['unsigned long']], 'Luid' : [0x54, ['_LUID']], 'ServerDllPerProcessData' : [0x5c, [ 'array', 1, ['pointer', ['void']]]], }], } winsrv_types_x64 = { '_COMMAND': [None, { 'CmdLength': [0x00, ['unsigned short']], 'Cmd' : [0x02, ['UnicodeString', dict( encoding='utf16', length=lambda x: x.CmdLength)]], }], '_COMMAND_HISTORY': [None, { 'Flags' : [0x00, ['Flags', { 'bitmap': {'Allocated': 0, 'Reset': 1}}]], 'ListEntry': [0x08, ['_LIST_ENTRY']], 'Application': [0x18, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256)]]], 'CommandCount': [0x20, ['short']], 'LastAdded': [0x22, ['short']], 'LastDisplayed': [0x24, ['short']], 'FirstCommand': [0x26, ['short']], 'CommandCountMax': [0x28, ['short']], 'ProcessHandle': [0x30, ['unsigned int']], 'PopupList': [0x38, ['_LIST_ENTRY']], 'CommandBucket': [0x48, [ 'array', lambda x: x.CommandCount, [ 'pointer', ['_COMMAND']]]], }], '_ALIAS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'SourceLength': [0x10, ['unsigned short']], 'TargetLength': [0x12, ['unsigned short']], 'Source': [0x14, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=lambda x: x.SourceLength * 2)]]], 'Target': [0x1C, ['pointer', ['UnicodeString', dict( encoding='utf16', length=lambda x: x.TargetLength * 2)]]], }], '_EXE_ALIAS_LIST' : [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ExeLength': [0x10, ['unsigned short']], 'ExeName': [0x12, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=lambda x: x.ExeLength * 2)]]], 'AliasList': [0x1A, ['_LIST_ENTRY']], }], '_POPUP_LIST' : [None, { 'ListEntry' : [0x00, ['_LIST_ENTRY']], }], '_CONSOLE_INFORMATION': [None, { 'CurrentScreenBuffer': [0xE8, ['pointer', ['_SCREEN_INFORMATION']]], 'ScreenBuffer': [0xF0, ['pointer', ['_SCREEN_INFORMATION']]], 'HistoryList': [0x188, ['_LIST_ENTRY']], 'ProcessList': [0x178, ['_LIST_ENTRY']], 'ExeAliasList': [0x198, ['_LIST_ENTRY']], 'HistoryBufferCount': [0x1A8, ['unsigned short']], 'HistoryBufferMax': [0x1AA, ['unsigned short']], 'CommandHistorySize': [0x1AC, ['unsigned short']], 'OriginalTitle': [0x1B0, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256)]]], 'Title': [0x1B8, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256)]]], }], '_CONSOLE_PROCESS': [None, { 'ListEntry': [0x00, ['_LIST_ENTRY']], 'ProcessHandle': [0x10, ['unsigned int']], 'Process': [0x18, ['pointer', ['_CSR_PROCESS']]], }], '_SCREEN_INFORMATION': [None, { 'Console': [0x00, ['pointer', ['_CONSOLE_INFORMATION']]], 'ScreenX': [0x28, ['short']], 'ScreenY': [0x2A, ['short']], 'Rows': [0x68, ['pointer', [ 'array', lambda x: x.ScreenY, ['_ROW']]]], 'Next': [0x128, ['pointer', ['_SCREEN_INFORMATION']]], }], '_ROW': [0x28, { 'Chars': [0x08, ['pointer', [ 'UnicodeString', dict( encoding='utf16', length=256)]]], }], # this is a public PDB '_CSR_PROCESS' : [0x60, { 'ClientId' : [0x0, ['_CLIENT_ID']], 'ListLink' : [0x8, ['_LIST_ENTRY']], 'ThreadList' : [0x10, ['_LIST_ENTRY']], 'NtSession' : [0x18, ['pointer', ['_CSR_NT_SESSION']]], 'ClientPort' : [0x1c, ['pointer', ['void']]], 'ClientViewBase' : [0x20, ['pointer', ['unsigned char']]], 'ClientViewBounds' : [0x24, ['pointer', ['unsigned char']]], 'ProcessHandle' : [0x28, ['pointer', ['void']]], 'SequenceNumber' : [0x2c, ['unsigned long']], 'Flags' : [0x30, ['unsigned long']], 'DebugFlags' : [0x34, ['unsigned long']], 'ReferenceCount' : [0x38, ['unsigned long']], 'ProcessGroupId' : [0x3c, ['unsigned long']], 'ProcessGroupSequence' : [0x40, ['unsigned long']], 'LastMessageSequence' : [0x44, ['unsigned long']], 'NumOutstandingMessages' : [0x48, ['unsigned long']], 'ShutdownLevel' : [0x4c, ['unsigned long']], 'ShutdownFlags' : [0x50, ['unsigned long']], 'Luid' : [0x54, ['_LUID']], 'ServerDllPerProcessData' : [0x5c, [ 'array', 1, ['pointer', ['void']]]], }], } class _CONSOLE_INFORMATION(obj.Struct): """ object class for console information structs """ def get_screens(self): """Generator for screens in the console. A console can have multiple screen buffers at a time, but only the current/active one is displayed. Multiple screens are tracked using the singly-linked list _SCREEN_INFORMATION.Next. See CreateConsoleScreenBuffer """ screens = [self.CurrentScreenBuffer] if self.ScreenBuffer not in screens: screens.append(self.ScreenBuffer) for screen in screens: cur = screen while cur and cur.v() != 0: yield cur cur = cur.Next.dereference() class _SCREEN_INFORMATION(obj.Struct): """ object class for screen information """ def get_buffer(self, truncate=True): """Get the screen buffer. The screen buffer is comprised of the screen's Y coordinate which tells us the number of rows and the X coordinate which tells us the width of each row in characters. These together provide all of the input and output that users see when the console is displayed. @param truncate: True if the empty rows at the end (i.e. bottom) of the screen buffer should be supressed. """ rows = [] for _, row in enumerate(self.Rows.dereference()): if row.Chars.is_valid(): rows.append(utils.SmartUnicode( row.Chars.dereference())[0:self.ScreenX]) # To truncate empty rows at the end, walk the list # backwards and get the last non-empty row. Use that # row index to splice. An "empty" row isn't just "" # as one might assume. It is actually ScreenX number # of space characters if truncate: non_empty_index = 0 for index, row in enumerate(reversed(rows)): ## It seems that when the buffer width is greater than 128 ## characters, its truncated to 128 in memory. if row.count(" ") != min(self.ScreenX, 128): non_empty_index = index break if non_empty_index == 0: rows = [] else: rows = rows[0:len(rows) - non_empty_index] return rows class WinSrv86(basic.Profile32Bits, basic.BasicClasses): """A domain specific profile for the xp, 2008.""" def __init__(self, **kwargs): super(WinSrv86, self).__init__(**kwargs) self.add_types(common_types) self.add_types(winsrv_types_x86) self.add_classes({ '_CONSOLE_INFORMATION': _CONSOLE_INFORMATION, '_SCREEN_INFORMATION': _SCREEN_INFORMATION, }) class WinSrv64(basic.ProfileLLP64, basic.BasicClasses): """A domain specific profile for the xp, 2008.""" def __init__(self, **kwargs): super(WinSrv64, self).__init__(**kwargs) self.add_types(common_types_64) self.add_types(winsrv_types_x64) self.add_classes({ '_CONSOLE_INFORMATION': _CONSOLE_INFORMATION, '_SCREEN_INFORMATION': _SCREEN_INFORMATION, }) class ConHost86(basic.Profile32Bits, basic.BasicClasses): """A domain specific profile for windows 7.""" def __init__(self, **kwargs): super(ConHost86, self).__init__(**kwargs) self.add_types(common_types) self.add_types(conhost_types_x86) self.add_classes({ '_CONSOLE_INFORMATION': _CONSOLE_INFORMATION, '_SCREEN_INFORMATION': _SCREEN_INFORMATION, }) class ConHost64(basic.ProfileLLP64, basic.BasicClasses): """A domain specific profile for windows 7.""" def __init__(self, **kwargs): super(ConHost64, self).__init__(**kwargs) self.add_types(common_types_64) self.add_types(conhost_types_x64) self.add_classes({ '_CONSOLE_INFORMATION': _CONSOLE_INFORMATION, '_SCREEN_INFORMATION': _SCREEN_INFORMATION, }) class WinHistoryScanner(vadinfo.VadScanner): """A vad scanner for command histories. The default pattern we search for, as described by Stevens and Casey, is "\x32\x00". That's because CommandCountMax is a little-endian unsigned short whose default value is 50. However, that value can be changed by right clicking cmd.exe and going to Properties->Options->Cmd History or by calling the API function kernel32!SetConsoleHistoryInfo. Thus you can tweak the search criteria by using the --MAX_HISTORY. """ def __init__(self, max_history=MAX_HISTORY_DEFAULT, **kwargs): super(WinHistoryScanner, self).__init__(**kwargs) self.max_history = max_history def scan(self, **kwargs): for hit in super(WinHistoryScanner, self).scan(**kwargs): # Check to see if the object is valid. hist = self.profile.Object( "_COMMAND_HISTORY", vm=self.address_space, offset=hit - self.profile.get_obj_offset( "_COMMAND_HISTORY", "CommandCountMax")) if not hist.is_valid(): continue # The count must be between zero and max if hist.CommandCount < 0 or hist.CommandCount > self.max_history: continue # Last added must be between -1 and max if hist.LastAdded < -1 or hist.LastAdded > self.max_history: continue # Last displayed must be between -1 and max if hist.LastDisplayed < -1 or hist.LastDisplayed > self.max_history: continue # First command must be between zero and max if hist.FirstCommand < 0 or hist.FirstCommand > self.max_history: continue # Validate first command with last added if (hist.FirstCommand != 0 and hist.FirstCommand != hist.LastAdded + 1): continue # Process handle must be a valid pid if hist.ProcessHandle <= 0 or hist.ProcessHandle > 0xFFFF: continue Popup = self.profile._POPUP_LIST( offset=hist.PopupList.Flink, vm=self.address_space) # Check that the popup list entry is in tact if Popup.ListEntry.Blink != hist.PopupList.obj_offset: continue yield hist class CmdScan(common.WindowsCommandPlugin): """Extract command history by scanning for _COMMAND_HISTORY""" __name = "cmdscan" __args = [ dict(name="max_history", default=MAX_HISTORY_DEFAULT, type="IntParser", help="Value of history buffer size. See " "HKEY_CURRENT_USER\\Console\\HistoryBufferSize " "for default.") ] def generate_hits(self): """Generates _COMMAND_HISTORY objects.""" architecture = self.profile.metadata("arch") # The process we select is conhost on Win7 or csrss for others if self.profile.metadata("major") >= 6: process_name = "conhost.exe" if architecture == "AMD64": process_profile = ConHost64(session=self.session) else: process_profile = ConHost86(session=self.session) else: process_name = "csrss.exe" if architecture == "AMD64": process_profile = WinSrv64(session=self.session) else: process_profile = WinSrv86(session=self.session) # Only select those processes we care about: for task in self.session.plugins.pslist( proc_regex=process_name).filter_processes(): scanner = WinHistoryScanner( task=task, process_profile=process_profile, max_history=self.plugin_args.max_history, session=self.session) pattern = bytes((self.plugin_args.max_history, 0)) scanner.checks = [ ("StringCheck", dict(needle=pattern)) ] scanner.build_constraints() for hist in scanner.scan(): yield task, hist def render(self, renderer): for task, hist in self.generate_hits(): renderer.section() renderer.format(u"CommandProcess: {0} Pid: {1}\n", task.ImageFileName, task.UniqueProcessId) renderer.format( u"CommandHistory: {0:#x} Application: {1} Flags: {2}\n", hist.obj_offset, hist.Application.dereference(), hist.Flags) renderer.format( u"CommandCount: {0} LastAdded: {1} LastDisplayed: {2}\n", hist.CommandCount, hist.LastAdded, hist.LastDisplayed) renderer.format(u"FirstCommand: {0} CommandCountMax: {1}\n", hist.FirstCommand, hist.CommandCountMax) renderer.format(u"ProcessHandle: {0:#x}\n", hist.ProcessHandle) renderer.table_header([("Cmd", "command", ">3"), ("Address", "address", "[addrpad]"), ("Text", "text", "")]) # If the _COMMAND_HISTORY is in use, we would only take # hist.CommandCount but since we're brute forcing, try the # maximum and hope that some slots were not overwritten # or zero-ed out. pointers = hist.obj_profile.Array( target="address", count=hist.CommandCountMax, offset=hist.obj_offset + hist.obj_profile.get_obj_offset( "_COMMAND_HISTORY", "CommandBucket"), vm=hist.obj_vm) for i, p in enumerate(pointers): cmd = p.cast("Pointer", target="_COMMAND").deref() if cmd.obj_offset and cmd.Cmd: renderer.table_row( i, cmd.obj_offset, utils.SmartUnicode(cmd.Cmd).encode("unicode_escape")) class ConsoleScanner(vadinfo.VadScanner): """A scanner for _CONSOLE_INFORMATION.""" def __init__(self, max_history=MAX_HISTORY_DEFAULT, history_buffers=HISTORY_BUFFERS_DEFAULTS, **kwargs): super(ConsoleScanner, self).__init__(**kwargs) self.max_history = max_history self.history_buffers = history_buffers def scan(self, **kwargs): for hit in super(ConsoleScanner, self).scan(**kwargs): # Check to see if the object is valid. console = self.profile.Object( "_CONSOLE_INFORMATION", offset=hit - self.profile.get_obj_offset( "_CONSOLE_INFORMATION", "CommandHistorySize"), vm=self.address_space, parent=self.task) if (console.HistoryBufferMax != self.history_buffers or console.HistoryBufferCount > self.history_buffers): continue # Check the first command history as the final constraint next_history = console.HistoryList.Flink.dereference( ).dereference_as("_COMMAND_HISTORY", "ListEntry") if next_history.CommandCountMax != self.max_history: continue yield console class ConsoleScan(CmdScan): """Extract command history by scanning for _CONSOLE_INFORMATION""" __name = "consolescan" __args = [ dict(name="history_buffers", default=HISTORY_BUFFERS_DEFAULTS, type="IntParser", help="Value of history buffer size. See " "HKEY_CURRENT_USER\\Console\\HistoryBufferSize " "for default.") ] def generate_hits(self): """Generates _CONSOLE_INFORMATION objects.""" architecture = self.profile.metadata("arch") # The process we select is conhost on Win7 or csrss for others # Only select those processes we care about: for task in self.session.plugins.pslist( proc_regex="(conhost.exe|csrss.exe)").filter_processes(): if utils.SmartUnicode(task.ImageFileName).lower() == "conhost.exe": if architecture == "AMD64": process_profile = ConHost64(session=self.session) else: process_profile = ConHost86(session=self.session) elif utils.SmartUnicode(task.ImageFileName).lower() == "csrss.exe": if architecture == "AMD64": process_profile = WinSrv64(session=self.session) else: process_profile = WinSrv86(session=self.session) else: continue scanner = ConsoleScanner( task=task, process_profile=process_profile, session=self.session, max_history=self.plugin_args.max_history, history_buffers=self.plugin_args.history_buffers) pattern = bytes((self.plugin_args.max_history, 0)) scanner.checks = [ ("StringCheck", dict(needle=pattern)) ] scanner.build_constraints() for console in scanner.scan(): yield task, console def render(self, renderer): for task, console in self.generate_hits(): renderer.section() renderer.format(u"ConsoleProcess: {0} Pid: {1}\n", task.ImageFileName, task.UniqueProcessId) renderer.format(u"Console: {0:#x} CommandHistorySize: {1}\n", console, console.CommandHistorySize) renderer.format( u"HistoryBufferCount: {0} HistoryBufferMax: {1}\n", console.HistoryBufferCount, console.HistoryBufferMax) renderer.format(u"OriginalTitle: {0}\n", console.OriginalTitle.dereference()) renderer.format(u"Title: {0}\n", console.Title.dereference()) for console_proc in console.ProcessList.list_of_type( "_CONSOLE_PROCESS", "ListEntry"): process = task.ObReferenceObjectByHandle( console_proc.ProcessHandle, type="_EPROCESS") if process: renderer.format( u"AttachedProcess: {0} Pid: {1} Handle: {2:#x}\n", process.ImageFileName, process.UniqueProcessId, console_proc.ProcessHandle) for hist in console.HistoryList.list_of_type( "_COMMAND_HISTORY", "ListEntry"): renderer.format(u"----\n") renderer.format( u"CommandHistory: {0:#x} Application: {1} Flags: {2}\n", hist, hist.Application.dereference(), hist.Flags) renderer.format( u"CommandCount: {0} LastAdded: {1} LastDisplayed: {2}\n", hist.CommandCount, hist.LastAdded, hist.LastDisplayed) renderer.format(u"FirstCommand: {0} CommandCountMax: {1}\n", hist.FirstCommand, hist.CommandCountMax) renderer.format(u"ProcessHandle: {0:#x}\n", hist.ProcessHandle) for i, cmd in enumerate(hist.CommandBucket): if cmd.Cmd.is_valid(): renderer.format(u"Cmd #{0} at {1:#x}: {2}\n", i, cmd, str(cmd.Cmd)) for exe_alias in console.ExeAliasList.list_of_type( "_EXE_ALIAS_LIST", "ListEntry"): for alias in exe_alias.AliasList.list_of_type( "_ALIAS", "ListEntry"): renderer.format(u"----\n") renderer.format( u"Alias: {0} Source: {1} Target: {2}\n", exe_alias.ExeName.dereference(), alias.Source.dereference(), alias.Target.dereference()) for screen in console.get_screens(): renderer.format(u"----\n") renderer.format(u"Screen {0:#x} X:{1} Y:{2}\n", screen.dereference(), screen.ScreenX, screen.ScreenY) renderer.format(u"Dump:\n{0}\n", '\n'.join(screen.get_buffer())) class Conhost(pe_vtypes.BasicPEProfile): """A profile for Conhost.exe.""" @classmethod def Initialize(cls, profile): super(Conhost, cls).Initialize(profile) if profile.metadata("arch") == "AMD64": profile.add_overlay(conhost_types_x64) profile.add_overlay(common_types_64) elif profile.metadata("arch") == "I386": profile.add_overlay(conhost_types_x86) profile.add_overlay(common_types) class Consoles(common.WindowsCommandPlugin): """Enumerate command consoles.""" name = "consoles" def _render_conhost_process(self, task, renderer): self.cc.SwitchProcessContext(task) console = self.session.address_resolver.get_constant_object( "conhost!gConsoleInformation", "_CONSOLE_INFORMATION") if console == None: self.session.logging.warning( "Unable to load profile for conhost.exe.") return renderer.format(u"ConsoleProcess: {0}\n", task) renderer.format(u"Title: {0}\n", console.Title.deref()) renderer.format(u"OriginalTitle: {0}\n", console.OriginalTitle.dereference()) for console_proc in console.ProcessList.list_of_type( "_CONSOLE_PROCESS", "ListEntry"): process = task.ObReferenceObjectByHandle( console_proc.ProcessHandle, type="_EPROCESS") if process: renderer.format( u"AttachedProcess: {0} Handle: {1:style=address}\n", process, console_proc.ProcessHandle) for hist in console.HistoryList.list_of_type( "_COMMAND_HISTORY", "ListEntry"): renderer.format(u"----\n") renderer.format( u"CommandHistory: {0:#x} Application: {1} Flags: {2}\n", hist, hist.Application.dereference(), hist.Flags) renderer.format( u"CommandCount: {0} LastAdded: {1} LastDisplayed: {2}\n", hist.CommandCount, hist.LastAdded, hist.LastDisplayed) renderer.format(u"FirstCommand: {0} CommandCountMax: {1}\n", hist.FirstCommand, hist.CommandCountMax) renderer.format(u"ProcessHandle: {0:#x}\n", hist.ProcessHandle) for i, cmd in enumerate(hist.CommandBucket): if cmd.Cmd.is_valid(): renderer.format(u"Cmd #{0} at {1:#x}: {2}\n", i, cmd, str(cmd.Cmd)) for exe_alias in console.ExeAliasList.list_of_type( "_EXE_ALIAS_LIST", "ListEntry"): for alias in exe_alias.AliasList.list_of_type( "_ALIAS", "ListEntry"): if alias == None: continue renderer.format(u"----\n") renderer.format( u"Alias: {0} Source: {1} Target: {2}\n", exe_alias.ExeName.dereference(), alias.Source.dereference(), alias.Target.dereference()) for screen in console.ScreenBuffer.walk_list("Next"): renderer.format(u"----\n") renderer.format(u"Screen {0:#x} X:{1} Y:{2}\n", screen, screen.ScreenX, screen.ScreenY) screen_data = [] for row in screen.Rows: row_data = row.Chars.deref() # Since a row is always screen.ScreenX wide a 0 width row means # the page is not available or incorrect. if len(row_data) == 0: continue screen_data.append((row_data, str(row_data).rstrip())) # Trim empty rows from the end of the screen. while screen_data and not screen_data[-1][1]: screen_data.pop(-1) for row, row_string in screen_data: renderer.format( "{0:style=address}: {1}\n", row, row_string) def render(self, renderer): self.cc = self.session.plugins.cc() with self.cc: for task in self.session.plugins.pslist( proc_regex="conhost.exe").filter_processes(): renderer.section() self._render_conhost_process(task, renderer)
gpl-2.0
UITools/saleor
saleor/payment/gateways/dummy/forms.py
1
1358
from django import forms from django.utils.translation import pgettext_lazy, ugettext_lazy as _ from ... import ChargeStatus class DummyPaymentForm(forms.Form): charge_status = forms.ChoiceField( label=pgettext_lazy('Payment status form field', 'Payment status'), choices=ChargeStatus.CHOICES, initial=ChargeStatus.NOT_CHARGED, widget=forms.RadioSelect) def clean(self): cleaned_data = super(DummyPaymentForm, self).clean() # Partially refunded is not supported directly # since only last transaction of call_gateway will be processed charge_status = cleaned_data['charge_status'] if charge_status in [ ChargeStatus.PARTIALLY_CHARGED, ChargeStatus.PARTIALLY_REFUNDED]: raise forms.ValidationError( _('Setting charge status to {} directly ' 'is not supported. Please use the dashboard to ' 'refund partially.'.format(charge_status)), code='invalid_charge_status') return cleaned_data def get_payment_token(self): """Return selected charge status instead of token for testing only. Gateways used for production should return an actual token instead.""" charge_status = self.cleaned_data['charge_status'] return charge_status
bsd-3-clause
geoff-reid/RackHD
test/tests/api/v2_0/__init__.py
10
1176
# import tests from config_tests import ConfigTests from nodes_tests import NodesTests from catalogs_tests import CatalogsTests from pollers_tests import PollersTests from obm_tests import OBMTests from workflows_tests import WorkflowsTests from workflowTasks_tests import WorkflowTasksTests from tags_tests import TagsTests from schema_tests import SchemaTests from lookups_tests import LookupsTests from skupack_tests import SkusTests from users_tests import UsersTests from swagger_tests import SwaggerTests from sel_alert_poller_tests import SELPollerAlertTests from os_install_tests import OSInstallTests from decomission_node_tests import DecommissionNodesTests tests = [ 'nodes_api2.tests', 'config_api2.tests', 'catalogs_api2.tests', 'pollers_api2.tests', 'obm_api2.tests', 'workflows_api2.tests', 'workflowTasks_api2.tests' 'pollers.tests', 'tags_api2.tests', 'obm_api2.tests', 'schemas_api2.tests','' 'skus_api2.tests', 'lookups_api2.tests', 'users_api2.tests', 'swagger.tests', 'sel_alert_poller_api2.tests' ] regression_tests = [ 'os-install.v2.0.tests', 'deccommission-nodes.v2.0.tests' ]
apache-2.0
cellcounter/cellcounter
cellcounter/accounts/test_views.py
1
17775
from urllib.parse import urlparse from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm from django.contrib.auth.models import User, AnonymousUser from django.contrib.auth.tokens import default_token_generator from django.core import mail from django.core.cache import cache from django.urls import reverse from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode from cellcounter.cc_kapi.factories import UserFactory, KeyboardFactory from .forms import EmailUserCreationForm, PasswordResetForm from .utils import read_signup_email from .views import PasswordResetConfirmView class TestRegistrationView(TestCase): def setUp(self): self.request_factory = RequestFactory() def test_get(self): response = self.client.get(reverse('register')) self.assertEqual(response.status_code, 200) self.assertIsInstance(response.context['form'], EmailUserCreationForm) def test_valid(self): data = {'username': '123', 'email': 'joe@example.org', 'password1': 'test', 'password2': 'test', 'tos': True} response = self.client.post(reverse('register'), data=data, follow=True) self.assertRedirects(response, reverse('new_count')) user = User.objects.get(username='123') messages = list(response.context['messages']) self.assertEqual("Successfully registered, you are now logged in! <a href='/accounts/%s/'>View your profile</a>" % user.id, messages[0].message) self.assertEqual(user, response.context['user']) def test_invalid(self): data = {'username': '123', 'email': 'joe@example.org', 'password1': 'test', 'password2': 'test', 'tos': False} response = self.client.post(reverse('register'), data=data) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'tos', 'You must agree our Terms of Service') self.assertEqual(AnonymousUser(), response.context['user']) @override_settings(RATELIMIT_ENABLE=True) def test_ratelimit_registration(self): cache.clear() data = {'username': '123', 'email': 'joe@example.org', 'password1': 'test', 'password2': 'test', 'tos': True} self.client.post(reverse('register'), data) self.client.logout() data['username'] = 'Another' self.client.post(reverse('register'), data, follow=True) self.client.logout() data['username'] = 'Another2' response = self.client.post(reverse('register'), data, follow=True) messages = list(response.context['messages']) self.assertEqual(1, len(messages)) self.assertEqual('You have been rate limited', messages[0].message) @override_settings(RATELIMIT_ENABLE=True) def test_ratelimit_invalid_form(self): cache.clear() data = {'username': '123', 'email': '1234', 'password1': 'test', 'password2': 'test', 'tos': True} self.client.post(reverse('register'), data) response = self.client.post(reverse('register'), data, follow=True) self.assertEqual(response.status_code, 200) self.assertNotIn('You have been rate limited', response.content.decode("utf-8")) class TestPasswordChangeView(TestCase): def setUp(self): self.factory = RequestFactory() self.user = UserFactory() self.valid_data = {'old_password': 'test', 'new_password1': 'new', 'new_password2': 'new'} self.invalid_data = {'old_password': 'test', 'new_password1': 'test', 'new_password2': '1234'} def test_logged_out_get_redirect(self): response = self.client.get(reverse('change-password')) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('change-password'))) def test_logged_out_post_redirect(self): response = self.client.post(reverse('change-password'), self.valid_data) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('change-password'))) def test_logged_in_to_form(self): self.client.force_login(self.user) response = self.client.get(reverse('change-password')) self.assertEqual(response.status_code, 200) self.assertIsInstance(response.context['form'], PasswordChangeForm) def test_post_valid(self): self.client.force_login(self.user) response = self.client.post(reverse('change-password'), data=self.valid_data, follow=True) self.assertRedirects(response, reverse('new_count')) messages = list(response.context['messages']) self.assertEqual('Password changed successfully', messages[0].message) def test_post_invalid(self): self.client.force_login(self.user) response = self.client.post(reverse('change-password'), data=self.invalid_data) self.assertFormError(response, 'form', 'new_password2', "The two password fields didn't match.") class TestUserDetailView(TestCase): def setUp(self): self.keyboard = KeyboardFactory() def test_get_anonymous(self): user2 = UserFactory() response = self.client.get(reverse('user-detail', kwargs={'pk': user2.id})) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('user-detail', kwargs={'pk': user2.id}))) def test_get_self(self): self.client.force_login(self.keyboard.user) response = self.client.get(reverse('user-detail', kwargs={'pk': self.keyboard.user.id})) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user_detail'], self.keyboard.user) self.assertEqual(len(response.context['keyboards']), 1) def test_get_someone_else(self): user2 = UserFactory() self.client.force_login(self.keyboard.user) response = self.client.get(reverse('user-detail', kwargs={'pk': user2.id})) self.assertEqual(response.status_code, 403) class TestUserDeleteView(TestCase): def setUp(self): self.user = UserFactory() def test_get_delete_anonymous(self): response = self.client.get(reverse('user-delete', kwargs={'pk': self.user.id})) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('user-delete', kwargs={'pk': self.user.id}))) def test_delete_anonymous(self): user2 = UserFactory() response = self.client.delete(reverse('user-delete', kwargs={'pk': user2.id})) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('user-delete', kwargs={'pk': user2.id}))) def test_get_delete_self(self): self.client.force_login(self.user) response = self.client.get(reverse('user-delete', kwargs={'pk': self.user.id})) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'accounts/user_check_delete.html') def test_delete_self(self): self.client.force_login(self.user) response = self.client.delete(reverse('user-delete', kwargs={'pk': self.user.id}), follow=True) self.assertRedirects(response, reverse('new_count')) self.assertEqual('User account deleted', list(response.context['messages'])[0].message) def test_get_delete_someone_else(self): user2 = UserFactory() self.client.force_login(self.user) response = self.client.get(reverse('user-delete', kwargs={'pk': user2.id})) self.assertEqual(response.status_code, 403) def test_delete_someone_else(self): user2 = UserFactory() self.client.force_login(self.user) response = self.client.delete(reverse('user-delete', kwargs={'pk': user2.id})) self.assertEqual(response.status_code, 403) class TestUserUpdateView(TestCase): def setUp(self): self.valid_data = {'first_name': 'Jack', 'last_name': 'Example', 'email': 'test@example.org'} self.extra_data = {'first_name': 'Joe', 'last_name': 'Example', 'email': 'test@example.org', 'username': 'invalid'} self.invalid_data = {'first_name': 'Joe', 'last_name': 'Example', 'email': '1234'} def test_get_update_when_anonymous(self): user = UserFactory() response = self.client.get(reverse('user-update', kwargs={'pk': user.id})) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('user-update', kwargs={'pk': user.id}))) def test_post_update_when_anonymous(self): user = UserFactory() response = self.client.post(reverse('user-update', kwargs={'pk': user.id}), data=self.valid_data) self.assertRedirects(response, "%s?next=%s" % (reverse('login'), reverse('user-update', kwargs={'pk': user.id}))) def test_update_self_valid(self): user = UserFactory() self.client.force_login(user) response = self.client.post(reverse('user-update', kwargs={'pk': user.id}), data=self.valid_data, follow=True) self.assertRedirects(response, reverse('user-detail', kwargs={'pk': user.id})) self.assertEqual('User details updated', list(response.context['messages'])[0].message) updated_user = User.objects.get(username=user.username) self.assertNotEqual(updated_user.first_name, user.first_name) self.assertNotEqual(updated_user.last_name, user.last_name) self.assertNotEqual(updated_user.email, user.email) def test_update_self_extra(self): user = UserFactory() self.client.force_login(user) response = self.client.post(reverse('user-update', kwargs={'pk': user.id}), data=self.extra_data, follow=True) self.assertRedirects(response, reverse('user-detail', kwargs={'pk': user.id})) self.assertEqual('User details updated', list(response.context['messages'])[0].message) updated_user = User.objects.get(username=user.username) self.assertNotEqual(updated_user.first_name, user.first_name) self.assertNotEqual(updated_user.last_name, user.last_name) self.assertNotEqual(updated_user.email, user.email) self.assertEqual(updated_user.username, user.username) def test_update_self_invalid(self): user = UserFactory() self.client.force_login(user) response = self.client.post(reverse('user-update', kwargs={'pk': user.id}), data=self.invalid_data) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'email', 'Enter a valid email address.') def test_update_someone_else(self): user = UserFactory() user2 = UserFactory() self.client.force_login(user) response = self.client.post(reverse('user-update', kwargs={'pk': user2.id})) self.assertEqual(response.status_code, 403) class TestPasswordResetView(TestCase): def setUp(self): self.factory = RequestFactory() self.user = UserFactory() def test_get_form(self): response = self.client.get(reverse('password-reset')) self.assertEqual(response.status_code, 200) self.assertIsInstance(response.context['form'], PasswordResetForm) self.assertTemplateUsed(response, 'accounts/reset_form.html') def test_post_valid_email(self): data = {'email': self.user.email} response = self.client.post(reverse('password-reset'), data=data, follow=True) self.assertRedirects(response, reverse('new_count')) self.assertEqual('Reset email sent', list(response.context['messages'])[0].message) self.assertEqual(1, len(mail.outbox)) url, path = read_signup_email(mail.outbox[0]) uidb64, token = urlparse(url).path.split('/')[-3:-1] self.assertEqual(path, reverse('password-reset-confirm', kwargs={'uidb64': uidb64, 'token': token})) def test_post_invalid_email(self): data = {'email': 'invalid@example.org'} response = self.client.post(reverse('password-reset'), data=data, follow=True) self.assertRedirects(response, reverse('new_count')) self.assertEqual(0, len(mail.outbox)) @override_settings(RATELIMIT_ENABLE=True) def test_post_ratelimit(self): for n in range(0, 5): self.client.post(reverse('password-reset'), data={'email': self.user.email}, follow=True) response = self.client.post(reverse('password-reset'), data={'email': self.user.email}, follow=True) self.assertEqual(list(response.context['messages'])[0].message, 'You have been rate limited') cache.clear() class TestPasswordResetConfirmView(TestCase): def setUp(self): self.user = UserFactory() self.valid_uidb64 = urlsafe_base64_encode(force_bytes(self.user.pk)) self.valid_data = {'new_password1': 'newpwd', 'new_password2': 'newpwd'} self.invalid_data = {'new_password1': 'newpwd', 'new_password2': '1234'} def _generate_token(self, user): return default_token_generator.make_token(user) def test_valid_user_valid(self): """valid_user() with valid uidb64""" self.assertEqual(PasswordResetConfirmView().valid_user(self.valid_uidb64), self.user) def test_valid_user_invalid(self): """valid_user() with invalid uidb64""" uidb64 = urlsafe_base64_encode(force_bytes(2)) self.assertIsNone(PasswordResetConfirmView().valid_user(uidb64)) def test_valid_token_valid(self): """valid_token() with valid user and token""" self.assertTrue(PasswordResetConfirmView().valid_token(self.user, self._generate_token(self.user))) def test_valid_token_invalid_token(self): """valid_token() with valid user and invalid token""" token = "AAA-AAAAAAAAAAAAAAAAAAAA" self.assertFalse(PasswordResetConfirmView().valid_token(self.user, token)) def test_valid_token_invalid_both(self): """valid_token() with invalid user and invalid token""" token = "AAA-AAAAAAAAAAAAAAAAAAAA" self.assertFalse(PasswordResetConfirmView().valid_token(None, self._generate_token(self.user))) def test_get_invalid_token(self): token = "AAA-AAAAAAAAAAAAAAAAAAAA" response = self.client.get(reverse('password-reset-confirm', kwargs={'uidb64': self.valid_uidb64, 'token': token})) self.assertEqual(response.status_code, 200) self.assertFalse(response.context['validlink']) self.assertIn("The password reset link was invalid, possibly because it has already been used." " Please request a new password reset.", response.content.decode("utf-8")) def test_get_invalid_user(self): response = self.client.get(reverse('password-reset-confirm', kwargs={'uidb64': urlsafe_base64_encode(force_bytes(2)), 'token': self._generate_token(self.user)})) self.assertEqual(response.status_code, 200) self.assertFalse(response.context['validlink']) self.assertIn("The password reset link was invalid, possibly because it has already been used." " Please request a new password reset.", response.content.decode("utf-8")) def test_post_invalid_token(self): token = "AAA-AAAAAAAAAAAAAAAAAAAA" response = self.client.post(reverse('password-reset-confirm', kwargs={'uidb64': self.valid_uidb64, 'token': token}), data=self.valid_data) self.assertEqual(response.status_code, 200) self.assertFalse(response.context['validlink']) self.assertIn("The password reset link was invalid, possibly because it has already been used." " Please request a new password reset.", response.content.decode("utf-8")) def test_get_valid(self): token = self._generate_token(self.user) response = self.client.get(reverse('password-reset-confirm', kwargs={'uidb64': self.valid_uidb64, 'token': token})) self.assertEqual(response.status_code, 200) self.assertIsInstance(response.context['form'], SetPasswordForm) def test_post_valid(self): token = self._generate_token(self.user) response = self.client.post(reverse('password-reset-confirm', kwargs={'uidb64': self.valid_uidb64, 'token': token}), data=self.valid_data, follow=True) self.assertRedirects(response, reverse('new_count')) self.assertEqual('Password reset successfully', list(response.context['messages'])[0].message) def test_post_invalid(self): token = self._generate_token(self.user) response = self.client.post(reverse('password-reset-confirm', kwargs={'uidb64': self.valid_uidb64, 'token': token}), data=self.invalid_data) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'new_password2', "The two password fields didn't match.")
mit
phoebusliang/parallel-lettuce
tests/integration/lib/Django-1.2.5/django/contrib/gis/measure.py
398
12282
# Copyright (c) 2007, Robert Coup <robert.coup@onetrackmind.co.nz> # 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. # # 3. Neither the name of Distance 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. # """ Distance and Area objects to allow for sensible and convienient calculation and conversions. Authors: Robert Coup, Justin Bronn Inspired by GeoPy (http://exogen.case.edu/projects/geopy/) and Geoff Biggs' PhD work on dimensioned units for robotics. """ __all__ = ['A', 'Area', 'D', 'Distance'] from decimal import Decimal class MeasureBase(object): def default_units(self, kwargs): """ Return the unit value and the default units specified from the given keyword arguments dictionary. """ val = 0.0 for unit, value in kwargs.iteritems(): if not isinstance(value, float): value = float(value) if unit in self.UNITS: val += self.UNITS[unit] * value default_unit = unit elif unit in self.ALIAS: u = self.ALIAS[unit] val += self.UNITS[u] * value default_unit = u else: lower = unit.lower() if lower in self.UNITS: val += self.UNITS[lower] * value default_unit = lower elif lower in self.LALIAS: u = self.LALIAS[lower] val += self.UNITS[u] * value default_unit = u else: raise AttributeError('Unknown unit type: %s' % unit) return val, default_unit @classmethod def unit_attname(cls, unit_str): """ Retrieves the unit attribute name for the given unit string. For example, if the given unit string is 'metre', 'm' would be returned. An exception is raised if an attribute cannot be found. """ lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str elif lower in cls.UNITS: return lower elif lower in cls.LALIAS: return cls.LALIAS[lower] else: raise Exception('Could not find a unit keyword associated with "%s"' % unit_str) class Distance(MeasureBase): UNITS = { 'chain' : 20.1168, 'chain_benoit' : 20.116782, 'chain_sears' : 20.1167645, 'british_chain_benoit' : 20.1167824944, 'british_chain_sears' : 20.1167651216, 'british_chain_sears_truncated' : 20.116756, 'cm' : 0.01, 'british_ft' : 0.304799471539, 'british_yd' : 0.914398414616, 'clarke_ft' : 0.3047972654, 'clarke_link' : 0.201166195164, 'fathom' : 1.8288, 'ft': 0.3048, 'german_m' : 1.0000135965, 'gold_coast_ft' : 0.304799710181508, 'indian_yd' : 0.914398530744, 'inch' : 0.0254, 'km': 1000.0, 'link' : 0.201168, 'link_benoit' : 0.20116782, 'link_sears' : 0.20116765, 'm': 1.0, 'mi': 1609.344, 'mm' : 0.001, 'nm': 1852.0, 'nm_uk' : 1853.184, 'rod' : 5.0292, 'sears_yd' : 0.91439841, 'survey_ft' : 0.304800609601, 'um' : 0.000001, 'yd': 0.9144, } # Unit aliases for `UNIT` terms encountered in Spatial Reference WKT. ALIAS = { 'centimeter' : 'cm', 'foot' : 'ft', 'inches' : 'inch', 'kilometer' : 'km', 'kilometre' : 'km', 'meter' : 'm', 'metre' : 'm', 'micrometer' : 'um', 'micrometre' : 'um', 'millimeter' : 'mm', 'millimetre' : 'mm', 'mile' : 'mi', 'yard' : 'yd', 'British chain (Benoit 1895 B)' : 'british_chain_benoit', 'British chain (Sears 1922)' : 'british_chain_sears', 'British chain (Sears 1922 truncated)' : 'british_chain_sears_truncated', 'British foot (Sears 1922)' : 'british_ft', 'British foot' : 'british_ft', 'British yard (Sears 1922)' : 'british_yd', 'British yard' : 'british_yd', "Clarke's Foot" : 'clarke_ft', "Clarke's link" : 'clarke_link', 'Chain (Benoit)' : 'chain_benoit', 'Chain (Sears)' : 'chain_sears', 'Foot (International)' : 'ft', 'German legal metre' : 'german_m', 'Gold Coast foot' : 'gold_coast_ft', 'Indian yard' : 'indian_yd', 'Link (Benoit)': 'link_benoit', 'Link (Sears)': 'link_sears', 'Nautical Mile' : 'nm', 'Nautical Mile (UK)' : 'nm_uk', 'US survey foot' : 'survey_ft', 'U.S. Foot' : 'survey_ft', 'Yard (Indian)' : 'indian_yd', 'Yard (Sears)' : 'sears_yd' } LALIAS = dict([(k.lower(), v) for k, v in ALIAS.items()]) def __init__(self, default_unit=None, **kwargs): # The base unit is in meters. self.m, self._default_unit = self.default_units(kwargs) if default_unit and isinstance(default_unit, str): self._default_unit = default_unit def __getattr__(self, name): if name in self.UNITS: return self.m / self.UNITS[name] else: raise AttributeError('Unknown unit type: %s' % name) def __repr__(self): return 'Distance(%s=%s)' % (self._default_unit, getattr(self, self._default_unit)) def __str__(self): return '%s %s' % (getattr(self, self._default_unit), self._default_unit) def __cmp__(self, other): if isinstance(other, Distance): return cmp(self.m, other.m) else: return NotImplemented def __add__(self, other): if isinstance(other, Distance): return Distance(default_unit=self._default_unit, m=(self.m + other.m)) else: raise TypeError('Distance must be added with Distance') def __iadd__(self, other): if isinstance(other, Distance): self.m += other.m return self else: raise TypeError('Distance must be added with Distance') def __sub__(self, other): if isinstance(other, Distance): return Distance(default_unit=self._default_unit, m=(self.m - other.m)) else: raise TypeError('Distance must be subtracted from Distance') def __isub__(self, other): if isinstance(other, Distance): self.m -= other.m return self else: raise TypeError('Distance must be subtracted from Distance') def __mul__(self, other): if isinstance(other, (int, float, long, Decimal)): return Distance(default_unit=self._default_unit, m=(self.m * float(other))) elif isinstance(other, Distance): return Area(default_unit='sq_' + self._default_unit, sq_m=(self.m * other.m)) else: raise TypeError('Distance must be multiplied with number or Distance') def __imul__(self, other): if isinstance(other, (int, float, long, Decimal)): self.m *= float(other) return self else: raise TypeError('Distance must be multiplied with number') def __rmul__(self, other): return self * other def __div__(self, other): if isinstance(other, (int, float, long, Decimal)): return Distance(default_unit=self._default_unit, m=(self.m / float(other))) else: raise TypeError('Distance must be divided with number') def __idiv__(self, other): if isinstance(other, (int, float, long, Decimal)): self.m /= float(other) return self else: raise TypeError('Distance must be divided with number') def __nonzero__(self): return bool(self.m) class Area(MeasureBase): # Getting the square units values and the alias dictionary. UNITS = dict([('sq_%s' % k, v ** 2) for k, v in Distance.UNITS.items()]) ALIAS = dict([(k, 'sq_%s' % v) for k, v in Distance.ALIAS.items()]) LALIAS = dict([(k.lower(), v) for k, v in ALIAS.items()]) def __init__(self, default_unit=None, **kwargs): self.sq_m, self._default_unit = self.default_units(kwargs) if default_unit and isinstance(default_unit, str): self._default_unit = default_unit def __getattr__(self, name): if name in self.UNITS: return self.sq_m / self.UNITS[name] else: raise AttributeError('Unknown unit type: ' + name) def __repr__(self): return 'Area(%s=%s)' % (self._default_unit, getattr(self, self._default_unit)) def __str__(self): return '%s %s' % (getattr(self, self._default_unit), self._default_unit) def __cmp__(self, other): if isinstance(other, Area): return cmp(self.sq_m, other.sq_m) else: return NotImplemented def __add__(self, other): if isinstance(other, Area): return Area(default_unit=self._default_unit, sq_m=(self.sq_m + other.sq_m)) else: raise TypeError('Area must be added with Area') def __iadd__(self, other): if isinstance(other, Area): self.sq_m += other.sq_m return self else: raise TypeError('Area must be added with Area') def __sub__(self, other): if isinstance(other, Area): return Area(default_unit=self._default_unit, sq_m=(self.sq_m - other.sq_m)) else: raise TypeError('Area must be subtracted from Area') def __isub__(self, other): if isinstance(other, Area): self.sq_m -= other.sq_m return self else: raise TypeError('Area must be subtracted from Area') def __mul__(self, other): if isinstance(other, (int, float, long, Decimal)): return Area(default_unit=self._default_unit, sq_m=(self.sq_m * float(other))) else: raise TypeError('Area must be multiplied with number') def __imul__(self, other): if isinstance(other, (int, float, long, Decimal)): self.sq_m *= float(other) return self else: raise TypeError('Area must be multiplied with number') def __rmul__(self, other): return self * other def __div__(self, other): if isinstance(other, (int, float, long, Decimal)): return Area(default_unit=self._default_unit, sq_m=(self.sq_m / float(other))) else: raise TypeError('Area must be divided with number') def __idiv__(self, other): if isinstance(other, (int, float, long, Decimal)): self.sq_m /= float(other) return self else: raise TypeError('Area must be divided with number') def __nonzero__(self): return bool(self.sq_m) # Shortcuts D = Distance A = Area
gpl-3.0
mwgoldsmith/kate
tools/KateDJ/kdj/demuxer.py
3
1808
import sys import os import tempfile from tools import Tools class Demuxer: def __init__(self,tools,filename,type): if not self.CreateDirectory(): raise Exception, 'Failed to create directory' self.Demux(tools,filename,type) def GetDirectory(self): return self.directory def CreateDirectory(self): try: self.directory=tempfile.mkdtemp(dir='.',prefix='katedj-tmp-extract-') except OSError,e: return False return True def GetCodecs(self,tools): cmdline=tools.codecs_command if cmdline!=None: try: popen=subprocess.Popen(cmdline,stdin=None,stderr=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True,shell=True) if popen.stdout: list=[] line=popen.stdout.readline() while line: line=line.split('\n')[0] if line and 'Kate' not in line: list.append(line) line=popen.stdout.readline() popen.stdout.close() return list except: pass return ['theora','vorbis','dirac','speex','flac','cmml'] def DemuxMisc(self,tools,filename): params=[] params+=['-o',os.path.join(self.directory,'misc.ogg')] for codec in self.GetCodecs(tools): params+=['-c',codec] params+=[filename] tools.run_demux(params) def DemuxKate(self,tools,filename,type): params=[] params+=['-o',os.path.join(self.directory,'kate.%l.%c.%i.%s.kate')] params+=['-t',type] params+=[filename] tools.run_katedec(params) def Demux(self,tools,filename,type): self.DemuxMisc(tools,filename) self.DemuxKate(tools,filename,type) if __name__=='__main__': tools=Tools() file='../../built-streams/demo.ogg' if len(sys.argv)>1: file=sys.argv[1]; demuxer=Demuxer(tools,file)
bsd-3-clause
okuta/chainer
chainermn/communicators/__init__.py
1
5547
from chainermn.communicators.communicator_base import CommunicatorBase # NOQA def create_communicator( communicator_name='pure_nccl', mpi_comm=None, allreduce_grad_dtype=None, batched_copy=False): """Create a ChainerMN communicator. Different communicators provide different approaches of communication, so they have different performance charasteristics. The default communicator ``pure_nccl`` is expected to generally perform well on a variety of environments, so one need not to change communicators in most cases. However, you may need to choose other communicators depending on your computing platform and the availability of NCCL library. The following communicators are available. +---------------+---+---+--------+--------------------------------------+ |Name |CPU|GPU|NCCL |Recommended Use Cases | +===============+===+===+========+======================================+ |pure_nccl | |OK |Required|``pure_nccl`` is recommended when | | | | |(>= v2) |NCCL2 is available in the environment.| +---------------+---+---+--------+--------------------------------------+ |flat | |OK | |N/A | +---------------+---+---+--------+--------------------------------------+ |naive |OK |OK | |Testing on CPU mode | +---------------+---+---+--------+--------------------------------------+ pure_nccl communicator supports multiple data types, FP32 and FP16, in gradient exchange. The communication data type is determined based on `chainer.global_config.dtype` and `allreduce_grad_dtype`. When `allreduce_grad_dtype` is the default value `None`, FP32 is used when `chainer.global_config.dtype` is `numpy.float32` and FP16 otherwise. `allreduce_grad_dtype` parameter, which is either `numpy.float16` or `numpy.float32`, overwrites the `chainer.global_config.dtype`. The table blow summarizes the data type selection in gradient exchange. +---------------------+--------------------------------------------+ | | allreduce_grad_dtype | +---------------------+---------+------------------+---------------+ | global_config.dtype | None | numpy.float16 | numpy.float32 | +=====================+=========+==================+===============+ | chainer.mixed16 | FP16 | FP16 | FP32 | +---------------------+---------+------------------+---------------+ | numpy.float16 | FP16 | FP16 | FP32 | +---------------------+---------+------------------+---------------+ | numpy.float32 | FP32 | FP16 | FP32 | +---------------------+---------+------------------+---------------+ Other communicators, namely ``flat`` and ``naive``, support only float32 communication, no matter what the model is. This is due to MPI's limited support of float16. Args: communicator_name: The name of communicator (``naive``, ``flat``, or ``pure_nccl``) mpi_comm: MPI4py communicator allreduce_grad_dtype: Data type of gradient used in All-Reduce. If ``None``, the dtype of a model is used. Returns: ChainerMN communicator that implements methods defined in :class:`chainermn.CommunicatorBase` """ if mpi_comm is None: try: import mpi4py.MPI except ImportError as e: raise ImportError(str(e) + ': ' 'ChainerMN requires mpi4py for ' 'distributed training. ' 'Please read the Chainer official document ' 'and setup MPI and mpi4py.') mpi_comm = mpi4py.MPI.COMM_WORLD if communicator_name != 'pure_nccl' and allreduce_grad_dtype is not None: raise ValueError( 'allreduce_grad_dtype is only available' 'at \'pure_nccl\' communicator.') if communicator_name != 'pure_nccl' and batched_copy: raise ValueError( 'batched_copy is only available' 'at \'pure_nccl\' communicator.') if communicator_name == 'naive': from chainermn.communicators.naive_communicator \ import NaiveCommunicator return NaiveCommunicator(mpi_comm=mpi_comm) elif communicator_name == 'flat': from chainermn.communicators.flat_communicator \ import FlatCommunicator return FlatCommunicator(mpi_comm=mpi_comm) elif communicator_name == 'non_cuda_aware': from chainermn.communicators.non_cuda_aware_communicator \ import NonCudaAwareCommunicator return NonCudaAwareCommunicator(mpi_comm=mpi_comm) elif communicator_name == 'pure_nccl': from chainermn.communicators.pure_nccl_communicator \ import PureNcclCommunicator return PureNcclCommunicator(mpi_comm=mpi_comm, allreduce_grad_dtype=allreduce_grad_dtype, batched_copy=batched_copy) elif communicator_name == 'dummy': from chainermn.communicators.dummy_communicator \ import DummyCommunicator return DummyCommunicator(mpi_comm=mpi_comm) else: raise ValueError( 'Unrecognized communicator: "{}"'.format(communicator_name))
mit
apanda/phantomjs-intercept
src/qt/qtwebkit/Tools/Scripts/webkitpy/style/checkers/png.py
170
3914
# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged # # 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 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. """Supports checking WebKit style in png files.""" import os import re from webkitpy.common import checksvnconfigfile from webkitpy.common import read_checksum_from_png from webkitpy.common.system.systemhost import SystemHost from webkitpy.common.checkout.scm.detection import SCMDetector class PNGChecker(object): """Check svn:mime-type for checking style""" categories = set(['image/png']) def __init__(self, file_path, handle_style_error, scm=None, host=None): self._file_path = file_path self._handle_style_error = handle_style_error self._host = host or SystemHost() self._fs = self._host.filesystem self._detector = scm or SCMDetector(self._fs, self._host.executive).detect_scm_system(self._fs.getcwd()) def check(self, inline=None): errorstr = "" config_file_path = "" detection = self._detector.display_name() if self._fs.exists(self._file_path) and self._file_path.endswith("-expected.png"): with self._fs.open_binary_file_for_reading(self._file_path) as filehandle: if not read_checksum_from_png.read_checksum(filehandle): self._handle_style_error(0, 'image/png', 5, "Image lacks a checksum. Generate pngs using run-webkit-tests to ensure they have a checksum.") if detection == "git": (file_missing, autoprop_missing, png_missing) = checksvnconfigfile.check(self._host, self._fs) config_file_path = checksvnconfigfile.config_file_path(self._host, self._fs) if file_missing: self._handle_style_error(0, 'image/png', 5, "There is no SVN config file. (%s)" % config_file_path) elif autoprop_missing and png_missing: self._handle_style_error(0, 'image/png', 5, checksvnconfigfile.errorstr_autoprop(config_file_path) + checksvnconfigfile.errorstr_png(config_file_path)) elif autoprop_missing: self._handle_style_error(0, 'image/png', 5, checksvnconfigfile.errorstr_autoprop(config_file_path)) elif png_missing: self._handle_style_error(0, 'image/png', 5, checksvnconfigfile.errorstr_png(config_file_path)) elif detection == "svn": prop_get = self._detector.propget("svn:mime-type", self._file_path) if prop_get != "image/png": errorstr = "Set the svn:mime-type property (svn propset svn:mime-type image/png %s)." % self._file_path self._handle_style_error(0, 'image/png', 5, errorstr)
bsd-3-clause
bertrand-l/numpy
numpy/distutils/command/autodist.py
148
2048
"""This module implements additional tests ala autoconf which can be useful. """ from __future__ import division, absolute_import, print_function # We put them here since they could be easily reused outside numpy.distutils def check_inline(cmd): """Return the inline identifier (may be empty).""" cmd._check_compiler() body = """ #ifndef __cplusplus static %(inline)s int static_func (void) { return 0; } %(inline)s int nostatic_func (void) { return 0; } #endif""" for kw in ['inline', '__inline__', '__inline']: st = cmd.try_compile(body % {'inline': kw}, None, None) if st: return kw return '' def check_restrict(cmd): """Return the restrict identifier (may be empty).""" cmd._check_compiler() body = """ static int static_func (char * %(restrict)s a) { return 0; } """ for kw in ['restrict', '__restrict__', '__restrict']: st = cmd.try_compile(body % {'restrict': kw}, None, None) if st: return kw return '' def check_compiler_gcc4(cmd): """Return True if the C compiler is GCC 4.x.""" cmd._check_compiler() body = """ int main() { #if (! defined __GNUC__) || (__GNUC__ < 4) #error gcc >= 4 required #endif return 0; } """ return cmd.try_compile(body, None, None) def check_gcc_function_attribute(cmd, attribute, name): """Return True if the given function attribute is supported.""" cmd._check_compiler() body = """ #pragma GCC diagnostic error "-Wattributes" #pragma clang diagnostic error "-Wattributes" int %s %s(void*); int main() { return 0; } """ % (attribute, name) return cmd.try_compile(body, None, None) != 0 def check_gcc_variable_attribute(cmd, attribute): """Return True if the given variable attribute is supported.""" cmd._check_compiler() body = """ #pragma GCC diagnostic error "-Wattributes" #pragma clang diagnostic error "-Wattributes" int %s foo; int main() { return 0; } """ % (attribute, ) return cmd.try_compile(body, None, None) != 0
bsd-3-clause
ramitalat/odoo
addons/account/wizard/account_report_general_ledger.py
267
3191
# -*- 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 openerp.osv import fields, osv class account_report_general_ledger(osv.osv_memory): _inherit = "account.common.account.report" _name = "account.report.general.ledger" _description = "General Ledger Report" _columns = { 'landscape': fields.boolean("Landscape Mode"), 'initial_balance': fields.boolean('Include Initial Balances', help='If you selected to filter by date or period, this field allow you to add a row to display the amount of debit/credit/balance that precedes the filter you\'ve set.'), 'amount_currency': fields.boolean("With Currency", help="It adds the currency column on report if the currency differs from the company currency."), 'sortby': fields.selection([('sort_date', 'Date'), ('sort_journal_partner', 'Journal & Partner')], 'Sort by', required=True), 'journal_ids': fields.many2many('account.journal', 'account_report_general_ledger_journal_rel', 'account_id', 'journal_id', 'Journals', required=True), } _defaults = { 'landscape': True, 'amount_currency': True, 'sortby': 'sort_date', 'initial_balance': False, } def onchange_fiscalyear(self, cr, uid, ids, fiscalyear=False, context=None): res = {} if not fiscalyear: res['value'] = {'initial_balance': False} return res def _print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data = self.pre_print_report(cr, uid, ids, data, context=context) data['form'].update(self.read(cr, uid, ids, ['landscape', 'initial_balance', 'amount_currency', 'sortby'])[0]) if not data['form']['fiscalyear_id']:# GTK client problem onchange does not consider in save record data['form'].update({'initial_balance': False}) if data['form']['landscape'] is False: data['form'].pop('landscape') else: context['landscape'] = data['form']['landscape'] return self.pool['report'].get_action(cr, uid, [], 'account.report_generalledger', data=data, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
jumping/Diamond
src/diamond/handler/stats_d.py
20
4833
# coding=utf-8 """ Implements the abstract Handler class, sending data to statsd. This is a UDP service, sending datagrams. They may be lost. It's OK. #### Dependencies * [statsd](https://pypi.python.org/pypi/statsd/) v2.0.0 or newer. * A compatible implementation of [statsd](https://github.com/etsy/statsd) #### Configuration Enable this handler * handlers = diamond.handler.stats_d.StatsdHandler #### Notes The handler file is named an odd stats_d.py because of an import issue with having the python library called statsd and this handler's module being called statsd, so we use an odd name for this handler. This doesn't affect the usage of this handler. """ from Handler import Handler import logging try: import statsd except ImportError: statsd = None class StatsdHandler(Handler): def __init__(self, config=None): """ Create a new instance of the StatsdHandler class """ # Initialize Handler Handler.__init__(self, config) logging.debug("Initialized statsd handler.") if not statsd: self.log.error('statsd import failed. Handler disabled') self.enabled = False return if not hasattr(statsd, 'StatsClient'): self.log.warn('python-statsd support is deprecated ' 'and will be removed in the future. ' 'Please use https://pypi.python.org/pypi/statsd/') # Initialize Options self.host = self.config['host'] self.port = int(self.config['port']) self.batch_size = int(self.config['batch']) self.metrics = [] self.old_values = {} # Connect self._connect() def get_default_config_help(self): """ Returns the help text for the configuration options for this handler """ config = super(StatsdHandler, self).get_default_config_help() config.update({ 'host': '', 'port': '', 'batch': '', }) return config def get_default_config(self): """ Return the default config for the handler """ config = super(StatsdHandler, self).get_default_config() config.update({ 'host': '', 'port': 1234, 'batch': 1, }) return config def process(self, metric): """ Process a metric by sending it to statsd """ self.metrics.append(metric) if len(self.metrics) >= self.batch_size: self._send() def _send(self): """ Send data to statsd. Fire and forget. Cross fingers and it'll arrive. """ if not statsd: return for metric in self.metrics: # Split the path into a prefix and a name # to work with the statsd module's view of the world. # It will get re-joined by the python-statsd module. # # For the statsd module, you specify prefix in the constructor # so we just use the full metric path. (prefix, name) = metric.path.rsplit(".", 1) logging.debug("Sending %s %s|g", name, metric.value) if metric.metric_type == 'GAUGE': if hasattr(statsd, 'StatsClient'): self.connection.gauge(metric.path, metric.value) else: statsd.Gauge(prefix, self.connection).send( name, metric.value) else: # To send a counter, we need to just send the delta # but without any time delta changes value = metric.raw_value if metric.path in self.old_values: value = value - self.old_values[metric.path] self.old_values[metric.path] = metric.raw_value if hasattr(statsd, 'StatsClient'): self.connection.incr(metric.path, value) else: statsd.Counter(prefix, self.connection).increment( name, value) if hasattr(statsd, 'StatsClient'): self.connection.send() self.metrics = [] def flush(self): """Flush metrics in queue""" self._send() def _connect(self): """ Connect to the statsd server """ if not statsd: return if hasattr(statsd, 'StatsClient'): self.connection = statsd.StatsClient( host=self.host, port=self.port ).pipeline() else: # Create socket self.connection = statsd.Connection( host=self.host, port=self.port, sample_rate=1.0 )
mit
MQQiang/kbengine
kbe/src/lib/python/Lib/test/test_largefile.py
96
6554
"""Test largefile support on system where this makes sense. """ import os import stat import sys import unittest from test.support import TESTFN, requires, unlink import io # C implementation of io import _pyio as pyio # Python implementation of io # size of file to create (>2GB; 2GB == 2147483648 bytes) size = 2500000000 class LargeFileTest: """Test that each file function works as expected for large (i.e. > 2GB) files. """ def setUp(self): if os.path.exists(TESTFN): mode = 'r+b' else: mode = 'w+b' with self.open(TESTFN, mode) as f: current_size = os.fstat(f.fileno())[stat.ST_SIZE] if current_size == size+1: return if current_size == 0: f.write(b'z') f.seek(0) f.seek(size) f.write(b'a') f.flush() self.assertEqual(os.fstat(f.fileno())[stat.ST_SIZE], size+1) @classmethod def tearDownClass(cls): with cls.open(TESTFN, 'wb'): pass if not os.stat(TESTFN)[stat.ST_SIZE] == 0: raise cls.failureException('File was not truncated by opening ' 'with mode "wb"') def test_osstat(self): self.assertEqual(os.stat(TESTFN)[stat.ST_SIZE], size+1) def test_seek_read(self): with self.open(TESTFN, 'rb') as f: self.assertEqual(f.tell(), 0) self.assertEqual(f.read(1), b'z') self.assertEqual(f.tell(), 1) f.seek(0) self.assertEqual(f.tell(), 0) f.seek(0, 0) self.assertEqual(f.tell(), 0) f.seek(42) self.assertEqual(f.tell(), 42) f.seek(42, 0) self.assertEqual(f.tell(), 42) f.seek(42, 1) self.assertEqual(f.tell(), 84) f.seek(0, 1) self.assertEqual(f.tell(), 84) f.seek(0, 2) # seek from the end self.assertEqual(f.tell(), size + 1 + 0) f.seek(-10, 2) self.assertEqual(f.tell(), size + 1 - 10) f.seek(-size-1, 2) self.assertEqual(f.tell(), 0) f.seek(size) self.assertEqual(f.tell(), size) # the 'a' that was written at the end of file above self.assertEqual(f.read(1), b'a') f.seek(-size-1, 1) self.assertEqual(f.read(1), b'z') self.assertEqual(f.tell(), 1) def test_lseek(self): with self.open(TESTFN, 'rb') as f: self.assertEqual(os.lseek(f.fileno(), 0, 0), 0) self.assertEqual(os.lseek(f.fileno(), 42, 0), 42) self.assertEqual(os.lseek(f.fileno(), 42, 1), 84) self.assertEqual(os.lseek(f.fileno(), 0, 1), 84) self.assertEqual(os.lseek(f.fileno(), 0, 2), size+1+0) self.assertEqual(os.lseek(f.fileno(), -10, 2), size+1-10) self.assertEqual(os.lseek(f.fileno(), -size-1, 2), 0) self.assertEqual(os.lseek(f.fileno(), size, 0), size) # the 'a' that was written at the end of file above self.assertEqual(f.read(1), b'a') def test_truncate(self): with self.open(TESTFN, 'r+b') as f: if not hasattr(f, 'truncate'): raise unittest.SkipTest("open().truncate() not available " "on this system") f.seek(0, 2) # else we've lost track of the true size self.assertEqual(f.tell(), size+1) # Cut it back via seek + truncate with no argument. newsize = size - 10 f.seek(newsize) f.truncate() self.assertEqual(f.tell(), newsize) # else pointer moved f.seek(0, 2) self.assertEqual(f.tell(), newsize) # else wasn't truncated # Ensure that truncate(smaller than true size) shrinks # the file. newsize -= 1 f.seek(42) f.truncate(newsize) self.assertEqual(f.tell(), 42) f.seek(0, 2) self.assertEqual(f.tell(), newsize) # XXX truncate(larger than true size) is ill-defined # across platform; cut it waaaaay back f.seek(0) f.truncate(1) self.assertEqual(f.tell(), 0) # else pointer moved f.seek(0) self.assertEqual(len(f.read()), 1) # else wasn't truncated def test_seekable(self): # Issue #5016; seekable() can return False when the current position # is negative when truncated to an int. for pos in (2**31-1, 2**31, 2**31+1): with self.open(TESTFN, 'rb') as f: f.seek(pos) self.assertTrue(f.seekable()) def setUpModule(): try: import signal # The default handler for SIGXFSZ is to abort the process. # By ignoring it, system calls exceeding the file size resource # limit will raise OSError instead of crashing the interpreter. signal.signal(signal.SIGXFSZ, signal.SIG_IGN) except (ImportError, AttributeError): pass # On Windows and Mac OSX this test comsumes large resources; It # takes a long time to build the >2GB file and takes >2GB of disk # space therefore the resource must be enabled to run this test. # If not, nothing after this line stanza will be executed. if sys.platform[:3] == 'win' or sys.platform == 'darwin': requires('largefile', 'test requires %s bytes and a long time to run' % str(size)) else: # Only run if the current filesystem supports large files. # (Skip this test on Windows, since we now always support # large files.) f = open(TESTFN, 'wb', buffering=0) try: # 2**31 == 2147483648 f.seek(2147483649) # Seeking is not enough of a test: you must write and flush, too! f.write(b'x') f.flush() except (OSError, OverflowError): raise unittest.SkipTest("filesystem does not have " "largefile support") finally: f.close() unlink(TESTFN) class CLargeFileTest(LargeFileTest, unittest.TestCase): open = staticmethod(io.open) class PyLargeFileTest(LargeFileTest, unittest.TestCase): open = staticmethod(pyio.open) def tearDownModule(): unlink(TESTFN) if __name__ == '__main__': unittest.main()
lgpl-3.0
barnsnake351/nova
nova/api/auth.py
9
5830
# Copyright (c) 2011 OpenStack Foundation # # 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. """ Common Auth Middleware. """ from oslo_config import cfg from oslo_log import log as logging from oslo_middleware import request_id from oslo_serialization import jsonutils import webob.dec import webob.exc from nova import context from nova.i18n import _ from nova import wsgi auth_opts = [ cfg.BoolOpt('api_rate_limit', default=False, help='Whether to use per-user rate limiting for the api. ' 'This option is only used by v2 api. Rate limiting ' 'is removed from v3 api.'), cfg.StrOpt('auth_strategy', default='keystone', help=''' The strategy to use for auth: keystone or noauth2. noauth2 is designed for testing only, as it does no actual credential checking. noauth2 provides administrative credentials only if 'admin' is specified as the username. '''), cfg.BoolOpt('use_forwarded_for', default=False, help='Treat X-Forwarded-For as the canonical remote address. ' 'Only enable this if you have a sanitizing proxy.'), ] CONF = cfg.CONF CONF.register_opts(auth_opts) LOG = logging.getLogger(__name__) def _load_pipeline(loader, pipeline): filters = [loader.get_filter(n) for n in pipeline[:-1]] app = loader.get_app(pipeline[-1]) filters.reverse() for filter in filters: app = filter(app) return app def pipeline_factory(loader, global_conf, **local_conf): """A paste pipeline replica that keys off of auth_strategy.""" pipeline = local_conf[CONF.auth_strategy] if not CONF.api_rate_limit: limit_name = CONF.auth_strategy + '_nolimit' pipeline = local_conf.get(limit_name, pipeline) pipeline = pipeline.split() return _load_pipeline(loader, pipeline) def pipeline_factory_v21(loader, global_conf, **local_conf): """A paste pipeline replica that keys off of auth_strategy.""" return _load_pipeline(loader, local_conf[CONF.auth_strategy].split()) # NOTE(oomichi): This pipeline_factory_v3 is for passing check-grenade-dsvm. pipeline_factory_v3 = pipeline_factory_v21 class InjectContext(wsgi.Middleware): """Add a 'nova.context' to WSGI environ.""" def __init__(self, context, *args, **kwargs): self.context = context super(InjectContext, self).__init__(*args, **kwargs) @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): req.environ['nova.context'] = self.context return self.application class NovaKeystoneContext(wsgi.Middleware): """Make a request context from keystone headers.""" @webob.dec.wsgify(RequestClass=wsgi.Request) def __call__(self, req): user_id = req.headers.get('X_USER') user_id = req.headers.get('X_USER_ID', user_id) if user_id is None: LOG.debug("Neither X_USER_ID nor X_USER found in request") return webob.exc.HTTPUnauthorized() roles = self._get_roles(req) if 'X_TENANT_ID' in req.headers: # This is the new header since Keystone went to ID/Name project_id = req.headers['X_TENANT_ID'] else: # This is for legacy compatibility project_id = req.headers['X_TENANT'] project_name = req.headers.get('X_TENANT_NAME') user_name = req.headers.get('X_USER_NAME') req_id = req.environ.get(request_id.ENV_REQUEST_ID) # Get the auth token auth_token = req.headers.get('X_AUTH_TOKEN', req.headers.get('X_STORAGE_TOKEN')) # Build a context, including the auth_token... remote_address = req.remote_addr if CONF.use_forwarded_for: remote_address = req.headers.get('X-Forwarded-For', remote_address) service_catalog = None if req.headers.get('X_SERVICE_CATALOG') is not None: try: catalog_header = req.headers.get('X_SERVICE_CATALOG') service_catalog = jsonutils.loads(catalog_header) except ValueError: raise webob.exc.HTTPInternalServerError( _('Invalid service catalog json.')) # NOTE(jamielennox): This is a full auth plugin set by auth_token # middleware in newer versions. user_auth_plugin = req.environ.get('keystone.token_auth') ctx = context.RequestContext(user_id, project_id, user_name=user_name, project_name=project_name, roles=roles, auth_token=auth_token, remote_address=remote_address, service_catalog=service_catalog, request_id=req_id, user_auth_plugin=user_auth_plugin) req.environ['nova.context'] = ctx return self.application def _get_roles(self, req): """Get the list of roles.""" roles = req.headers.get('X_ROLES', '') return [r.strip() for r in roles.split(',')]
apache-2.0
mSenyor/kivy
kivy/uix/image.py
1
11853
''' Image ===== The :class:`Image` widget is used to display an image:: wimg = Image(source='mylogo.png') Asynchronous Loading -------------------- To load an image asynchronously (for example from an external webserver), use the :class:`AsyncImage` subclass:: aimg = AsyncImage(source='http://mywebsite.com/logo.png') This can be useful as it prevents your application from waiting until the image is loaded. If you want to display large images or retrieve them from URL's, using :class:`AsyncImage` will allow these resources to be retrieved on a background thread without blocking your application. Alignment --------- By default, the image is centered and fits inside the widget bounding box. If you don't want that, you can set `allow_stretch` to True and `keep_ratio` to False. You can also inherit from Image and create your own style. For example, if you want your image to be greater than,the size of your widget, you could do:: class FullImage(Image): pass And in your kivy language file:: <-FullImage>: canvas: Color: rgb: (1, 1, 1) Rectangle: texture: self.texture size: self.width + 20, self.height + 20 pos: self.x - 10, self.y - 10 ''' __all__ = ('Image', 'AsyncImage') from kivy.uix.widget import Widget from kivy.core.image import Image as CoreImage from kivy.resources import resource_find from kivy.properties import StringProperty, ObjectProperty, ListProperty, \ AliasProperty, BooleanProperty, NumericProperty from kivy.logger import Logger # delayed imports Loader = None class Image(Widget): '''Image class, see module documentation for more information. ''' source = StringProperty(None) '''Filename / source of your image. :attr:`source` is a :class:`~kivy.properties.StringProperty` and defaults to None. ''' texture = ObjectProperty(None, allownone=True) '''Texture object of the image. The texture represents the original, loaded image texture. It is streched and positioned during rendering according to the :attr:`allow_stretch` and :attr:`keep_ratio` properties. Depending of the texture creation, the value will be a :class:`~kivy.graphics.texture.Texture` or a :class:`~kivy.graphics.texture.TextureRegion` object. :attr:`texture` is a :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' texture_size = ListProperty([0, 0]) '''Texture size of the image. This represents the original, loaded image texture size. .. warning:: The texture size is set after the texture property. So if you listen to the change on :attr:`texture`, the property texture_size will not be up-to-date. Use self.texture.size instead. ''' def get_image_ratio(self): if self.texture: return self.texture.width / float(self.texture.height) return 1. mipmap = BooleanProperty(False) '''Indicate if you want OpenGL mipmapping to be applied to the texture. Read :ref:`mipmap` for more information. .. versionadded:: 1.0.7 :attr:`mipmap` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' image_ratio = AliasProperty(get_image_ratio, None, bind=('texture', )) '''Ratio of the image (width / float(height). :attr:`image_ratio` is a :class:`~kivy.properties.AliasProperty` and is read-only. ''' color = ListProperty([1, 1, 1, 1]) '''Image color, in the format (r, g, b, a). This attribute can be used to 'tint' an image. Be careful: if the source image is not gray/white, the color will not really work as expected. .. versionadded:: 1.0.6 :attr:`color` is a :class:`~kivy.properties.ListProperty` and defaults to [1, 1, 1, 1]. ''' allow_stretch = BooleanProperty(False) '''If True, the normalized image size will be maximized to fit in the image box. Otherwise, if the box is too tall, the image will not be stretched more than 1:1 pixels. .. versionadded:: 1.0.7 :attr:`allow_stretch` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' keep_ratio = BooleanProperty(True) '''If False along with allow_stretch being True, the normalized image size will be maximized to fit in the image box and ignores the aspect ratio of the image. Otherwise, if the box is too tall, the image will not be stretched more than 1:1 pixels. .. versionadded:: 1.0.8 :attr:`keep_ratio` is a :class:`~kivy.properties.BooleanProperty` and defaults to True. ''' keep_data = BooleanProperty(False) '''If True, the underlaying _coreimage will store the raw image data. This is useful when performing pixel based collision detection. .. versionadded:: 1.3.0 :attr:`keep_data` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' anim_delay = NumericProperty(.25) '''Delay the animation if the image is sequenced (like an animated gif). If anim_delay is set to -1, the animation will be stopped. .. versionadded:: 1.0.8 :attr:`anim_delay` is a :class:`~kivy.properties.NumericProperty` and defaults to 0.25 (4 FPS). ''' anim_loop = NumericProperty(0) '''Number of loops to play then stop animating. 0 means keep animating. .. versionadded:: 1.9.0 :attr:`anim_loop` is a :class:`~kivy.properties.NumericProperty` defaults to 0. ''' nocache = BooleanProperty(False) '''If this property is set True, the image will not be added to the internal cache. The cache will simply ignore any calls trying to append the core image. .. versionadded:: 1.6.0 :attr:`nocache` is a :class:`~kivy.properties.BooleanProperty` and defaults to False. ''' def get_norm_image_size(self): if not self.texture: return self.size ratio = self.image_ratio w, h = self.size tw, th = self.texture.size # ensure that the width is always maximized to the containter width if self.allow_stretch: if not self.keep_ratio: return w, h iw = w else: iw = min(w, tw) # calculate the appropriate height ih = iw / ratio # if the height is too higher, take the height of the container # and calculate appropriate width. no need to test further. :) if ih > h: if self.allow_stretch: ih = h else: ih = min(h, th) iw = ih * ratio return iw, ih norm_image_size = AliasProperty(get_norm_image_size, None, bind=( 'texture', 'size', 'image_ratio', 'allow_stretch')) '''Normalized image size within the widget box. This size will always fit the widget size and will preserve the image ratio. :attr:`norm_image_size` is a :class:`~kivy.properties.AliasProperty` and is read-only. ''' def __init__(self, **kwargs): self._coreimage = None self._loops = 0 super(Image, self).__init__(**kwargs) fbind = self.fbind update = self.texture_update fbind('source', update) fbind('mipmap', update) if self.source: update() self.on_anim_delay(self, kwargs.get('anim_delay', .25)) def texture_update(self, *largs): if not self.source: self.texture = None else: filename = resource_find(self.source) self._loops = 0 if filename is None: return Logger.error('Image: Error reading file {filename}'. format(filename=self.source)) mipmap = self.mipmap if self._coreimage is not None: self._coreimage.unbind(on_texture=self._on_tex_change) try: self._coreimage = ci = CoreImage(filename, mipmap=mipmap, anim_delay=self.anim_delay, keep_data=self.keep_data, nocache=self.nocache) except: self._coreimage = ci = None if ci: ci.bind(on_texture=self._on_tex_change) self.texture = ci.texture def on_anim_delay(self, instance, value): self._loop = 0 if self._coreimage is None: return self._coreimage.anim_delay = value if value < 0: self._coreimage.anim_reset(False) def on_texture(self, instance, value): if value is not None: self.texture_size = list(value.size) def _on_tex_change(self, *largs): # update texture from core image self.texture = self._coreimage.texture ci = self._coreimage if self.anim_loop and ci._anim_index == len(ci._image.textures) - 1: self._loops += 1 if self.anim_loop == self._loops: ci.anim_reset(False) self._loops = 0 def reload(self): '''Reload image from disk. This facilitates re-loading of images from disk in case the image content changes. .. versionadded:: 1.3.0 Usage:: im = Image(source = '1.jpg') # -- do something -- im.reload() # image will be re-loaded from disk ''' try: self._coreimage.remove_from_cache() except AttributeError: pass olsource = self.source self.source = '' self.source = olsource def on_nocache(self, *args): if self.nocache and self._coreimage: self._coreimage.remove_from_cache() self._coreimage._nocache = True class AsyncImage(Image): '''Asynchronous Image class. See the module documentation for more information. .. note:: The AsyncImage is a specialized form of the Image class. You may want to refer to the :mod:`~kivy.loader` documentation and in particular, the :class:`~kivy.loader.ProxyImage` for more detail on how to handle events around asynchronous image loading. ''' def __init__(self, **kwargs): self._coreimage = None super(AsyncImage, self).__init__(**kwargs) global Loader if not Loader: from kivy.loader import Loader self.fbind('source', self._load_source) if self.source: self._load_source() self.on_anim_delay(self, kwargs.get('anim_delay', .25)) def _load_source(self, *args): source = self.source if not source: if self._coreimage is not None: self._coreimage.unbind(on_texture=self._on_tex_change) self.texture = None self._coreimage = None else: if not self.is_uri(source): source = resource_find(source) self._coreimage = image = Loader.image(source, nocache=self.nocache, mipmap=self.mipmap, anim_delay=self.anim_delay) image.bind(on_load=self._on_source_load) image.bind(on_texture=self._on_tex_change) self.texture = image.texture def _on_source_load(self, value): image = self._coreimage.image if not image: return self.texture = image.texture def is_uri(self, filename): proto = filename.split('://', 1)[0] return proto in ('http', 'https', 'ftp', 'smb') def _on_tex_change(self, *largs): if self._coreimage: self.texture = self._coreimage.texture def texture_update(self, *largs): pass
mit
kerlw/POSTMan-Chrome-Extension
proxy/proxy_server.py
102
3014
#!/usr/bin/python from twisted.internet import reactor from twisted.web import http from twisted.web.proxy import Proxy, ProxyRequest, ProxyClientFactory, ProxyClient from ImageFile import Parser from StringIO import StringIO class InterceptingProxyClient(ProxyClient): def __init__(self, *args, **kwargs): ProxyClient.__init__(self, *args, **kwargs) self.overrides = [] self.restricted_headers = [ 'accept-charset', 'accept-encoding', 'access-control-request-headers', 'access-control-request-method', 'connection', 'content-length', 'cookie', 'cookie2', 'content-transfer-encoding', 'date', 'expect', 'host', 'keep-alive', 'origin', 'referer', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'user-agent', 'via' ] self.all_headers = [] self.unsent_restricted_headers = [] def sendHeader(self, name, value): if "postman-" in name: new_header = name[8:] print "Header %s, %s, %s" % (name, value, new_header) name = new_header header = { "name": name, "value": value } self.all_headers.append(name) ProxyClient.sendHeader(self, name, value) elif name in self.restricted_headers: header = { "name": name, "value": value } print "Restricted header %s" % name self.unsent_restricted_headers.append(header) else: ProxyClient.sendHeader(self, name, value) def endHeaders(self): for header in self.unsent_restricted_headers: if not header["name"] in self.all_headers: ProxyClient.sendHeader(self, header["name"], header["value"]) ProxyClient.endHeaders(self) def handleHeader(self, key, value): # change response header here print("Header: %s: %s" % (key, value)) l = key.lower() if l == "location": key = "Postman-Location" ProxyClient.handleHeader(self, key, value) def handleResponseEnd(self): if not self._finished: self.father.responseHeaders.setRawHeaders("client", ["location"]) ProxyClient.handleResponseEnd(self) class InterceptingProxyClientFactory(ProxyClientFactory): protocol = InterceptingProxyClient class InterceptingProxyRequest(ProxyRequest): protocols = {'http': InterceptingProxyClientFactory, 'https': InterceptingProxyClientFactory} class InterceptingProxy(Proxy): requestFactory = InterceptingProxyRequest factory = http.HTTPFactory() factory.protocol = InterceptingProxy port = 8000 reactor.listenTCP(8000, factory) reactor.run() print "Listening on port %d" % port
apache-2.0
heeraj123/oh-mainline
vendor/packages/twisted/doc/mail/examples/smtpclient_tls.py
22
4733
""" Demonstrate sending mail via SMTP while employing TLS and performing authentication. """ import sys from OpenSSL.SSL import SSLv3_METHOD from twisted.mail.smtp import ESMTPSenderFactory from twisted.python.usage import Options, UsageError from twisted.internet.ssl import ClientContextFactory from twisted.internet.defer import Deferred from twisted.internet import reactor def sendmail( authenticationUsername, authenticationSecret, fromAddress, toAddress, messageFile, smtpHost, smtpPort=25 ): """ @param authenticationUsername: The username with which to authenticate. @param authenticationSecret: The password with which to authenticate. @param fromAddress: The SMTP reverse path (ie, MAIL FROM) @param toAddress: The SMTP forward path (ie, RCPT TO) @param messageFile: A file-like object containing the headers and body of the message to send. @param smtpHost: The MX host to which to connect. @param smtpPort: The port number to which to connect. @return: A Deferred which will be called back when the message has been sent or which will errback if it cannot be sent. """ # Create a context factory which only allows SSLv3 and does not verify # the peer's certificate. contextFactory = ClientContextFactory() contextFactory.method = SSLv3_METHOD resultDeferred = Deferred() senderFactory = ESMTPSenderFactory( authenticationUsername, authenticationSecret, fromAddress, toAddress, messageFile, resultDeferred, contextFactory=contextFactory) reactor.connectTCP(smtpHost, smtpPort, senderFactory) return resultDeferred class SendmailOptions(Options): synopsis = "smtpclient_tls.py [options]" optParameters = [ ('username', 'u', None, 'The username with which to authenticate to the SMTP server.'), ('password', 'p', None, 'The password with which to authenticate to the SMTP server.'), ('from-address', 'f', None, 'The address from which to send the message.'), ('to-address', 't', None, 'The address to which to send the message.'), ('message', 'm', None, 'The filename which contains the message to send.'), ('smtp-host', 'h', None, 'The host through which to send the message.'), ('smtp-port', None, '25', 'The port number on smtp-host to which to connect.')] def postOptions(self): """ Parse integer parameters, open the message file, and make sure all required parameters have been specified. """ try: self['smtp-port'] = int(self['smtp-port']) except ValueError: raise UsageError("--smtp-port argument must be an integer.") if self['username'] is None: raise UsageError( "Must specify authentication username with --username") if self['password'] is None: raise UsageError( "Must specify authentication password with --password") if self['from-address'] is None: raise UsageError("Must specify from address with --from-address") if self['to-address'] is None: raise UsageError("Must specify from address with --to-address") if self['smtp-host'] is None: raise UsageError("Must specify smtp host with --smtp-host") if self['message'] is None: raise UsageError( "Must specify a message file to send with --message") try: self['message'] = file(self['message']) except Exception, e: raise UsageError(e) def cbSentMessage(result): """ Called when the message has been sent. Report success to the user and then stop the reactor. """ print "Message sent" reactor.stop() def ebSentMessage(err): """ Called if the message cannot be sent. Report the failure to the user and then stop the reactor. """ err.printTraceback() reactor.stop() def main(args=None): """ Parse arguments and send an email based on them. """ o = SendmailOptions() try: o.parseOptions(args) except UsageError, e: raise SystemExit(e) else: from twisted.python import log log.startLogging(sys.stdout) result = sendmail( o['username'], o['password'], o['from-address'], o['to-address'], o['message'], o['smtp-host'], o['smtp-port']) result.addCallbacks(cbSentMessage, ebSentMessage) reactor.run() if __name__ == '__main__': main(sys.argv[1:])
agpl-3.0
thoughtpalette/thoughts.thoughtpalette.com
node_modules/grunt-docker/node_modules/docker/node_modules/pygmentize-bundled/vendor/pygments/build-3.3/pygments/lexers/text.py
94
68777
# -*- coding: utf-8 -*- """ pygments.lexers.text ~~~~~~~~~~~~~~~~~~~~ Lexers for non-source code file types. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from bisect import bisect from pygments.lexer import Lexer, LexerContext, RegexLexer, ExtendedRegexLexer, \ bygroups, include, using, this, do_insertions from pygments.token import Punctuation, Text, Comment, Keyword, Name, String, \ Generic, Operator, Number, Whitespace, Literal from pygments.util import get_bool_opt, ClassNotFound from pygments.lexers.other import BashLexer __all__ = ['IniLexer', 'PropertiesLexer', 'SourcesListLexer', 'BaseMakefileLexer', 'MakefileLexer', 'DiffLexer', 'IrcLogsLexer', 'TexLexer', 'GroffLexer', 'ApacheConfLexer', 'BBCodeLexer', 'MoinWikiLexer', 'RstLexer', 'VimLexer', 'GettextLexer', 'SquidConfLexer', 'DebianControlLexer', 'DarcsPatchLexer', 'YamlLexer', 'LighttpdConfLexer', 'NginxConfLexer', 'CMakeLexer', 'HttpLexer', 'PyPyLogLexer', 'RegeditLexer', 'HxmlLexer', 'EbnfLexer'] class IniLexer(RegexLexer): """ Lexer for configuration files in INI style. """ name = 'INI' aliases = ['ini', 'cfg', 'dosini'] filenames = ['*.ini', '*.cfg'] mimetypes = ['text/x-ini'] tokens = { 'root': [ (r'\s+', Text), (r'[;#].*', Comment.Single), (r'\[.*?\]$', Keyword), (r'(.*?)([ \t]*)(=)([ \t]*)(.*(?:\n[ \t].+)*)', bygroups(Name.Attribute, Text, Operator, Text, String)) ] } def analyse_text(text): npos = text.find('\n') if npos < 3: return False return text[0] == '[' and text[npos-1] == ']' class RegeditLexer(RegexLexer): """ Lexer for `Windows Registry <http://en.wikipedia.org/wiki/Windows_Registry#.REG_files>`_ files produced by regedit. *New in Pygments 1.6.* """ name = 'reg' aliases = ['registry'] filenames = ['*.reg'] mimetypes = ['text/x-windows-registry'] tokens = { 'root': [ (r'Windows Registry Editor.*', Text), (r'\s+', Text), (r'[;#].*', Comment.Single), (r'(\[)(-?)(HKEY_[A-Z_]+)(.*?\])$', bygroups(Keyword, Operator, Name.Builtin, Keyword)), # String keys, which obey somewhat normal escaping (r'("(?:\\"|\\\\|[^"])+")([ \t]*)(=)([ \t]*)', bygroups(Name.Attribute, Text, Operator, Text), 'value'), # Bare keys (includes @) (r'(.*?)([ \t]*)(=)([ \t]*)', bygroups(Name.Attribute, Text, Operator, Text), 'value'), ], 'value': [ (r'-', Operator, '#pop'), # delete value (r'(dword|hex(?:\([0-9a-fA-F]\))?)(:)([0-9a-fA-F,]+)', bygroups(Name.Variable, Punctuation, Number), '#pop'), # As far as I know, .reg files do not support line continuation. (r'.*', String, '#pop'), ] } def analyse_text(text): return text.startswith('Windows Registry Editor') class PropertiesLexer(RegexLexer): """ Lexer for configuration files in Java's properties format. *New in Pygments 1.4.* """ name = 'Properties' aliases = ['properties', 'jproperties'] filenames = ['*.properties'] mimetypes = ['text/x-java-properties'] tokens = { 'root': [ (r'\s+', Text), (r'(?:[;#]|//).*$', Comment), (r'(.*?)([ \t]*)([=:])([ \t]*)(.*(?:(?<=\\)\n.*)*)', bygroups(Name.Attribute, Text, Operator, Text, String)), ], } class SourcesListLexer(RegexLexer): """ Lexer that highlights debian sources.list files. *New in Pygments 0.7.* """ name = 'Debian Sourcelist' aliases = ['sourceslist', 'sources.list', 'debsources'] filenames = ['sources.list'] mimetype = ['application/x-debian-sourceslist'] tokens = { 'root': [ (r'\s+', Text), (r'#.*?$', Comment), (r'^(deb(?:-src)?)(\s+)', bygroups(Keyword, Text), 'distribution') ], 'distribution': [ (r'#.*?$', Comment, '#pop'), (r'\$\(ARCH\)', Name.Variable), (r'[^\s$[]+', String), (r'\[', String.Other, 'escaped-distribution'), (r'\$', String), (r'\s+', Text, 'components') ], 'escaped-distribution': [ (r'\]', String.Other, '#pop'), (r'\$\(ARCH\)', Name.Variable), (r'[^\]$]+', String.Other), (r'\$', String.Other) ], 'components': [ (r'#.*?$', Comment, '#pop:2'), (r'$', Text, '#pop:2'), (r'\s+', Text), (r'\S+', Keyword.Pseudo), ] } def analyse_text(text): for line in text.split('\n'): line = line.strip() if not (line.startswith('#') or line.startswith('deb ') or line.startswith('deb-src ') or not line): return False return True class MakefileLexer(Lexer): """ Lexer for BSD and GNU make extensions (lenient enough to handle both in the same file even). *Rewritten in Pygments 0.10.* """ name = 'Makefile' aliases = ['make', 'makefile', 'mf', 'bsdmake'] filenames = ['*.mak', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'] mimetypes = ['text/x-makefile'] r_special = re.compile(r'^(?:' # BSD Make r'\.\s*(include|undef|error|warning|if|else|elif|endif|for|endfor)|' # GNU Make r'\s*(ifeq|ifneq|ifdef|ifndef|else|endif|-?include|define|endef|:))(?=\s)') r_comment = re.compile(r'^\s*@?#') def get_tokens_unprocessed(self, text): ins = [] lines = text.splitlines(True) done = '' lex = BaseMakefileLexer(**self.options) backslashflag = False for line in lines: if self.r_special.match(line) or backslashflag: ins.append((len(done), [(0, Comment.Preproc, line)])) backslashflag = line.strip().endswith('\\') elif self.r_comment.match(line): ins.append((len(done), [(0, Comment, line)])) else: done += line for item in do_insertions(ins, lex.get_tokens_unprocessed(done)): yield item class BaseMakefileLexer(RegexLexer): """ Lexer for simple Makefiles (no preprocessing). *New in Pygments 0.10.* """ name = 'Base Makefile' aliases = ['basemake'] filenames = [] mimetypes = [] tokens = { 'root': [ (r'^(?:[\t ]+.*\n|\n)+', using(BashLexer)), (r'\$\((?:.*\\\n|.*\n)+', using(BashLexer)), (r'\s+', Text), (r'#.*?\n', Comment), (r'(export)(\s+)(?=[a-zA-Z0-9_${}\t -]+\n)', bygroups(Keyword, Text), 'export'), (r'export\s+', Keyword), # assignment (r'([a-zA-Z0-9_${}.-]+)(\s*)([!?:+]?=)([ \t]*)((?:.*\\\n)+|.*\n)', bygroups(Name.Variable, Text, Operator, Text, using(BashLexer))), # strings (r'(?s)"(\\\\|\\.|[^"\\])*"', String.Double), (r"(?s)'(\\\\|\\.|[^'\\])*'", String.Single), # targets (r'([^\n:]+)(:+)([ \t]*)', bygroups(Name.Function, Operator, Text), 'block-header'), # TODO: add paren handling (grr) ], 'export': [ (r'[a-zA-Z0-9_${}-]+', Name.Variable), (r'\n', Text, '#pop'), (r'\s+', Text), ], 'block-header': [ (r'[^,\\\n#]+', Number), (r',', Punctuation), (r'#.*?\n', Comment), (r'\\\n', Text), # line continuation (r'\\.', Text), (r'(?:[\t ]+.*\n|\n)+', using(BashLexer), '#pop'), ], } class DiffLexer(RegexLexer): """ Lexer for unified or context-style diffs or patches. """ name = 'Diff' aliases = ['diff', 'udiff'] filenames = ['*.diff', '*.patch'] mimetypes = ['text/x-diff', 'text/x-patch'] tokens = { 'root': [ (r' .*\n', Text), (r'\+.*\n', Generic.Inserted), (r'-.*\n', Generic.Deleted), (r'!.*\n', Generic.Strong), (r'@.*\n', Generic.Subheading), (r'([Ii]ndex|diff).*\n', Generic.Heading), (r'=.*\n', Generic.Heading), (r'.*\n', Text), ] } def analyse_text(text): if text[:7] == 'Index: ': return True if text[:5] == 'diff ': return True if text[:4] == '--- ': return 0.9 DPATCH_KEYWORDS = ['hunk', 'addfile', 'adddir', 'rmfile', 'rmdir', 'move', 'replace'] class DarcsPatchLexer(RegexLexer): """ DarcsPatchLexer is a lexer for the various versions of the darcs patch format. Examples of this format are derived by commands such as ``darcs annotate --patch`` and ``darcs send``. *New in Pygments 0.10.* """ name = 'Darcs Patch' aliases = ['dpatch'] filenames = ['*.dpatch', '*.darcspatch'] tokens = { 'root': [ (r'<', Operator), (r'>', Operator), (r'{', Operator), (r'}', Operator), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)(\])', bygroups(Operator, Keyword, Name, Text, Name, Operator, Literal.Date, Text, Operator)), (r'(\[)((?:TAG )?)(.*)(\n)(.*)(\*\*)(\d+)(\s?)', bygroups(Operator, Keyword, Name, Text, Name, Operator, Literal.Date, Text), 'comment'), (r'New patches:', Generic.Heading), (r'Context:', Generic.Heading), (r'Patch bundle hash:', Generic.Heading), (r'(\s*)(%s)(.*\n)' % '|'.join(DPATCH_KEYWORDS), bygroups(Text, Keyword, Text)), (r'\+', Generic.Inserted, "insert"), (r'-', Generic.Deleted, "delete"), (r'.*\n', Text), ], 'comment': [ (r'[^\]].*\n', Comment), (r'\]', Operator, "#pop"), ], 'specialText': [ # darcs add [_CODE_] special operators for clarity (r'\n', Text, "#pop"), # line-based (r'\[_[^_]*_]', Operator), ], 'insert': [ include('specialText'), (r'\[', Generic.Inserted), (r'[^\n\[]+', Generic.Inserted), ], 'delete': [ include('specialText'), (r'\[', Generic.Deleted), (r'[^\n\[]+', Generic.Deleted), ], } class IrcLogsLexer(RegexLexer): """ Lexer for IRC logs in *irssi*, *xchat* or *weechat* style. """ name = 'IRC logs' aliases = ['irc'] filenames = ['*.weechatlog'] mimetypes = ['text/x-irclog'] flags = re.VERBOSE | re.MULTILINE timestamp = r""" ( # irssi / xchat and others (?: \[|\()? # Opening bracket or paren for the timestamp (?: # Timestamp (?: (?:\d{1,4} [-/]?)+ # Date as - or /-separated groups of digits [T ])? # Date/time separator: T or space (?: \d?\d [:.]?)+ # Time as :/.-separated groups of 1 or 2 digits ) (?: \]|\))?\s+ # Closing bracket or paren for the timestamp | # weechat \d{4}\s\w{3}\s\d{2}\s # Date \d{2}:\d{2}:\d{2}\s+ # Time + Whitespace | # xchat \w{3}\s\d{2}\s # Date \d{2}:\d{2}:\d{2}\s+ # Time + Whitespace )? """ tokens = { 'root': [ # log start/end (r'^\*\*\*\*(.*)\*\*\*\*$', Comment), # hack ("^" + timestamp + r'(\s*<[^>]*>\s*)$', bygroups(Comment.Preproc, Name.Tag)), # normal msgs ("^" + timestamp + r""" (\s*<.*?>\s*) # Nick """, bygroups(Comment.Preproc, Name.Tag), 'msg'), # /me msgs ("^" + timestamp + r""" (\s*[*]\s+) # Star (\S+\s+.*?\n) # Nick + rest of message """, bygroups(Comment.Preproc, Keyword, Generic.Inserted)), # join/part msgs ("^" + timestamp + r""" (\s*(?:\*{3}|<?-[!@=P]?->?)\s*) # Star(s) or symbols (\S+\s+) # Nick + Space (.*?\n) # Rest of message """, bygroups(Comment.Preproc, Keyword, String, Comment)), (r"^.*?\n", Text), ], 'msg': [ (r"\S+:(?!//)", Name.Attribute), # Prefix (r".*\n", Text, '#pop'), ], } class BBCodeLexer(RegexLexer): """ A lexer that highlights BBCode(-like) syntax. *New in Pygments 0.6.* """ name = 'BBCode' aliases = ['bbcode'] mimetypes = ['text/x-bbcode'] tokens = { 'root': [ (r'[^[]+', Text), # tag/end tag begin (r'\[/?\w+', Keyword, 'tag'), # stray bracket (r'\[', Text), ], 'tag': [ (r'\s+', Text), # attribute with value (r'(\w+)(=)("?[^\s"\]]+"?)', bygroups(Name.Attribute, Operator, String)), # tag argument (a la [color=green]) (r'(=)("?[^\s"\]]+"?)', bygroups(Operator, String)), # tag end (r'\]', Keyword, '#pop'), ], } class TexLexer(RegexLexer): """ Lexer for the TeX and LaTeX typesetting languages. """ name = 'TeX' aliases = ['tex', 'latex'] filenames = ['*.tex', '*.aux', '*.toc'] mimetypes = ['text/x-tex', 'text/x-latex'] tokens = { 'general': [ (r'%.*?\n', Comment), (r'[{}]', Name.Builtin), (r'[&_^]', Name.Builtin), ], 'root': [ (r'\\\[', String.Backtick, 'displaymath'), (r'\\\(', String, 'inlinemath'), (r'\$\$', String.Backtick, 'displaymath'), (r'\$', String, 'inlinemath'), (r'\\([a-zA-Z]+|.)', Keyword, 'command'), include('general'), (r'[^\\$%&_^{}]+', Text), ], 'math': [ (r'\\([a-zA-Z]+|.)', Name.Variable), include('general'), (r'[0-9]+', Number), (r'[-=!+*/()\[\]]', Operator), (r'[^=!+*/()\[\]\\$%&_^{}0-9-]+', Name.Builtin), ], 'inlinemath': [ (r'\\\)', String, '#pop'), (r'\$', String, '#pop'), include('math'), ], 'displaymath': [ (r'\\\]', String, '#pop'), (r'\$\$', String, '#pop'), (r'\$', Name.Builtin), include('math'), ], 'command': [ (r'\[.*?\]', Name.Attribute), (r'\*', Keyword), (r'', Text, '#pop'), ], } def analyse_text(text): for start in ("\\documentclass", "\\input", "\\documentstyle", "\\relax"): if text[:len(start)] == start: return True class GroffLexer(RegexLexer): """ Lexer for the (g)roff typesetting language, supporting groff extensions. Mainly useful for highlighting manpage sources. *New in Pygments 0.6.* """ name = 'Groff' aliases = ['groff', 'nroff', 'man'] filenames = ['*.[1234567]', '*.man'] mimetypes = ['application/x-troff', 'text/troff'] tokens = { 'root': [ (r'(\.)(\w+)', bygroups(Text, Keyword), 'request'), (r'\.', Punctuation, 'request'), # Regular characters, slurp till we find a backslash or newline (r'[^\\\n]*', Text, 'textline'), ], 'textline': [ include('escapes'), (r'[^\\\n]+', Text), (r'\n', Text, '#pop'), ], 'escapes': [ # groff has many ways to write escapes. (r'\\"[^\n]*', Comment), (r'\\[fn]\w', String.Escape), (r'\\\(.{2}', String.Escape), (r'\\.\[.*\]', String.Escape), (r'\\.', String.Escape), (r'\\\n', Text, 'request'), ], 'request': [ (r'\n', Text, '#pop'), include('escapes'), (r'"[^\n"]+"', String.Double), (r'\d+', Number), (r'\S+', String), (r'\s+', Text), ], } def analyse_text(text): if text[:1] != '.': return False if text[:3] == '.\\"': return True if text[:4] == '.TH ': return True if text[1:3].isalnum() and text[3].isspace(): return 0.9 class ApacheConfLexer(RegexLexer): """ Lexer for configuration files following the Apache config file format. *New in Pygments 0.6.* """ name = 'ApacheConf' aliases = ['apacheconf', 'aconf', 'apache'] filenames = ['.htaccess', 'apache.conf', 'apache2.conf'] mimetypes = ['text/x-apacheconf'] flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'\s+', Text), (r'(#.*?)$', Comment), (r'(<[^\s>]+)(?:(\s+)(.*?))?(>)', bygroups(Name.Tag, Text, String, Name.Tag)), (r'([a-zA-Z][a-zA-Z0-9_]*)(\s+)', bygroups(Name.Builtin, Text), 'value'), (r'\.+', Text), ], 'value': [ (r'$', Text, '#pop'), (r'[^\S\n]+', Text), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'\d+', Number), (r'/([a-zA-Z0-9][a-zA-Z0-9_./-]+)', String.Other), (r'(on|off|none|any|all|double|email|dns|min|minimal|' r'os|productonly|full|emerg|alert|crit|error|warn|' r'notice|info|debug|registry|script|inetd|standalone|' r'user|group)\b', Keyword), (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), (r'[^\s"]+', Text) ] } class MoinWikiLexer(RegexLexer): """ For MoinMoin (and Trac) Wiki markup. *New in Pygments 0.7.* """ name = 'MoinMoin/Trac Wiki markup' aliases = ['trac-wiki', 'moin'] filenames = [] mimetypes = ['text/x-trac-wiki'] flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ (r'^#.*$', Comment), (r'(!)(\S+)', bygroups(Keyword, Text)), # Ignore-next # Titles (r'^(=+)([^=]+)(=+)(\s*#.+)?$', bygroups(Generic.Heading, using(this), Generic.Heading, String)), # Literal code blocks, with optional shebang (r'({{{)(\n#!.+)?', bygroups(Name.Builtin, Name.Namespace), 'codeblock'), (r'(\'\'\'?|\|\||`|__|~~|\^|,,|::)', Comment), # Formatting # Lists (r'^( +)([.*-])( )', bygroups(Text, Name.Builtin, Text)), (r'^( +)([a-z]{1,5}\.)( )', bygroups(Text, Name.Builtin, Text)), # Other Formatting (r'\[\[\w+.*?\]\]', Keyword), # Macro (r'(\[[^\s\]]+)(\s+[^\]]+?)?(\])', bygroups(Keyword, String, Keyword)), # Link (r'^----+$', Keyword), # Horizontal rules (r'[^\n\'\[{!_~^,|]+', Text), (r'\n', Text), (r'.', Text), ], 'codeblock': [ (r'}}}', Name.Builtin, '#pop'), # these blocks are allowed to be nested in Trac, but not MoinMoin (r'{{{', Text, '#push'), (r'[^{}]+', Comment.Preproc), # slurp boring text (r'.', Comment.Preproc), # allow loose { or } ], } class RstLexer(RegexLexer): """ For `reStructuredText <http://docutils.sf.net/rst.html>`_ markup. *New in Pygments 0.7.* Additional options accepted: `handlecodeblocks` Highlight the contents of ``.. sourcecode:: langauge`` and ``.. code:: language`` directives with a lexer for the given language (default: ``True``). *New in Pygments 0.8.* """ name = 'reStructuredText' aliases = ['rst', 'rest', 'restructuredtext'] filenames = ['*.rst', '*.rest'] mimetypes = ["text/x-rst", "text/prs.fallenstein.rst"] flags = re.MULTILINE def _handle_sourcecode(self, match): from pygments.lexers import get_lexer_by_name # section header yield match.start(1), Punctuation, match.group(1) yield match.start(2), Text, match.group(2) yield match.start(3), Operator.Word, match.group(3) yield match.start(4), Punctuation, match.group(4) yield match.start(5), Text, match.group(5) yield match.start(6), Keyword, match.group(6) yield match.start(7), Text, match.group(7) # lookup lexer if wanted and existing lexer = None if self.handlecodeblocks: try: lexer = get_lexer_by_name(match.group(6).strip()) except ClassNotFound: pass indention = match.group(8) indention_size = len(indention) code = (indention + match.group(9) + match.group(10) + match.group(11)) # no lexer for this language. handle it like it was a code block if lexer is None: yield match.start(8), String, code return # highlight the lines with the lexer. ins = [] codelines = code.splitlines(True) code = '' for line in codelines: if len(line) > indention_size: ins.append((len(code), [(0, Text, line[:indention_size])])) code += line[indention_size:] else: code += line for item in do_insertions(ins, lexer.get_tokens_unprocessed(code)): yield item # from docutils.parsers.rst.states closers = '\'")]}>\u2019\u201d\xbb!?' unicode_delimiters = '\u2010\u2011\u2012\u2013\u2014\u00a0' end_string_suffix = (r'((?=$)|(?=[-/:.,; \n\x00%s%s]))' % (re.escape(unicode_delimiters), re.escape(closers))) tokens = { 'root': [ # Heading with overline (r'^(=+|-+|`+|:+|\.+|\'+|"+|~+|\^+|_+|\*+|\++|#+)([ \t]*\n)' r'(.+)(\n)(\1)(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text, Generic.Heading, Text)), # Plain heading (r'^(\S.*)(\n)(={3,}|-{3,}|`{3,}|:{3,}|\.{3,}|\'{3,}|"{3,}|' r'~{3,}|\^{3,}|_{3,}|\*{3,}|\+{3,}|#{3,})(\n)', bygroups(Generic.Heading, Text, Generic.Heading, Text)), # Bulleted lists (r'^(\s*)([-*+])( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), # Numbered lists (r'^(\s*)([0-9#ivxlcmIVXLCM]+\.)( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), (r'^(\s*)(\(?[0-9#ivxlcmIVXLCM]+\))( .+\n(?:\1 .+\n)*)', bygroups(Text, Number, using(this, state='inline'))), # Numbered, but keep words at BOL from becoming lists (r'^(\s*)([A-Z]+\.)( .+\n(?:\1 .+\n)+)', bygroups(Text, Number, using(this, state='inline'))), (r'^(\s*)(\(?[A-Za-z]+\))( .+\n(?:\1 .+\n)+)', bygroups(Text, Number, using(this, state='inline'))), # Line blocks (r'^(\s*)(\|)( .+\n(?:\| .+\n)*)', bygroups(Text, Operator, using(this, state='inline'))), # Sourcecode directives (r'^( *\.\.)(\s*)((?:source)?code)(::)([ \t]*)([^\n]+)' r'(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\8.*|)\n)+)', _handle_sourcecode), # A directive (r'^( *\.\.)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))', bygroups(Punctuation, Text, Operator.Word, Punctuation, Text, using(this, state='inline'))), # A reference target (r'^( *\.\.)(\s*)(_(?:[^:\\]|\\.)+:)(.*?)$', bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))), # A footnote/citation target (r'^( *\.\.)(\s*)(\[.+\])(.*?)$', bygroups(Punctuation, Text, Name.Tag, using(this, state='inline'))), # A substitution def (r'^( *\.\.)(\s*)(\|.+\|)(\s*)([\w:-]+?)(::)(?:([ \t]*)(.*))', bygroups(Punctuation, Text, Name.Tag, Text, Operator.Word, Punctuation, Text, using(this, state='inline'))), # Comments (r'^ *\.\..*(\n( +.*\n|\n)+)?', Comment.Preproc), # Field list (r'^( *)(:[a-zA-Z-]+:)(\s*)$', bygroups(Text, Name.Class, Text)), (r'^( *)(:.*?:)([ \t]+)(.*?)$', bygroups(Text, Name.Class, Text, Name.Function)), # Definition list (r'^([^ ].*(?<!::)\n)((?:(?: +.*)\n)+)', bygroups(using(this, state='inline'), using(this, state='inline'))), # Code blocks (r'(::)(\n[ \t]*\n)([ \t]+)(.*)(\n)((?:(?:\3.*|)\n)+)', bygroups(String.Escape, Text, String, String, Text, String)), include('inline'), ], 'inline': [ (r'\\.', Text), # escape (r'``', String, 'literal'), # code (r'(`.+?)(<.+?>)(`__?)', # reference with inline target bygroups(String, String.Interpol, String)), (r'`.+?`__?', String), # reference (r'(`.+?`)(:[a-zA-Z0-9:-]+?:)?', bygroups(Name.Variable, Name.Attribute)), # role (r'(:[a-zA-Z0-9:-]+?:)(`.+?`)', bygroups(Name.Attribute, Name.Variable)), # role (content first) (r'\*\*.+?\*\*', Generic.Strong), # Strong emphasis (r'\*.+?\*', Generic.Emph), # Emphasis (r'\[.*?\]_', String), # Footnote or citation (r'<.+?>', Name.Tag), # Hyperlink (r'[^\\\n\[*`:]+', Text), (r'.', Text), ], 'literal': [ (r'[^`]+', String), (r'``' + end_string_suffix, String, '#pop'), (r'`', String), ] } def __init__(self, **options): self.handlecodeblocks = get_bool_opt(options, 'handlecodeblocks', True) RegexLexer.__init__(self, **options) def analyse_text(text): if text[:2] == '..' and text[2:3] != '.': return 0.3 p1 = text.find("\n") p2 = text.find("\n", p1 + 1) if (p2 > -1 and # has two lines p1 * 2 + 1 == p2 and # they are the same length text[p1+1] in '-=' and # the next line both starts and ends with text[p1+1] == text[p2-1]): # ...a sufficiently high header return 0.5 class VimLexer(RegexLexer): """ Lexer for VimL script files. *New in Pygments 0.8.* """ name = 'VimL' aliases = ['vim'] filenames = ['*.vim', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc'] mimetypes = ['text/x-vim'] flags = re.MULTILINE tokens = { 'root': [ (r'^\s*".*', Comment), (r'[ \t]+', Text), # TODO: regexes can have other delims (r'/(\\\\|\\/|[^\n/])*/', String.Regex), (r'"(\\\\|\\"|[^\n"])*"', String.Double), (r"'(\\\\|\\'|[^\n'])*'", String.Single), # Who decided that doublequote was a good comment character?? (r'(?<=\s)"[^\-:.%#=*].*', Comment), (r'-?\d+', Number), (r'#[0-9a-f]{6}', Number.Hex), (r'^:', Punctuation), (r'[()<>+=!|,~-]', Punctuation), # Inexact list. Looks decent. (r'\b(let|if|else|endif|elseif|fun|function|endfunction)\b', Keyword), (r'\b(NONE|bold|italic|underline|dark|light)\b', Name.Builtin), (r'\b\w+\b', Name.Other), # These are postprocessed below (r'.', Text), ], } def __init__(self, **options): from pygments.lexers._vimbuiltins import command, option, auto self._cmd = command self._opt = option self._aut = auto RegexLexer.__init__(self, **options) def is_in(self, w, mapping): r""" It's kind of difficult to decide if something might be a keyword in VimL because it allows you to abbreviate them. In fact, 'ab[breviate]' is a good example. :ab, :abbre, or :abbreviate are valid ways to call it so rather than making really awful regexps like:: \bab(?:b(?:r(?:e(?:v(?:i(?:a(?:t(?:e)?)?)?)?)?)?)?)?\b we match `\b\w+\b` and then call is_in() on those tokens. See `scripts/get_vimkw.py` for how the lists are extracted. """ p = bisect(mapping, (w,)) if p > 0: if mapping[p-1][0] == w[:len(mapping[p-1][0])] and \ mapping[p-1][1][:len(w)] == w: return True if p < len(mapping): return mapping[p][0] == w[:len(mapping[p][0])] and \ mapping[p][1][:len(w)] == w return False def get_tokens_unprocessed(self, text): # TODO: builtins are only subsequent tokens on lines # and 'keywords' only happen at the beginning except # for :au ones for index, token, value in \ RegexLexer.get_tokens_unprocessed(self, text): if token is Name.Other: if self.is_in(value, self._cmd): yield index, Keyword, value elif self.is_in(value, self._opt) or \ self.is_in(value, self._aut): yield index, Name.Builtin, value else: yield index, Text, value else: yield index, token, value class GettextLexer(RegexLexer): """ Lexer for Gettext catalog files. *New in Pygments 0.9.* """ name = 'Gettext Catalog' aliases = ['pot', 'po'] filenames = ['*.pot', '*.po'] mimetypes = ['application/x-gettext', 'text/x-gettext', 'text/gettext'] tokens = { 'root': [ (r'^#,\s.*?$', Keyword.Type), (r'^#:\s.*?$', Keyword.Declaration), #(r'^#$', Comment), (r'^(#|#\.\s|#\|\s|#~\s|#\s).*$', Comment.Single), (r'^(")([A-Za-z-]+:)(.*")$', bygroups(String, Name.Property, String)), (r'^".*"$', String), (r'^(msgid|msgid_plural|msgstr)(\s+)(".*")$', bygroups(Name.Variable, Text, String)), (r'^(msgstr\[)(\d)(\])(\s+)(".*")$', bygroups(Name.Variable, Number.Integer, Name.Variable, Text, String)), ] } class SquidConfLexer(RegexLexer): """ Lexer for `squid <http://www.squid-cache.org/>`_ configuration files. *New in Pygments 0.9.* """ name = 'SquidConf' aliases = ['squidconf', 'squid.conf', 'squid'] filenames = ['squid.conf'] mimetypes = ['text/x-squidconf'] flags = re.IGNORECASE keywords = [ "access_log", "acl", "always_direct", "announce_host", "announce_period", "announce_port", "announce_to", "anonymize_headers", "append_domain", "as_whois_server", "auth_param_basic", "authenticate_children", "authenticate_program", "authenticate_ttl", "broken_posts", "buffered_logs", "cache_access_log", "cache_announce", "cache_dir", "cache_dns_program", "cache_effective_group", "cache_effective_user", "cache_host", "cache_host_acl", "cache_host_domain", "cache_log", "cache_mem", "cache_mem_high", "cache_mem_low", "cache_mgr", "cachemgr_passwd", "cache_peer", "cache_peer_access", "cahce_replacement_policy", "cache_stoplist", "cache_stoplist_pattern", "cache_store_log", "cache_swap", "cache_swap_high", "cache_swap_log", "cache_swap_low", "client_db", "client_lifetime", "client_netmask", "connect_timeout", "coredump_dir", "dead_peer_timeout", "debug_options", "delay_access", "delay_class", "delay_initial_bucket_level", "delay_parameters", "delay_pools", "deny_info", "dns_children", "dns_defnames", "dns_nameservers", "dns_testnames", "emulate_httpd_log", "err_html_text", "fake_user_agent", "firewall_ip", "forwarded_for", "forward_snmpd_port", "fqdncache_size", "ftpget_options", "ftpget_program", "ftp_list_width", "ftp_passive", "ftp_user", "half_closed_clients", "header_access", "header_replace", "hierarchy_stoplist", "high_response_time_warning", "high_page_fault_warning", "hosts_file", "htcp_port", "http_access", "http_anonymizer", "httpd_accel", "httpd_accel_host", "httpd_accel_port", "httpd_accel_uses_host_header", "httpd_accel_with_proxy", "http_port", "http_reply_access", "icp_access", "icp_hit_stale", "icp_port", "icp_query_timeout", "ident_lookup", "ident_lookup_access", "ident_timeout", "incoming_http_average", "incoming_icp_average", "inside_firewall", "ipcache_high", "ipcache_low", "ipcache_size", "local_domain", "local_ip", "logfile_rotate", "log_fqdn", "log_icp_queries", "log_mime_hdrs", "maximum_object_size", "maximum_single_addr_tries", "mcast_groups", "mcast_icp_query_timeout", "mcast_miss_addr", "mcast_miss_encode_key", "mcast_miss_port", "memory_pools", "memory_pools_limit", "memory_replacement_policy", "mime_table", "min_http_poll_cnt", "min_icp_poll_cnt", "minimum_direct_hops", "minimum_object_size", "minimum_retry_timeout", "miss_access", "negative_dns_ttl", "negative_ttl", "neighbor_timeout", "neighbor_type_domain", "netdb_high", "netdb_low", "netdb_ping_period", "netdb_ping_rate", "never_direct", "no_cache", "passthrough_proxy", "pconn_timeout", "pid_filename", "pinger_program", "positive_dns_ttl", "prefer_direct", "proxy_auth", "proxy_auth_realm", "query_icmp", "quick_abort", "quick_abort", "quick_abort_max", "quick_abort_min", "quick_abort_pct", "range_offset_limit", "read_timeout", "redirect_children", "redirect_program", "redirect_rewrites_host_header", "reference_age", "reference_age", "refresh_pattern", "reload_into_ims", "request_body_max_size", "request_size", "request_timeout", "shutdown_lifetime", "single_parent_bypass", "siteselect_timeout", "snmp_access", "snmp_incoming_address", "snmp_port", "source_ping", "ssl_proxy", "store_avg_object_size", "store_objects_per_bucket", "strip_query_terms", "swap_level1_dirs", "swap_level2_dirs", "tcp_incoming_address", "tcp_outgoing_address", "tcp_recv_bufsize", "test_reachability", "udp_hit_obj", "udp_hit_obj_size", "udp_incoming_address", "udp_outgoing_address", "unique_hostname", "unlinkd_program", "uri_whitespace", "useragent_log", "visible_hostname", "wais_relay", "wais_relay_host", "wais_relay_port", ] opts = [ "proxy-only", "weight", "ttl", "no-query", "default", "round-robin", "multicast-responder", "on", "off", "all", "deny", "allow", "via", "parent", "no-digest", "heap", "lru", "realm", "children", "q1", "q2", "credentialsttl", "none", "disable", "offline_toggle", "diskd", ] actions = [ "shutdown", "info", "parameter", "server_list", "client_list", r'squid\.conf', ] actions_stats = [ "objects", "vm_objects", "utilization", "ipcache", "fqdncache", "dns", "redirector", "io", "reply_headers", "filedescriptors", "netdb", ] actions_log = ["status", "enable", "disable", "clear"] acls = [ "url_regex", "urlpath_regex", "referer_regex", "port", "proto", "req_mime_type", "rep_mime_type", "method", "browser", "user", "src", "dst", "time", "dstdomain", "ident", "snmp_community", ] ip_re = ( r'(?:(?:(?:[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}|0x0*[0-9a-f]{1,2}|' r'0+[1-3]?[0-7]{0,2})(?:\.(?:[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}|' r'0x0*[0-9a-f]{1,2}|0+[1-3]?[0-7]{0,2})){3})|(?!.*::.*::)(?:(?!:)|' r':(?=:))(?:[0-9a-f]{0,4}(?:(?<=::)|(?<!::):)){6}(?:[0-9a-f]{0,4}' r'(?:(?<=::)|(?<!::):)[0-9a-f]{0,4}(?:(?<=::)|(?<!:)|(?<=:)(?<!::):)|' r'(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-4]|2[0-4]\d|1\d\d|' r'[1-9]?\d)){3}))' ) def makelistre(list): return r'\b(?:' + '|'.join(list) + r')\b' tokens = { 'root': [ (r'\s+', Whitespace), (r'#', Comment, 'comment'), (makelistre(keywords), Keyword), (makelistre(opts), Name.Constant), # Actions (makelistre(actions), String), (r'stats/'+makelistre(actions), String), (r'log/'+makelistre(actions)+r'=', String), (makelistre(acls), Keyword), (ip_re + r'(?:/(?:' + ip_re + r'|\b\d+\b))?', Number.Float), (r'(?:\b\d+\b(?:-\b\d+|%)?)', Number), (r'\S+', Text), ], 'comment': [ (r'\s*TAG:.*', String.Escape, '#pop'), (r'.*', Comment, '#pop'), ], } class DebianControlLexer(RegexLexer): """ Lexer for Debian ``control`` files and ``apt-cache show <pkg>`` outputs. *New in Pygments 0.9.* """ name = 'Debian Control file' aliases = ['control', 'debcontrol'] filenames = ['control'] tokens = { 'root': [ (r'^(Description)', Keyword, 'description'), (r'^(Maintainer)(:\s*)', bygroups(Keyword, Text), 'maintainer'), (r'^((Build-)?Depends)', Keyword, 'depends'), (r'^((?:Python-)?Version)(:\s*)(\S+)$', bygroups(Keyword, Text, Number)), (r'^((?:Installed-)?Size)(:\s*)(\S+)$', bygroups(Keyword, Text, Number)), (r'^(MD5Sum|SHA1|SHA256)(:\s*)(\S+)$', bygroups(Keyword, Text, Number)), (r'^([a-zA-Z\-0-9\.]*?)(:\s*)(.*?)$', bygroups(Keyword, Whitespace, String)), ], 'maintainer': [ (r'<[^>]+>', Generic.Strong), (r'<[^>]+>$', Generic.Strong, '#pop'), (r',\n?', Text), (r'.', Text), ], 'description': [ (r'(.*)(Homepage)(: )(\S+)', bygroups(Text, String, Name, Name.Class)), (r':.*\n', Generic.Strong), (r' .*\n', Text), ('', Text, '#pop'), ], 'depends': [ (r':\s*', Text), (r'(\$)(\{)(\w+\s*:\s*\w+)', bygroups(Operator, Text, Name.Entity)), (r'\(', Text, 'depend_vers'), (r',', Text), (r'\|', Operator), (r'[\s]+', Text), (r'[}\)]\s*$', Text, '#pop'), (r'}', Text), (r'[^,]$', Name.Function, '#pop'), (r'([\+\.a-zA-Z0-9-])(\s*)', bygroups(Name.Function, Text)), (r'\[.*?\]', Name.Entity), ], 'depend_vers': [ (r'\),', Text, '#pop'), (r'\)[^,]', Text, '#pop:2'), (r'([><=]+)(\s*)([^\)]+)', bygroups(Operator, Text, Number)) ] } class YamlLexerContext(LexerContext): """Indentation context for the YAML lexer.""" def __init__(self, *args, **kwds): super(YamlLexerContext, self).__init__(*args, **kwds) self.indent_stack = [] self.indent = -1 self.next_indent = 0 self.block_scalar_indent = None class YamlLexer(ExtendedRegexLexer): """ Lexer for `YAML <http://yaml.org/>`_, a human-friendly data serialization language. *New in Pygments 0.11.* """ name = 'YAML' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] def something(token_class): """Do not produce empty tokens.""" def callback(lexer, match, context): text = match.group() if not text: return yield match.start(), token_class, text context.pos = match.end() return callback def reset_indent(token_class): """Reset the indentation levels.""" def callback(lexer, match, context): text = match.group() context.indent_stack = [] context.indent = -1 context.next_indent = 0 context.block_scalar_indent = None yield match.start(), token_class, text context.pos = match.end() return callback def save_indent(token_class, start=False): """Save a possible indentation level.""" def callback(lexer, match, context): text = match.group() extra = '' if start: context.next_indent = len(text) if context.next_indent < context.indent: while context.next_indent < context.indent: context.indent = context.indent_stack.pop() if context.next_indent > context.indent: extra = text[context.indent:] text = text[:context.indent] else: context.next_indent += len(text) if text: yield match.start(), token_class, text if extra: yield match.start()+len(text), token_class.Error, extra context.pos = match.end() return callback def set_indent(token_class, implicit=False): """Set the previously saved indentation level.""" def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_indent += len(text) yield match.start(), token_class, text context.pos = match.end() return callback def set_block_scalar_indent(token_class): """Set an explicit indentation level for a block scalar.""" def callback(lexer, match, context): text = match.group() context.block_scalar_indent = None if not text: return increment = match.group(1) if increment: current_indent = max(context.indent, 0) increment = int(increment) context.block_scalar_indent = current_indent + increment if text: yield match.start(), token_class, text context.pos = match.end() return callback def parse_block_scalar_empty_line(indent_token_class, content_token_class): """Process an empty line in a block scalar.""" def callback(lexer, match, context): text = match.group() if (context.block_scalar_indent is None or len(text) <= context.block_scalar_indent): if text: yield match.start(), indent_token_class, text else: indentation = text[:context.block_scalar_indent] content = text[context.block_scalar_indent:] yield match.start(), indent_token_class, indentation yield (match.start()+context.block_scalar_indent, content_token_class, content) context.pos = match.end() return callback def parse_block_scalar_indent(token_class): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return context.block_scalar_indent = len(text) else: if len(text) < context.block_scalar_indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback def parse_plain_scalar_indent(token_class): """Process indentation spaces in a plain scalar.""" def callback(lexer, match, context): text = match.group() if len(text) <= context.indent: context.stack.pop() context.stack.pop() return if text: yield match.start(), token_class, text context.pos = match.end() return callback tokens = { # the root rules 'root': [ # ignored whitespaces (r'[ ]+(?=#|$)', Text), # line breaks (r'\n+', Text), # a comment (r'#[^\n]*', Comment.Single), # the '%YAML' directive (r'^%YAML(?=[ ]|$)', reset_indent(Name.Tag), 'yaml-directive'), # the %TAG directive (r'^%TAG(?=[ ]|$)', reset_indent(Name.Tag), 'tag-directive'), # document start and document end indicators (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Name.Namespace), 'block-line'), # indentation spaces (r'[ ]*(?![ \t\n\r\f\v]|$)', save_indent(Text, start=True), ('block-line', 'indentation')), ], # trailing whitespaces after directives or a block scalar indicator 'ignored-line': [ # ignored whitespaces (r'[ ]+(?=#|$)', Text), # a comment (r'#[^\n]*', Comment.Single), # line break (r'\n', Text, '#pop:2'), ], # the %YAML directive 'yaml-directive': [ # the version number (r'([ ]+)([0-9]+\.[0-9]+)', bygroups(Text, Number), 'ignored-line'), ], # the %YAG directive 'tag-directive': [ # a tag handle and the corresponding prefix (r'([ ]+)(!|![0-9A-Za-z_-]*!)' r'([ ]+)(!|!?[0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+)', bygroups(Text, Keyword.Type, Text, Keyword.Type), 'ignored-line'), ], # block scalar indicators and indentation spaces 'indentation': [ # trailing whitespaces are ignored (r'[ ]*$', something(Text), '#pop:2'), # whitespaces preceeding block collection indicators (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Text)), # block collection indicators (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)), # the beginning a block line (r'[ ]*', save_indent(Text), '#pop'), ], # an indented line in the block context 'block-line': [ # the line end (r'[ ]*(?=#|$)', something(Text), '#pop'), # whitespaces separating tokens (r'[ ]+', Text), # tags, anchors and aliases, include('descriptors'), # block collections and scalars include('block-nodes'), # flow collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^ \t\n\r\f\v?:,\[\]{}#&*!|>\'"%@`-]|[?:-][^ \t\n\r\f\v])', something(Name.Variable), 'plain-scalar-in-block-context'), ], # tags, anchors, aliases 'descriptors' : [ # a full-form tag (r'!<[0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+>', Keyword.Type), # a tag in the form '!', '!suffix' or '!handle!suffix' (r'!(?:[0-9A-Za-z_-]+)?' r'(?:![0-9A-Za-z;/?:@&=+$,_.!~*\'()\[\]%-]+)?', Keyword.Type), # an anchor (r'&[0-9A-Za-z_-]+', Name.Label), # an alias (r'\*[0-9A-Za-z_-]+', Name.Variable), ], # block collections and scalars 'block-nodes': [ # implicit key (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)), # literal and folded scalars (r'[|>]', Punctuation.Indicator, ('block-scalar-content', 'block-scalar-header')), ], # flow collections and quoted scalars 'flow-nodes': [ # a flow sequence (r'\[', Punctuation.Indicator, 'flow-sequence'), # a flow mapping (r'\{', Punctuation.Indicator, 'flow-mapping'), # a single-quoted scalar (r'\'', String, 'single-quoted-scalar'), # a double-quoted scalar (r'\"', String, 'double-quoted-scalar'), ], # the content of a flow collection 'flow-collection': [ # whitespaces (r'[ ]+', Text), # line breaks (r'\n+', Text), # a comment (r'#[^\n]*', Comment.Single), # simple indicators (r'[?:,]', Punctuation.Indicator), # tags, anchors and aliases include('descriptors'), # nested collections and quoted scalars include('flow-nodes'), # a plain scalar (r'(?=[^ \t\n\r\f\v?:,\[\]{}#&*!|>\'"%@`])', something(Name.Variable), 'plain-scalar-in-flow-context'), ], # a flow sequence indicated by '[' and ']' 'flow-sequence': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\]', Punctuation.Indicator, '#pop'), ], # a flow mapping indicated by '{' and '}' 'flow-mapping': [ # include flow collection rules include('flow-collection'), # the closing indicator (r'\}', Punctuation.Indicator, '#pop'), ], # block scalar lines 'block-scalar-content': [ # line break (r'\n', Text), # empty line (r'^[ ]+$', parse_block_scalar_empty_line(Text, Name.Constant)), # indentation spaces (we may leave the state here) (r'^[ ]*', parse_block_scalar_indent(Text)), # line content (r'[^\n\r\f\v]+', Name.Constant), ], # the content of a literal or folded scalar 'block-scalar-header': [ # indentation indicator followed by chomping flag (r'([1-9])?[+-]?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), # chomping flag followed by indentation indicator (r'[+-]?([1-9])?(?=[ ]|$)', set_block_scalar_indent(Punctuation.Indicator), 'ignored-line'), ], # ignored and regular whitespaces in quoted scalars 'quoted-scalar-whitespaces': [ # leading and trailing whitespaces are ignored (r'^[ ]+', Text), (r'[ ]+$', Text), # line breaks are ignored (r'\n+', Text), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), ], # single-quoted scalars 'single-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of the quote character (r'\'\'', String.Escape), # regular non-whitespace characters (r'[^ \t\n\r\f\v\']+', String), # the closing quote (r'\'', String, '#pop'), ], # double-quoted scalars 'double-quoted-scalar': [ # include whitespace and line break rules include('quoted-scalar-whitespaces'), # escaping of special characters (r'\\[0abt\tn\nvfre "\\N_LP]', String), # escape codes (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})', String.Escape), # regular non-whitespace characters (r'[^ \t\n\r\f\v\"\\]+', String), # the closing quote (r'"', String, '#pop'), ], # the beginning of a new line while scanning a plain scalar 'plain-scalar-in-block-context-new-line': [ # empty lines (r'^[ ]+$', Text), # line breaks (r'\n+', Text), # document start and document end indicators (r'^(?=---|\.\.\.)', something(Name.Namespace), '#pop:3'), # indentation spaces (we may leave the block line state here) (r'^[ ]*', parse_plain_scalar_indent(Text), '#pop'), ], # a plain scalar in the block context 'plain-scalar-in-block-context': [ # the scalar ends with the ':' indicator (r'[ ]*(?=:[ ]|:$)', something(Text), '#pop'), # the scalar ends with whitespaces followed by a comment (r'[ ]+(?=#)', Text, '#pop'), # trailing whitespaces are ignored (r'[ ]+$', Text), # line breaks are ignored (r'\n+', Text, 'plain-scalar-in-block-context-new-line'), # other whitespaces are a part of the value (r'[ ]+', Literal.Scalar.Plain), # regular non-whitespace characters (r'(?::(?![ \t\n\r\f\v])|[^ \t\n\r\f\v:])+', Literal.Scalar.Plain), ], # a plain scalar is the flow context 'plain-scalar-in-flow-context': [ # the scalar ends with an indicator character (r'[ ]*(?=[,:?\[\]{}])', something(Text), '#pop'), # the scalar ends with a comment (r'[ ]+(?=#)', Text, '#pop'), # leading and trailing whitespaces are ignored (r'^[ ]+', Text), (r'[ ]+$', Text), # line breaks are ignored (r'\n+', Text), # other whitespaces are a part of the value (r'[ ]+', Name.Variable), # regular non-whitespace characters (r'[^ \t\n\r\f\v,:?\[\]{}]+', Name.Variable), ], } def get_tokens_unprocessed(self, text=None, context=None): if context is None: context = YamlLexerContext(text, 0) return super(YamlLexer, self).get_tokens_unprocessed(text, context) class LighttpdConfLexer(RegexLexer): """ Lexer for `Lighttpd <http://lighttpd.net/>`_ configuration files. *New in Pygments 0.11.* """ name = 'Lighttpd configuration file' aliases = ['lighty', 'lighttpd'] filenames = [] mimetypes = ['text/x-lighttpd-conf'] tokens = { 'root': [ (r'#.*\n', Comment.Single), (r'/\S*', Name), # pathname (r'[a-zA-Z._-]+', Keyword), (r'\d+\.\d+\.\d+\.\d+(?:/\d+)?', Number), (r'[0-9]+', Number), (r'=>|=~|\+=|==|=|\+', Operator), (r'\$[A-Z]+', Name.Builtin), (r'[(){}\[\],]', Punctuation), (r'"([^"\\]*(?:\\.[^"\\]*)*)"', String.Double), (r'\s+', Text), ], } class NginxConfLexer(RegexLexer): """ Lexer for `Nginx <http://nginx.net/>`_ configuration files. *New in Pygments 0.11.* """ name = 'Nginx configuration file' aliases = ['nginx'] filenames = [] mimetypes = ['text/x-nginx-conf'] tokens = { 'root': [ (r'(include)(\s+)([^\s;]+)', bygroups(Keyword, Text, Name)), (r'[^\s;#]+', Keyword, 'stmt'), include('base'), ], 'block': [ (r'}', Punctuation, '#pop:2'), (r'[^\s;#]+', Keyword.Namespace, 'stmt'), include('base'), ], 'stmt': [ (r'{', Punctuation, 'block'), (r';', Punctuation, '#pop'), include('base'), ], 'base': [ (r'#.*\n', Comment.Single), (r'on|off', Name.Constant), (r'\$[^\s;#()]+', Name.Variable), (r'([a-z0-9.-]+)(:)([0-9]+)', bygroups(Name, Punctuation, Number.Integer)), (r'[a-z-]+/[a-z-+]+', String), # mimetype #(r'[a-zA-Z._-]+', Keyword), (r'[0-9]+[km]?\b', Number.Integer), (r'(~)(\s*)([^\s{]+)', bygroups(Punctuation, Text, String.Regex)), (r'[:=~]', Punctuation), (r'[^\s;#{}$]+', String), # catch all (r'/[^\s;#]*', Name), # pathname (r'\s+', Text), (r'[$;]', Text), # leftover characters ], } class CMakeLexer(RegexLexer): """ Lexer for `CMake <http://cmake.org/Wiki/CMake>`_ files. *New in Pygments 1.2.* """ name = 'CMake' aliases = ['cmake'] filenames = ['*.cmake', 'CMakeLists.txt'] mimetypes = ['text/x-cmake'] tokens = { 'root': [ #(r'(ADD_CUSTOM_COMMAND|ADD_CUSTOM_TARGET|ADD_DEFINITIONS|' # r'ADD_DEPENDENCIES|ADD_EXECUTABLE|ADD_LIBRARY|ADD_SUBDIRECTORY|' # r'ADD_TEST|AUX_SOURCE_DIRECTORY|BUILD_COMMAND|BUILD_NAME|' # r'CMAKE_MINIMUM_REQUIRED|CONFIGURE_FILE|CREATE_TEST_SOURCELIST|' # r'ELSE|ELSEIF|ENABLE_LANGUAGE|ENABLE_TESTING|ENDFOREACH|' # r'ENDFUNCTION|ENDIF|ENDMACRO|ENDWHILE|EXEC_PROGRAM|' # r'EXECUTE_PROCESS|EXPORT_LIBRARY_DEPENDENCIES|FILE|FIND_FILE|' # r'FIND_LIBRARY|FIND_PACKAGE|FIND_PATH|FIND_PROGRAM|FLTK_WRAP_UI|' # r'FOREACH|FUNCTION|GET_CMAKE_PROPERTY|GET_DIRECTORY_PROPERTY|' # r'GET_FILENAME_COMPONENT|GET_SOURCE_FILE_PROPERTY|' # r'GET_TARGET_PROPERTY|GET_TEST_PROPERTY|IF|INCLUDE|' # r'INCLUDE_DIRECTORIES|INCLUDE_EXTERNAL_MSPROJECT|' # r'INCLUDE_REGULAR_EXPRESSION|INSTALL|INSTALL_FILES|' # r'INSTALL_PROGRAMS|INSTALL_TARGETS|LINK_DIRECTORIES|' # r'LINK_LIBRARIES|LIST|LOAD_CACHE|LOAD_COMMAND|MACRO|' # r'MAKE_DIRECTORY|MARK_AS_ADVANCED|MATH|MESSAGE|OPTION|' # r'OUTPUT_REQUIRED_FILES|PROJECT|QT_WRAP_CPP|QT_WRAP_UI|REMOVE|' # r'REMOVE_DEFINITIONS|SEPARATE_ARGUMENTS|SET|' # r'SET_DIRECTORY_PROPERTIES|SET_SOURCE_FILES_PROPERTIES|' # r'SET_TARGET_PROPERTIES|SET_TESTS_PROPERTIES|SITE_NAME|' # r'SOURCE_GROUP|STRING|SUBDIR_DEPENDS|SUBDIRS|' # r'TARGET_LINK_LIBRARIES|TRY_COMPILE|TRY_RUN|UNSET|' # r'USE_MANGLED_MESA|UTILITY_SOURCE|VARIABLE_REQUIRES|' # r'VTK_MAKE_INSTANTIATOR|VTK_WRAP_JAVA|VTK_WRAP_PYTHON|' # r'VTK_WRAP_TCL|WHILE|WRITE_FILE|' # r'COUNTARGS)\b', Name.Builtin, 'args'), (r'\b(\w+)([ \t]*)(\()', bygroups(Name.Builtin, Text, Punctuation), 'args'), include('keywords'), include('ws') ], 'args': [ (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'(\${)(.+?)(})', bygroups(Operator, Name.Variable, Operator)), (r'(?s)".*?"', String.Double), (r'\\\S+', String), (r'[^\)$"# \t\n]+', String), (r'\n', Text), # explicitly legal include('keywords'), include('ws') ], 'string': [ ], 'keywords': [ (r'\b(WIN32|UNIX|APPLE|CYGWIN|BORLAND|MINGW|MSVC|MSVC_IDE|MSVC60|' r'MSVC70|MSVC71|MSVC80|MSVC90)\b', Keyword), ], 'ws': [ (r'[ \t]+', Text), (r'#.+\n', Comment), ] } class HttpLexer(RegexLexer): """ Lexer for HTTP sessions. *New in Pygments 1.5.* """ name = 'HTTP' aliases = ['http'] flags = re.DOTALL def header_callback(self, match): if match.group(1).lower() == 'content-type': content_type = match.group(5).strip() if ';' in content_type: content_type = content_type[:content_type.find(';')].strip() self.content_type = content_type yield match.start(1), Name.Attribute, match.group(1) yield match.start(2), Text, match.group(2) yield match.start(3), Operator, match.group(3) yield match.start(4), Text, match.group(4) yield match.start(5), Literal, match.group(5) yield match.start(6), Text, match.group(6) def continuous_header_callback(self, match): yield match.start(1), Text, match.group(1) yield match.start(2), Literal, match.group(2) yield match.start(3), Text, match.group(3) def content_callback(self, match): content_type = getattr(self, 'content_type', None) content = match.group() offset = match.start() if content_type: from pygments.lexers import get_lexer_for_mimetype try: lexer = get_lexer_for_mimetype(content_type) except ClassNotFound: pass else: for idx, token, value in lexer.get_tokens_unprocessed(content): yield offset + idx, token, value return yield offset, Text, content tokens = { 'root': [ (r'(GET|POST|PUT|DELETE|HEAD|OPTIONS|TRACE|PATCH)( +)([^ ]+)( +)' r'(HTTP)(/)(1\.[01])(\r?\n|$)', bygroups(Name.Function, Text, Name.Namespace, Text, Keyword.Reserved, Operator, Number, Text), 'headers'), (r'(HTTP)(/)(1\.[01])( +)(\d{3})( +)([^\r\n]+)(\r?\n|$)', bygroups(Keyword.Reserved, Operator, Number, Text, Number, Text, Name.Exception, Text), 'headers'), ], 'headers': [ (r'([^\s:]+)( *)(:)( *)([^\r\n]+)(\r?\n|$)', header_callback), (r'([\t ]+)([^\r\n]+)(\r?\n|$)', continuous_header_callback), (r'\r?\n', Text, 'content') ], 'content': [ (r'.+', content_callback) ] } class PyPyLogLexer(RegexLexer): """ Lexer for PyPy log files. *New in Pygments 1.5.* """ name = "PyPy Log" aliases = ["pypylog", "pypy"] filenames = ["*.pypylog"] mimetypes = ['application/x-pypylog'] tokens = { "root": [ (r"\[\w+\] {jit-log-.*?$", Keyword, "jit-log"), (r"\[\w+\] {jit-backend-counts$", Keyword, "jit-backend-counts"), include("extra-stuff"), ], "jit-log": [ (r"\[\w+\] jit-log-.*?}$", Keyword, "#pop"), (r"^\+\d+: ", Comment), (r"--end of the loop--", Comment), (r"[ifp]\d+", Name), (r"ptr\d+", Name), (r"(\()(\w+(?:\.\w+)?)(\))", bygroups(Punctuation, Name.Builtin, Punctuation)), (r"[\[\]=,()]", Punctuation), (r"(\d+\.\d+|inf|-inf)", Number.Float), (r"-?\d+", Number.Integer), (r"'.*'", String), (r"(None|descr|ConstClass|ConstPtr|TargetToken)", Name), (r"<.*?>+", Name.Builtin), (r"(label|debug_merge_point|jump|finish)", Name.Class), (r"(int_add_ovf|int_add|int_sub_ovf|int_sub|int_mul_ovf|int_mul|" r"int_floordiv|int_mod|int_lshift|int_rshift|int_and|int_or|" r"int_xor|int_eq|int_ne|int_ge|int_gt|int_le|int_lt|int_is_zero|" r"int_is_true|" r"uint_floordiv|uint_ge|uint_lt|" r"float_add|float_sub|float_mul|float_truediv|float_neg|" r"float_eq|float_ne|float_ge|float_gt|float_le|float_lt|float_abs|" r"ptr_eq|ptr_ne|instance_ptr_eq|instance_ptr_ne|" r"cast_int_to_float|cast_float_to_int|" r"force_token|quasiimmut_field|same_as|virtual_ref_finish|" r"virtual_ref|mark_opaque_ptr|" r"call_may_force|call_assembler|call_loopinvariant|" r"call_release_gil|call_pure|call|" r"new_with_vtable|new_array|newstr|newunicode|new|" r"arraylen_gc|" r"getarrayitem_gc_pure|getarrayitem_gc|setarrayitem_gc|" r"getarrayitem_raw|setarrayitem_raw|getfield_gc_pure|" r"getfield_gc|getinteriorfield_gc|setinteriorfield_gc|" r"getfield_raw|setfield_gc|setfield_raw|" r"strgetitem|strsetitem|strlen|copystrcontent|" r"unicodegetitem|unicodesetitem|unicodelen|" r"guard_true|guard_false|guard_value|guard_isnull|" r"guard_nonnull_class|guard_nonnull|guard_class|guard_no_overflow|" r"guard_not_forced|guard_no_exception|guard_not_invalidated)", Name.Builtin), include("extra-stuff"), ], "jit-backend-counts": [ (r"\[\w+\] jit-backend-counts}$", Keyword, "#pop"), (r":", Punctuation), (r"\d+", Number), include("extra-stuff"), ], "extra-stuff": [ (r"\s+", Text), (r"#.*?$", Comment), ], } class HxmlLexer(RegexLexer): """ Lexer for `haXe build <http://haxe.org/doc/compiler>`_ files. *New in Pygments 1.6.* """ name = 'Hxml' aliases = ['haxeml', 'hxml'] filenames = ['*.hxml'] tokens = { 'root': [ # Seperator (r'(--)(next)', bygroups(Punctuation, Generic.Heading)), # Compiler switches with one dash (r'(-)(prompt|debug|v)', bygroups(Punctuation, Keyword.Keyword)), # Compilerswitches with two dashes (r'(--)(neko-source|flash-strict|flash-use-stage|no-opt|no-traces|' r'no-inline|times|no-output)', bygroups(Punctuation, Keyword)), # Targets and other options that take an argument (r'(-)(cpp|js|neko|x|as3|swf9?|swf-lib|php|xml|main|lib|D|resource|' r'cp|cmd)( +)(.+)', bygroups(Punctuation, Keyword, Whitespace, String)), # Options that take only numerical arguments (r'(-)(swf-version)( +)(\d+)', bygroups(Punctuation, Keyword, Number.Integer)), # An Option that defines the size, the fps and the background # color of an flash movie (r'(-)(swf-header)( +)(\d+)(:)(\d+)(:)(\d+)(:)([A-Fa-f0-9]{6})', bygroups(Punctuation, Keyword, Whitespace, Number.Integer, Punctuation, Number.Integer, Punctuation, Number.Integer, Punctuation, Number.Hex)), # options with two dashes that takes arguments (r'(--)(js-namespace|php-front|php-lib|remap|gen-hx-classes)( +)' r'(.+)', bygroups(Punctuation, Keyword, Whitespace, String)), # Single line comment, multiline ones are not allowed. (r'#.*', Comment.Single) ] } class EbnfLexer(RegexLexer): """ Lexer for `ISO/IEC 14977 EBNF <http://en.wikipedia.org/wiki/Extended_Backus%E2%80%93Naur_Form>`_ grammars. *New in Pygments 1.7.* """ name = 'EBNF' aliases = ['ebnf'] filenames = ['*.ebnf'] mimetypes = ['text/x-ebnf'] tokens = { 'root': [ include('whitespace'), include('comment_start'), include('identifier'), (r'=', Operator, 'production'), ], 'production': [ include('whitespace'), include('comment_start'), include('identifier'), (r'"[^"]*"', String.Double), (r"'[^']*'", String.Single), (r'(\?[^?]*\?)', Name.Entity), (r'[\[\]{}(),|]', Punctuation), (r'-', Operator), (r';', Punctuation, '#pop'), ], 'whitespace': [ (r'\s+', Text), ], 'comment_start': [ (r'\(\*', Comment.Multiline, 'comment'), ], 'comment': [ (r'[^*)]', Comment.Multiline), include('comment_start'), (r'\*\)', Comment.Multiline, '#pop'), (r'[*)]', Comment.Multiline), ], 'identifier': [ (r'([a-zA-Z][a-zA-Z0-9 \-]*)', Keyword), ], }
mit
moto-timo/ironpython3
Src/StdLib/Lib/encodings/mac_arabic.py
272
36467
""" Python Character Mapping Codec generated from 'VENDORS/APPLE/ARABIC.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_map)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='mac-arabic', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x0081: 0x00a0, # NO-BREAK SPACE, right-left 0x0082: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0083: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE 0x0084: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE 0x0085: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x0086: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x0087: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE 0x0088: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE 0x0089: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x008a: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS 0x008b: 0x06ba, # ARABIC LETTER NOON GHUNNA 0x008c: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x008d: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA 0x008e: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x008f: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE 0x0090: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x0091: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS 0x0092: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE 0x0093: 0x2026, # HORIZONTAL ELLIPSIS, right-left 0x0094: 0x00ee, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x0095: 0x00ef, # LATIN SMALL LETTER I WITH DIAERESIS 0x0096: 0x00f1, # LATIN SMALL LETTER N WITH TILDE 0x0097: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE 0x0098: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x0099: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x009a: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS 0x009b: 0x00f7, # DIVISION SIGN, right-left 0x009c: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE 0x009d: 0x00f9, # LATIN SMALL LETTER U WITH GRAVE 0x009e: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x009f: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x00a0: 0x0020, # SPACE, right-left 0x00a1: 0x0021, # EXCLAMATION MARK, right-left 0x00a2: 0x0022, # QUOTATION MARK, right-left 0x00a3: 0x0023, # NUMBER SIGN, right-left 0x00a4: 0x0024, # DOLLAR SIGN, right-left 0x00a5: 0x066a, # ARABIC PERCENT SIGN 0x00a6: 0x0026, # AMPERSAND, right-left 0x00a7: 0x0027, # APOSTROPHE, right-left 0x00a8: 0x0028, # LEFT PARENTHESIS, right-left 0x00a9: 0x0029, # RIGHT PARENTHESIS, right-left 0x00aa: 0x002a, # ASTERISK, right-left 0x00ab: 0x002b, # PLUS SIGN, right-left 0x00ac: 0x060c, # ARABIC COMMA 0x00ad: 0x002d, # HYPHEN-MINUS, right-left 0x00ae: 0x002e, # FULL STOP, right-left 0x00af: 0x002f, # SOLIDUS, right-left 0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO, right-left (need override) 0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE, right-left (need override) 0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO, right-left (need override) 0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE, right-left (need override) 0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR, right-left (need override) 0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE, right-left (need override) 0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX, right-left (need override) 0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN, right-left (need override) 0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT, right-left (need override) 0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE, right-left (need override) 0x00ba: 0x003a, # COLON, right-left 0x00bb: 0x061b, # ARABIC SEMICOLON 0x00bc: 0x003c, # LESS-THAN SIGN, right-left 0x00bd: 0x003d, # EQUALS SIGN, right-left 0x00be: 0x003e, # GREATER-THAN SIGN, right-left 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: 0x274a, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left 0x00c1: 0x0621, # ARABIC LETTER HAMZA 0x00c2: 0x0622, # ARABIC LETTER ALEF WITH MADDA ABOVE 0x00c3: 0x0623, # ARABIC LETTER ALEF WITH HAMZA ABOVE 0x00c4: 0x0624, # ARABIC LETTER WAW WITH HAMZA ABOVE 0x00c5: 0x0625, # ARABIC LETTER ALEF WITH HAMZA BELOW 0x00c6: 0x0626, # ARABIC LETTER YEH WITH HAMZA ABOVE 0x00c7: 0x0627, # ARABIC LETTER ALEF 0x00c8: 0x0628, # ARABIC LETTER BEH 0x00c9: 0x0629, # ARABIC LETTER TEH MARBUTA 0x00ca: 0x062a, # ARABIC LETTER TEH 0x00cb: 0x062b, # ARABIC LETTER THEH 0x00cc: 0x062c, # ARABIC LETTER JEEM 0x00cd: 0x062d, # ARABIC LETTER HAH 0x00ce: 0x062e, # ARABIC LETTER KHAH 0x00cf: 0x062f, # ARABIC LETTER DAL 0x00d0: 0x0630, # ARABIC LETTER THAL 0x00d1: 0x0631, # ARABIC LETTER REH 0x00d2: 0x0632, # ARABIC LETTER ZAIN 0x00d3: 0x0633, # ARABIC LETTER SEEN 0x00d4: 0x0634, # ARABIC LETTER SHEEN 0x00d5: 0x0635, # ARABIC LETTER SAD 0x00d6: 0x0636, # ARABIC LETTER DAD 0x00d7: 0x0637, # ARABIC LETTER TAH 0x00d8: 0x0638, # ARABIC LETTER ZAH 0x00d9: 0x0639, # ARABIC LETTER AIN 0x00da: 0x063a, # ARABIC LETTER GHAIN 0x00db: 0x005b, # LEFT SQUARE BRACKET, right-left 0x00dc: 0x005c, # REVERSE SOLIDUS, right-left 0x00dd: 0x005d, # RIGHT SQUARE BRACKET, right-left 0x00de: 0x005e, # CIRCUMFLEX ACCENT, right-left 0x00df: 0x005f, # LOW LINE, right-left 0x00e0: 0x0640, # ARABIC TATWEEL 0x00e1: 0x0641, # ARABIC LETTER FEH 0x00e2: 0x0642, # ARABIC LETTER QAF 0x00e3: 0x0643, # ARABIC LETTER KAF 0x00e4: 0x0644, # ARABIC LETTER LAM 0x00e5: 0x0645, # ARABIC LETTER MEEM 0x00e6: 0x0646, # ARABIC LETTER NOON 0x00e7: 0x0647, # ARABIC LETTER HEH 0x00e8: 0x0648, # ARABIC LETTER WAW 0x00e9: 0x0649, # ARABIC LETTER ALEF MAKSURA 0x00ea: 0x064a, # ARABIC LETTER YEH 0x00eb: 0x064b, # ARABIC FATHATAN 0x00ec: 0x064c, # ARABIC DAMMATAN 0x00ed: 0x064d, # ARABIC KASRATAN 0x00ee: 0x064e, # ARABIC FATHA 0x00ef: 0x064f, # ARABIC DAMMA 0x00f0: 0x0650, # ARABIC KASRA 0x00f1: 0x0651, # ARABIC SHADDA 0x00f2: 0x0652, # ARABIC SUKUN 0x00f3: 0x067e, # ARABIC LETTER PEH 0x00f4: 0x0679, # ARABIC LETTER TTEH 0x00f5: 0x0686, # ARABIC LETTER TCHEH 0x00f6: 0x06d5, # ARABIC LETTER AE 0x00f7: 0x06a4, # ARABIC LETTER VEH 0x00f8: 0x06af, # ARABIC LETTER GAF 0x00f9: 0x0688, # ARABIC LETTER DDAL 0x00fa: 0x0691, # ARABIC LETTER RREH 0x00fb: 0x007b, # LEFT CURLY BRACKET, right-left 0x00fc: 0x007c, # VERTICAL LINE, right-left 0x00fd: 0x007d, # RIGHT CURLY BRACKET, right-left 0x00fe: 0x0698, # ARABIC LETTER JEH 0x00ff: 0x06d2, # ARABIC LETTER YEH BARREE }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> CONTROL CHARACTER '\x01' # 0x0001 -> CONTROL CHARACTER '\x02' # 0x0002 -> CONTROL CHARACTER '\x03' # 0x0003 -> CONTROL CHARACTER '\x04' # 0x0004 -> CONTROL CHARACTER '\x05' # 0x0005 -> CONTROL CHARACTER '\x06' # 0x0006 -> CONTROL CHARACTER '\x07' # 0x0007 -> CONTROL CHARACTER '\x08' # 0x0008 -> CONTROL CHARACTER '\t' # 0x0009 -> CONTROL CHARACTER '\n' # 0x000a -> CONTROL CHARACTER '\x0b' # 0x000b -> CONTROL CHARACTER '\x0c' # 0x000c -> CONTROL CHARACTER '\r' # 0x000d -> CONTROL CHARACTER '\x0e' # 0x000e -> CONTROL CHARACTER '\x0f' # 0x000f -> CONTROL CHARACTER '\x10' # 0x0010 -> CONTROL CHARACTER '\x11' # 0x0011 -> CONTROL CHARACTER '\x12' # 0x0012 -> CONTROL CHARACTER '\x13' # 0x0013 -> CONTROL CHARACTER '\x14' # 0x0014 -> CONTROL CHARACTER '\x15' # 0x0015 -> CONTROL CHARACTER '\x16' # 0x0016 -> CONTROL CHARACTER '\x17' # 0x0017 -> CONTROL CHARACTER '\x18' # 0x0018 -> CONTROL CHARACTER '\x19' # 0x0019 -> CONTROL CHARACTER '\x1a' # 0x001a -> CONTROL CHARACTER '\x1b' # 0x001b -> CONTROL CHARACTER '\x1c' # 0x001c -> CONTROL CHARACTER '\x1d' # 0x001d -> CONTROL CHARACTER '\x1e' # 0x001e -> CONTROL CHARACTER '\x1f' # 0x001f -> CONTROL CHARACTER ' ' # 0x0020 -> SPACE, left-right '!' # 0x0021 -> EXCLAMATION MARK, left-right '"' # 0x0022 -> QUOTATION MARK, left-right '#' # 0x0023 -> NUMBER SIGN, left-right '$' # 0x0024 -> DOLLAR SIGN, left-right '%' # 0x0025 -> PERCENT SIGN, left-right '&' # 0x0026 -> AMPERSAND, left-right "'" # 0x0027 -> APOSTROPHE, left-right '(' # 0x0028 -> LEFT PARENTHESIS, left-right ')' # 0x0029 -> RIGHT PARENTHESIS, left-right '*' # 0x002a -> ASTERISK, left-right '+' # 0x002b -> PLUS SIGN, left-right ',' # 0x002c -> COMMA, left-right; in Arabic-script context, displayed as 0x066C ARABIC THOUSANDS SEPARATOR '-' # 0x002d -> HYPHEN-MINUS, left-right '.' # 0x002e -> FULL STOP, left-right; in Arabic-script context, displayed as 0x066B ARABIC DECIMAL SEPARATOR '/' # 0x002f -> SOLIDUS, left-right '0' # 0x0030 -> DIGIT ZERO; in Arabic-script context, displayed as 0x0660 ARABIC-INDIC DIGIT ZERO '1' # 0x0031 -> DIGIT ONE; in Arabic-script context, displayed as 0x0661 ARABIC-INDIC DIGIT ONE '2' # 0x0032 -> DIGIT TWO; in Arabic-script context, displayed as 0x0662 ARABIC-INDIC DIGIT TWO '3' # 0x0033 -> DIGIT THREE; in Arabic-script context, displayed as 0x0663 ARABIC-INDIC DIGIT THREE '4' # 0x0034 -> DIGIT FOUR; in Arabic-script context, displayed as 0x0664 ARABIC-INDIC DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE; in Arabic-script context, displayed as 0x0665 ARABIC-INDIC DIGIT FIVE '6' # 0x0036 -> DIGIT SIX; in Arabic-script context, displayed as 0x0666 ARABIC-INDIC DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN; in Arabic-script context, displayed as 0x0667 ARABIC-INDIC DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT; in Arabic-script context, displayed as 0x0668 ARABIC-INDIC DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE; in Arabic-script context, displayed as 0x0669 ARABIC-INDIC DIGIT NINE ':' # 0x003a -> COLON, left-right ';' # 0x003b -> SEMICOLON, left-right '<' # 0x003c -> LESS-THAN SIGN, left-right '=' # 0x003d -> EQUALS SIGN, left-right '>' # 0x003e -> GREATER-THAN SIGN, left-right '?' # 0x003f -> QUESTION MARK, left-right '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET, left-right '\\' # 0x005c -> REVERSE SOLIDUS, left-right ']' # 0x005d -> RIGHT SQUARE BRACKET, left-right '^' # 0x005e -> CIRCUMFLEX ACCENT, left-right '_' # 0x005f -> LOW LINE, left-right '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET, left-right '|' # 0x007c -> VERTICAL LINE, left-right '}' # 0x007d -> RIGHT CURLY BRACKET, left-right '~' # 0x007e -> TILDE '\x7f' # 0x007f -> CONTROL CHARACTER '\xc4' # 0x0080 -> LATIN CAPITAL LETTER A WITH DIAERESIS '\xa0' # 0x0081 -> NO-BREAK SPACE, right-left '\xc7' # 0x0082 -> LATIN CAPITAL LETTER C WITH CEDILLA '\xc9' # 0x0083 -> LATIN CAPITAL LETTER E WITH ACUTE '\xd1' # 0x0084 -> LATIN CAPITAL LETTER N WITH TILDE '\xd6' # 0x0085 -> LATIN CAPITAL LETTER O WITH DIAERESIS '\xdc' # 0x0086 -> LATIN CAPITAL LETTER U WITH DIAERESIS '\xe1' # 0x0087 -> LATIN SMALL LETTER A WITH ACUTE '\xe0' # 0x0088 -> LATIN SMALL LETTER A WITH GRAVE '\xe2' # 0x0089 -> LATIN SMALL LETTER A WITH CIRCUMFLEX '\xe4' # 0x008a -> LATIN SMALL LETTER A WITH DIAERESIS '\u06ba' # 0x008b -> ARABIC LETTER NOON GHUNNA '\xab' # 0x008c -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left '\xe7' # 0x008d -> LATIN SMALL LETTER C WITH CEDILLA '\xe9' # 0x008e -> LATIN SMALL LETTER E WITH ACUTE '\xe8' # 0x008f -> LATIN SMALL LETTER E WITH GRAVE '\xea' # 0x0090 -> LATIN SMALL LETTER E WITH CIRCUMFLEX '\xeb' # 0x0091 -> LATIN SMALL LETTER E WITH DIAERESIS '\xed' # 0x0092 -> LATIN SMALL LETTER I WITH ACUTE '\u2026' # 0x0093 -> HORIZONTAL ELLIPSIS, right-left '\xee' # 0x0094 -> LATIN SMALL LETTER I WITH CIRCUMFLEX '\xef' # 0x0095 -> LATIN SMALL LETTER I WITH DIAERESIS '\xf1' # 0x0096 -> LATIN SMALL LETTER N WITH TILDE '\xf3' # 0x0097 -> LATIN SMALL LETTER O WITH ACUTE '\xbb' # 0x0098 -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left '\xf4' # 0x0099 -> LATIN SMALL LETTER O WITH CIRCUMFLEX '\xf6' # 0x009a -> LATIN SMALL LETTER O WITH DIAERESIS '\xf7' # 0x009b -> DIVISION SIGN, right-left '\xfa' # 0x009c -> LATIN SMALL LETTER U WITH ACUTE '\xf9' # 0x009d -> LATIN SMALL LETTER U WITH GRAVE '\xfb' # 0x009e -> LATIN SMALL LETTER U WITH CIRCUMFLEX '\xfc' # 0x009f -> LATIN SMALL LETTER U WITH DIAERESIS ' ' # 0x00a0 -> SPACE, right-left '!' # 0x00a1 -> EXCLAMATION MARK, right-left '"' # 0x00a2 -> QUOTATION MARK, right-left '#' # 0x00a3 -> NUMBER SIGN, right-left '$' # 0x00a4 -> DOLLAR SIGN, right-left '\u066a' # 0x00a5 -> ARABIC PERCENT SIGN '&' # 0x00a6 -> AMPERSAND, right-left "'" # 0x00a7 -> APOSTROPHE, right-left '(' # 0x00a8 -> LEFT PARENTHESIS, right-left ')' # 0x00a9 -> RIGHT PARENTHESIS, right-left '*' # 0x00aa -> ASTERISK, right-left '+' # 0x00ab -> PLUS SIGN, right-left '\u060c' # 0x00ac -> ARABIC COMMA '-' # 0x00ad -> HYPHEN-MINUS, right-left '.' # 0x00ae -> FULL STOP, right-left '/' # 0x00af -> SOLIDUS, right-left '\u0660' # 0x00b0 -> ARABIC-INDIC DIGIT ZERO, right-left (need override) '\u0661' # 0x00b1 -> ARABIC-INDIC DIGIT ONE, right-left (need override) '\u0662' # 0x00b2 -> ARABIC-INDIC DIGIT TWO, right-left (need override) '\u0663' # 0x00b3 -> ARABIC-INDIC DIGIT THREE, right-left (need override) '\u0664' # 0x00b4 -> ARABIC-INDIC DIGIT FOUR, right-left (need override) '\u0665' # 0x00b5 -> ARABIC-INDIC DIGIT FIVE, right-left (need override) '\u0666' # 0x00b6 -> ARABIC-INDIC DIGIT SIX, right-left (need override) '\u0667' # 0x00b7 -> ARABIC-INDIC DIGIT SEVEN, right-left (need override) '\u0668' # 0x00b8 -> ARABIC-INDIC DIGIT EIGHT, right-left (need override) '\u0669' # 0x00b9 -> ARABIC-INDIC DIGIT NINE, right-left (need override) ':' # 0x00ba -> COLON, right-left '\u061b' # 0x00bb -> ARABIC SEMICOLON '<' # 0x00bc -> LESS-THAN SIGN, right-left '=' # 0x00bd -> EQUALS SIGN, right-left '>' # 0x00be -> GREATER-THAN SIGN, right-left '\u061f' # 0x00bf -> ARABIC QUESTION MARK '\u274a' # 0x00c0 -> EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left '\u0621' # 0x00c1 -> ARABIC LETTER HAMZA '\u0622' # 0x00c2 -> ARABIC LETTER ALEF WITH MADDA ABOVE '\u0623' # 0x00c3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE '\u0624' # 0x00c4 -> ARABIC LETTER WAW WITH HAMZA ABOVE '\u0625' # 0x00c5 -> ARABIC LETTER ALEF WITH HAMZA BELOW '\u0626' # 0x00c6 -> ARABIC LETTER YEH WITH HAMZA ABOVE '\u0627' # 0x00c7 -> ARABIC LETTER ALEF '\u0628' # 0x00c8 -> ARABIC LETTER BEH '\u0629' # 0x00c9 -> ARABIC LETTER TEH MARBUTA '\u062a' # 0x00ca -> ARABIC LETTER TEH '\u062b' # 0x00cb -> ARABIC LETTER THEH '\u062c' # 0x00cc -> ARABIC LETTER JEEM '\u062d' # 0x00cd -> ARABIC LETTER HAH '\u062e' # 0x00ce -> ARABIC LETTER KHAH '\u062f' # 0x00cf -> ARABIC LETTER DAL '\u0630' # 0x00d0 -> ARABIC LETTER THAL '\u0631' # 0x00d1 -> ARABIC LETTER REH '\u0632' # 0x00d2 -> ARABIC LETTER ZAIN '\u0633' # 0x00d3 -> ARABIC LETTER SEEN '\u0634' # 0x00d4 -> ARABIC LETTER SHEEN '\u0635' # 0x00d5 -> ARABIC LETTER SAD '\u0636' # 0x00d6 -> ARABIC LETTER DAD '\u0637' # 0x00d7 -> ARABIC LETTER TAH '\u0638' # 0x00d8 -> ARABIC LETTER ZAH '\u0639' # 0x00d9 -> ARABIC LETTER AIN '\u063a' # 0x00da -> ARABIC LETTER GHAIN '[' # 0x00db -> LEFT SQUARE BRACKET, right-left '\\' # 0x00dc -> REVERSE SOLIDUS, right-left ']' # 0x00dd -> RIGHT SQUARE BRACKET, right-left '^' # 0x00de -> CIRCUMFLEX ACCENT, right-left '_' # 0x00df -> LOW LINE, right-left '\u0640' # 0x00e0 -> ARABIC TATWEEL '\u0641' # 0x00e1 -> ARABIC LETTER FEH '\u0642' # 0x00e2 -> ARABIC LETTER QAF '\u0643' # 0x00e3 -> ARABIC LETTER KAF '\u0644' # 0x00e4 -> ARABIC LETTER LAM '\u0645' # 0x00e5 -> ARABIC LETTER MEEM '\u0646' # 0x00e6 -> ARABIC LETTER NOON '\u0647' # 0x00e7 -> ARABIC LETTER HEH '\u0648' # 0x00e8 -> ARABIC LETTER WAW '\u0649' # 0x00e9 -> ARABIC LETTER ALEF MAKSURA '\u064a' # 0x00ea -> ARABIC LETTER YEH '\u064b' # 0x00eb -> ARABIC FATHATAN '\u064c' # 0x00ec -> ARABIC DAMMATAN '\u064d' # 0x00ed -> ARABIC KASRATAN '\u064e' # 0x00ee -> ARABIC FATHA '\u064f' # 0x00ef -> ARABIC DAMMA '\u0650' # 0x00f0 -> ARABIC KASRA '\u0651' # 0x00f1 -> ARABIC SHADDA '\u0652' # 0x00f2 -> ARABIC SUKUN '\u067e' # 0x00f3 -> ARABIC LETTER PEH '\u0679' # 0x00f4 -> ARABIC LETTER TTEH '\u0686' # 0x00f5 -> ARABIC LETTER TCHEH '\u06d5' # 0x00f6 -> ARABIC LETTER AE '\u06a4' # 0x00f7 -> ARABIC LETTER VEH '\u06af' # 0x00f8 -> ARABIC LETTER GAF '\u0688' # 0x00f9 -> ARABIC LETTER DDAL '\u0691' # 0x00fa -> ARABIC LETTER RREH '{' # 0x00fb -> LEFT CURLY BRACKET, right-left '|' # 0x00fc -> VERTICAL LINE, right-left '}' # 0x00fd -> RIGHT CURLY BRACKET, right-left '\u0698' # 0x00fe -> ARABIC LETTER JEH '\u06d2' # 0x00ff -> ARABIC LETTER YEH BARREE ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # CONTROL CHARACTER 0x0001: 0x0001, # CONTROL CHARACTER 0x0002: 0x0002, # CONTROL CHARACTER 0x0003: 0x0003, # CONTROL CHARACTER 0x0004: 0x0004, # CONTROL CHARACTER 0x0005: 0x0005, # CONTROL CHARACTER 0x0006: 0x0006, # CONTROL CHARACTER 0x0007: 0x0007, # CONTROL CHARACTER 0x0008: 0x0008, # CONTROL CHARACTER 0x0009: 0x0009, # CONTROL CHARACTER 0x000a: 0x000a, # CONTROL CHARACTER 0x000b: 0x000b, # CONTROL CHARACTER 0x000c: 0x000c, # CONTROL CHARACTER 0x000d: 0x000d, # CONTROL CHARACTER 0x000e: 0x000e, # CONTROL CHARACTER 0x000f: 0x000f, # CONTROL CHARACTER 0x0010: 0x0010, # CONTROL CHARACTER 0x0011: 0x0011, # CONTROL CHARACTER 0x0012: 0x0012, # CONTROL CHARACTER 0x0013: 0x0013, # CONTROL CHARACTER 0x0014: 0x0014, # CONTROL CHARACTER 0x0015: 0x0015, # CONTROL CHARACTER 0x0016: 0x0016, # CONTROL CHARACTER 0x0017: 0x0017, # CONTROL CHARACTER 0x0018: 0x0018, # CONTROL CHARACTER 0x0019: 0x0019, # CONTROL CHARACTER 0x001a: 0x001a, # CONTROL CHARACTER 0x001b: 0x001b, # CONTROL CHARACTER 0x001c: 0x001c, # CONTROL CHARACTER 0x001d: 0x001d, # CONTROL CHARACTER 0x001e: 0x001e, # CONTROL CHARACTER 0x001f: 0x001f, # CONTROL CHARACTER 0x0020: 0x0020, # SPACE, left-right 0x0020: 0x00a0, # SPACE, right-left 0x0021: 0x0021, # EXCLAMATION MARK, left-right 0x0021: 0x00a1, # EXCLAMATION MARK, right-left 0x0022: 0x0022, # QUOTATION MARK, left-right 0x0022: 0x00a2, # QUOTATION MARK, right-left 0x0023: 0x0023, # NUMBER SIGN, left-right 0x0023: 0x00a3, # NUMBER SIGN, right-left 0x0024: 0x0024, # DOLLAR SIGN, left-right 0x0024: 0x00a4, # DOLLAR SIGN, right-left 0x0025: 0x0025, # PERCENT SIGN, left-right 0x0026: 0x0026, # AMPERSAND, left-right 0x0026: 0x00a6, # AMPERSAND, right-left 0x0027: 0x0027, # APOSTROPHE, left-right 0x0027: 0x00a7, # APOSTROPHE, right-left 0x0028: 0x0028, # LEFT PARENTHESIS, left-right 0x0028: 0x00a8, # LEFT PARENTHESIS, right-left 0x0029: 0x0029, # RIGHT PARENTHESIS, left-right 0x0029: 0x00a9, # RIGHT PARENTHESIS, right-left 0x002a: 0x002a, # ASTERISK, left-right 0x002a: 0x00aa, # ASTERISK, right-left 0x002b: 0x002b, # PLUS SIGN, left-right 0x002b: 0x00ab, # PLUS SIGN, right-left 0x002c: 0x002c, # COMMA, left-right; in Arabic-script context, displayed as 0x066C ARABIC THOUSANDS SEPARATOR 0x002d: 0x002d, # HYPHEN-MINUS, left-right 0x002d: 0x00ad, # HYPHEN-MINUS, right-left 0x002e: 0x002e, # FULL STOP, left-right; in Arabic-script context, displayed as 0x066B ARABIC DECIMAL SEPARATOR 0x002e: 0x00ae, # FULL STOP, right-left 0x002f: 0x002f, # SOLIDUS, left-right 0x002f: 0x00af, # SOLIDUS, right-left 0x0030: 0x0030, # DIGIT ZERO; in Arabic-script context, displayed as 0x0660 ARABIC-INDIC DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE; in Arabic-script context, displayed as 0x0661 ARABIC-INDIC DIGIT ONE 0x0032: 0x0032, # DIGIT TWO; in Arabic-script context, displayed as 0x0662 ARABIC-INDIC DIGIT TWO 0x0033: 0x0033, # DIGIT THREE; in Arabic-script context, displayed as 0x0663 ARABIC-INDIC DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR; in Arabic-script context, displayed as 0x0664 ARABIC-INDIC DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE; in Arabic-script context, displayed as 0x0665 ARABIC-INDIC DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX; in Arabic-script context, displayed as 0x0666 ARABIC-INDIC DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN; in Arabic-script context, displayed as 0x0667 ARABIC-INDIC DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT; in Arabic-script context, displayed as 0x0668 ARABIC-INDIC DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE; in Arabic-script context, displayed as 0x0669 ARABIC-INDIC DIGIT NINE 0x003a: 0x003a, # COLON, left-right 0x003a: 0x00ba, # COLON, right-left 0x003b: 0x003b, # SEMICOLON, left-right 0x003c: 0x003c, # LESS-THAN SIGN, left-right 0x003c: 0x00bc, # LESS-THAN SIGN, right-left 0x003d: 0x003d, # EQUALS SIGN, left-right 0x003d: 0x00bd, # EQUALS SIGN, right-left 0x003e: 0x003e, # GREATER-THAN SIGN, left-right 0x003e: 0x00be, # GREATER-THAN SIGN, right-left 0x003f: 0x003f, # QUESTION MARK, left-right 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET, left-right 0x005b: 0x00db, # LEFT SQUARE BRACKET, right-left 0x005c: 0x005c, # REVERSE SOLIDUS, left-right 0x005c: 0x00dc, # REVERSE SOLIDUS, right-left 0x005d: 0x005d, # RIGHT SQUARE BRACKET, left-right 0x005d: 0x00dd, # RIGHT SQUARE BRACKET, right-left 0x005e: 0x005e, # CIRCUMFLEX ACCENT, left-right 0x005e: 0x00de, # CIRCUMFLEX ACCENT, right-left 0x005f: 0x005f, # LOW LINE, left-right 0x005f: 0x00df, # LOW LINE, right-left 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET, left-right 0x007b: 0x00fb, # LEFT CURLY BRACKET, right-left 0x007c: 0x007c, # VERTICAL LINE, left-right 0x007c: 0x00fc, # VERTICAL LINE, right-left 0x007d: 0x007d, # RIGHT CURLY BRACKET, left-right 0x007d: 0x00fd, # RIGHT CURLY BRACKET, right-left 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # CONTROL CHARACTER 0x00a0: 0x0081, # NO-BREAK SPACE, right-left 0x00ab: 0x008c, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x00bb: 0x0098, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK, right-left 0x00c4: 0x0080, # LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c7: 0x0082, # LATIN CAPITAL LETTER C WITH CEDILLA 0x00c9: 0x0083, # LATIN CAPITAL LETTER E WITH ACUTE 0x00d1: 0x0084, # LATIN CAPITAL LETTER N WITH TILDE 0x00d6: 0x0085, # LATIN CAPITAL LETTER O WITH DIAERESIS 0x00dc: 0x0086, # LATIN CAPITAL LETTER U WITH DIAERESIS 0x00e0: 0x0088, # LATIN SMALL LETTER A WITH GRAVE 0x00e1: 0x0087, # LATIN SMALL LETTER A WITH ACUTE 0x00e2: 0x0089, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4: 0x008a, # LATIN SMALL LETTER A WITH DIAERESIS 0x00e7: 0x008d, # LATIN SMALL LETTER C WITH CEDILLA 0x00e8: 0x008f, # LATIN SMALL LETTER E WITH GRAVE 0x00e9: 0x008e, # LATIN SMALL LETTER E WITH ACUTE 0x00ea: 0x0090, # LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb: 0x0091, # LATIN SMALL LETTER E WITH DIAERESIS 0x00ed: 0x0092, # LATIN SMALL LETTER I WITH ACUTE 0x00ee: 0x0094, # LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ef: 0x0095, # LATIN SMALL LETTER I WITH DIAERESIS 0x00f1: 0x0096, # LATIN SMALL LETTER N WITH TILDE 0x00f3: 0x0097, # LATIN SMALL LETTER O WITH ACUTE 0x00f4: 0x0099, # LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6: 0x009a, # LATIN SMALL LETTER O WITH DIAERESIS 0x00f7: 0x009b, # DIVISION SIGN, right-left 0x00f9: 0x009d, # LATIN SMALL LETTER U WITH GRAVE 0x00fa: 0x009c, # LATIN SMALL LETTER U WITH ACUTE 0x00fb: 0x009e, # LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00fc: 0x009f, # LATIN SMALL LETTER U WITH DIAERESIS 0x060c: 0x00ac, # ARABIC COMMA 0x061b: 0x00bb, # ARABIC SEMICOLON 0x061f: 0x00bf, # ARABIC QUESTION MARK 0x0621: 0x00c1, # ARABIC LETTER HAMZA 0x0622: 0x00c2, # ARABIC LETTER ALEF WITH MADDA ABOVE 0x0623: 0x00c3, # ARABIC LETTER ALEF WITH HAMZA ABOVE 0x0624: 0x00c4, # ARABIC LETTER WAW WITH HAMZA ABOVE 0x0625: 0x00c5, # ARABIC LETTER ALEF WITH HAMZA BELOW 0x0626: 0x00c6, # ARABIC LETTER YEH WITH HAMZA ABOVE 0x0627: 0x00c7, # ARABIC LETTER ALEF 0x0628: 0x00c8, # ARABIC LETTER BEH 0x0629: 0x00c9, # ARABIC LETTER TEH MARBUTA 0x062a: 0x00ca, # ARABIC LETTER TEH 0x062b: 0x00cb, # ARABIC LETTER THEH 0x062c: 0x00cc, # ARABIC LETTER JEEM 0x062d: 0x00cd, # ARABIC LETTER HAH 0x062e: 0x00ce, # ARABIC LETTER KHAH 0x062f: 0x00cf, # ARABIC LETTER DAL 0x0630: 0x00d0, # ARABIC LETTER THAL 0x0631: 0x00d1, # ARABIC LETTER REH 0x0632: 0x00d2, # ARABIC LETTER ZAIN 0x0633: 0x00d3, # ARABIC LETTER SEEN 0x0634: 0x00d4, # ARABIC LETTER SHEEN 0x0635: 0x00d5, # ARABIC LETTER SAD 0x0636: 0x00d6, # ARABIC LETTER DAD 0x0637: 0x00d7, # ARABIC LETTER TAH 0x0638: 0x00d8, # ARABIC LETTER ZAH 0x0639: 0x00d9, # ARABIC LETTER AIN 0x063a: 0x00da, # ARABIC LETTER GHAIN 0x0640: 0x00e0, # ARABIC TATWEEL 0x0641: 0x00e1, # ARABIC LETTER FEH 0x0642: 0x00e2, # ARABIC LETTER QAF 0x0643: 0x00e3, # ARABIC LETTER KAF 0x0644: 0x00e4, # ARABIC LETTER LAM 0x0645: 0x00e5, # ARABIC LETTER MEEM 0x0646: 0x00e6, # ARABIC LETTER NOON 0x0647: 0x00e7, # ARABIC LETTER HEH 0x0648: 0x00e8, # ARABIC LETTER WAW 0x0649: 0x00e9, # ARABIC LETTER ALEF MAKSURA 0x064a: 0x00ea, # ARABIC LETTER YEH 0x064b: 0x00eb, # ARABIC FATHATAN 0x064c: 0x00ec, # ARABIC DAMMATAN 0x064d: 0x00ed, # ARABIC KASRATAN 0x064e: 0x00ee, # ARABIC FATHA 0x064f: 0x00ef, # ARABIC DAMMA 0x0650: 0x00f0, # ARABIC KASRA 0x0651: 0x00f1, # ARABIC SHADDA 0x0652: 0x00f2, # ARABIC SUKUN 0x0660: 0x00b0, # ARABIC-INDIC DIGIT ZERO, right-left (need override) 0x0661: 0x00b1, # ARABIC-INDIC DIGIT ONE, right-left (need override) 0x0662: 0x00b2, # ARABIC-INDIC DIGIT TWO, right-left (need override) 0x0663: 0x00b3, # ARABIC-INDIC DIGIT THREE, right-left (need override) 0x0664: 0x00b4, # ARABIC-INDIC DIGIT FOUR, right-left (need override) 0x0665: 0x00b5, # ARABIC-INDIC DIGIT FIVE, right-left (need override) 0x0666: 0x00b6, # ARABIC-INDIC DIGIT SIX, right-left (need override) 0x0667: 0x00b7, # ARABIC-INDIC DIGIT SEVEN, right-left (need override) 0x0668: 0x00b8, # ARABIC-INDIC DIGIT EIGHT, right-left (need override) 0x0669: 0x00b9, # ARABIC-INDIC DIGIT NINE, right-left (need override) 0x066a: 0x00a5, # ARABIC PERCENT SIGN 0x0679: 0x00f4, # ARABIC LETTER TTEH 0x067e: 0x00f3, # ARABIC LETTER PEH 0x0686: 0x00f5, # ARABIC LETTER TCHEH 0x0688: 0x00f9, # ARABIC LETTER DDAL 0x0691: 0x00fa, # ARABIC LETTER RREH 0x0698: 0x00fe, # ARABIC LETTER JEH 0x06a4: 0x00f7, # ARABIC LETTER VEH 0x06af: 0x00f8, # ARABIC LETTER GAF 0x06ba: 0x008b, # ARABIC LETTER NOON GHUNNA 0x06d2: 0x00ff, # ARABIC LETTER YEH BARREE 0x06d5: 0x00f6, # ARABIC LETTER AE 0x2026: 0x0093, # HORIZONTAL ELLIPSIS, right-left 0x274a: 0x00c0, # EIGHT TEARDROP-SPOKED PROPELLER ASTERISK, right-left }
apache-2.0
nghiattran/self-steering
submission.py
1
3899
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Author: Nghia Tran """ Generate csv for predicting steering angles. Usage: usage: submission.py [-h] [--limit LIMIT] [--save SAVE] logdir test_folder Create submission for Udacity. positional arguments: logdir Path to logdir. test_folder Path to test folder. optional arguments: -h, --help show this help message and exit --limit LIMIT, -l LIMIT Number of files. --save SAVE, -s SAVE Save file. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import time import argparse import os import sys import logging from inputs.udacity_input import load_image def load(logdir): import tensorflow as tf import tensorvision.utils as tv_utils import tensorvision.core as core tv_utils.set_gpus_to_use() # Loading hyperparameters from logdir hypes = tv_utils.load_hypes_from_logdir(logdir, base_path='hypes') logging.info("Hypes loaded successfully.") # Loading tv modules (encoder.py, decoder.py, eval.py) from logdir modules = tv_utils.load_modules_from_logdir(logdir) logging.info("Modules loaded successfully. Starting to build tf graph.") with tf.Graph().as_default(): # Create placeholder for input image_pl = tf.placeholder(tf.float32, shape=(hypes["image_height"], hypes["image_width"], 3)) image = tf.expand_dims(image_pl, 0) # build Tensorflow graph using the model from logdir prediction = core.build_inference_graph(hypes, modules, image=image) logging.info("Graph build successfully.") # Create a session for running Ops on the Graph. sess = tf.Session() saver = tf.train.Saver() # Load weights from logdir core.load_weights(logdir, sess, saver) logging.info("Weights loaded successfully.") return image_pl, prediction, sess, hypes def main(): logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', level=logging.INFO, stream=sys.stdout) parser = argparse.ArgumentParser(description='Create submission for Udacity.') parser.add_argument('logdir', type=str, help='Path to logdir.') parser.add_argument('test_folder', type=str, help='Path to test folder.') parser.add_argument('--limit', '-l', type=int, default=-1, help='Number of files.') parser.add_argument('--save', '-s', type=str, default='submission.csv', help='Save file.') args = parser.parse_args() logdir = args.logdir image_pl, prediction, sess, hypes = load(logdir) save_file = args.save files = sorted(os.listdir(args.test_folder))[:args.limit] if len(files) == 0: logging.warning('No image found at path %s' % args.test_folder) exit(1) start = time.time() with open(save_file, 'w') as f: f.write('frame_id,steering_angle\n') for i, file in enumerate(files): sys.stdout.write('\r>> Processubg %d/%d images' % (i + 1, len(files))) sys.stdout.flush() filepath = os.path.join(args.test_folder, file) img = load_image(path=filepath, hypes=hypes) feed = {image_pl: img} output = prediction['output'] pred = sess.run(output, feed_dict=feed) pred = pred[0][0] frame_id = os.path.splitext(file)[0] f.write('%s,%f\n' % (frame_id, pred)) time_taken = time.time() - start logging.info('Video saved as %s' % save_file) logging.info('Number of images: %d' % len(files)) logging.info('Time takes: %.2f s' % (time_taken)) logging.info('Frequency: %.2f fps' % (len(files) / time_taken)) if __name__ == '__main__': main()
mit
thnee/ansible
test/units/cli/arguments/test_optparse_helpers.py
31
1127
# -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import pytest from ansible import constants as C from ansible.cli.arguments import option_helpers as opt_help from ansible import __path__ as ansible_path from ansible.release import __version__ as ansible_version if C.DEFAULT_MODULE_PATH is None: cpath = u'Default w/o overrides' else: cpath = C.DEFAULT_MODULE_PATH FAKE_PROG = u'ansible-cli-test' VERSION_OUTPUT = opt_help.version(prog=FAKE_PROG) @pytest.mark.parametrize( 'must_have', [ FAKE_PROG + u' %s' % ansible_version, u'config file = %s' % C.CONFIG_FILE, u'configured module search path = %s' % cpath, u'ansible python module location = %s' % ':'.join(ansible_path), u'executable location = ', u'python version = %s' % ''.join(sys.version.splitlines()), ] ) def test_option_helper_version(must_have): assert must_have in VERSION_OUTPUT
gpl-3.0
ixdy/kubernetes-test-infra
gubernator/third_party/defusedxml/pulldom.py
64
1162
# defusedxml # # Copyright (c) 2013 by Christian Heimes <christian@python.org> # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. """Defused xml.dom.pulldom """ from __future__ import print_function, absolute_import from xml.dom.pulldom import parse as _parse from xml.dom.pulldom import parseString as _parseString from .sax import make_parser __origin__ = "xml.dom.pulldom" def parse(stream_or_string, parser=None, bufsize=None, forbid_dtd=False, forbid_entities=True, forbid_external=True): if parser is None: parser = make_parser() parser.forbid_dtd = forbid_dtd parser.forbid_entities = forbid_entities parser.forbid_external = forbid_external return _parse(stream_or_string, parser, bufsize) def parseString(string, parser=None, forbid_dtd=False, forbid_entities=True, forbid_external=True): if parser is None: parser = make_parser() parser.forbid_dtd = forbid_dtd parser.forbid_entities = forbid_entities parser.forbid_external = forbid_external return _parseString(string, parser)
apache-2.0
SOMACMU/trippins
webapps/trippins/tests.py
1
3548
from django.test import TestCase from django.contrib.auth import SESSION_KEY from django.core.urlresolvers import reverse from trippins.models import * class AccountManagementTest(TestCase): def create_tmp_user(self): user = User(username="test-use") user.set_password('123') user.save() t_user = TripUser(user=user) t_user.save() def test_register(self): registration = {} registration['username'] = 'test-use' registration['email'] = 'test@trippins.us' registration['first_name'] = 'Test' registration['last_name'] = 'Test' registration['password1'] = '123' registration['password2'] = '123' resp = self.client.post(reverse('registration'),registration) self.assertEqual( len(User.objects.filter(username=registration['username'])), 1 ) user = User.objects.get(username=registration['username']) self.assertEqual( len(TripUser.objects.filter(user=user)), 1 ) self.assertRedirects(resp, reverse('index')) def test_legal_login(self): self.create_tmp_user() login = {} login['username'] = 'test-use' login['password'] = '123' self.client.post(reverse('login'), login) self.assertTrue(SESSION_KEY in self.client.session) def test_illegal_login(self): self.create_tmp_user() login = {} login['username'] = 'test-use' login['password'] = '12345' self.client.post(reverse('login'), login) self.assertFalse(SESSION_KEY in self.client.session) class PinManagementTest(TestCase): username = 'do-not-touch-it' password = '1234' def create_tmp_user(self): user = User(username=self.username) user.set_password(self.password) user.save() self.user = user t_user = TripUser(user=user) t_user.save() self.t_user = t_user def login_helper(self): self.create_tmp_user() self.client.login(username=self.username, password=self.password) def temp_pin_helper(self): tPin = tempPin(user=self.t_user, photos='[]') tPin.save() return tPin def pin_helper(self): pin = Pin(user=self.t_user) pin.save() return pin def test_temp_pin_creation(self): self.login_helper() pin_info = {} pin_info['longtitude'] = 123 pin_info['latitude'] = 123 resp = self.client.post(reverse('create_temp_pin'), pin_info) self.assertEquals(len(tempPin.objects.filter(id=resp.content)), 1) def test_pin_creation(self): self.login_helper() tPin = self.temp_pin_helper() pin_info = {} pin_info['private'] = 'true' pin_info['desc'] = "" resp = self.client.post(reverse('create_pin', kwargs={'pid':tPin.id}), pin_info) self.assertEquals(len(tempPin.objects.filter(id=tPin.id)), 0) self.assertEquals(len(Pin.objects.filter(id=resp.content)), 1) def test_temp_pin_deletion(self): self.login_helper() tPin = self.temp_pin_helper() self.client.get(reverse('cancel_pin', kwargs={'pid':tPin.id})) self.assertEquals(len(tempPin.objects.filter(id=tPin.id)), 0) def test_pin_deletion(self): self.login_helper() pin = self.pin_helper() self.client.get(reverse('delete_pin', kwargs={'pid': pin.id})) self.assertEquals(len(Pin.objects.filter(id=pin.id)), 0)
gpl-3.0
JingJunYin/tensorflow
tensorflow/python/framework/tensor_shape.py
36
28237
# 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. # ============================================================================== """Helper classes for tensor shape inference.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import tensor_shape_pb2 from tensorflow.python.util import compat class Dimension(object): """Represents the value of one dimension in a TensorShape.""" def __init__(self, value): """Creates a new Dimension with the given value.""" if value is None: self._value = None else: self._value = int(value) if (not isinstance(value, compat.bytes_or_text_types) and self._value != value): raise ValueError("Ambiguous dimension: %s" % value) if self._value < 0: raise ValueError("Dimension %d must be >= 0" % self._value) def __repr__(self): return "Dimension(%s)" % repr(self._value) def __str__(self): value = self._value return "?" if value is None else str(value) def __eq__(self, other): """Returns true if `other` has the same known value as this Dimension.""" try: other = as_dimension(other) except (TypeError, ValueError): return NotImplemented if self._value is None or other.value is None: return None return self._value == other.value def __ne__(self, other): """Returns true if `other` has a different known value from `self`.""" try: other = as_dimension(other) except (TypeError, ValueError): return NotImplemented if self._value is None or other.value is None: return None return self._value != other.value def __int__(self): return self._value # This is needed for Windows. # See https://github.com/tensorflow/tensorflow/pull/9780 def __long__(self): return self._value def __index__(self): # Allow use in Python 3 range return self._value @property def value(self): """The value of this dimension, or None if it is unknown.""" return self._value def is_compatible_with(self, other): """Returns true if `other` is compatible with this Dimension. Two known Dimensions are compatible if they have the same value. An unknown Dimension is compatible with all other Dimensions. Args: other: Another Dimension. Returns: True if this Dimension and `other` are compatible. """ other = as_dimension(other) return (self._value is None or other.value is None or self._value == other.value) def assert_is_compatible_with(self, other): """Raises an exception if `other` is not compatible with this Dimension. Args: other: Another Dimension. Raises: ValueError: If `self` and `other` are not compatible (see is_compatible_with). """ if not self.is_compatible_with(other): raise ValueError("Dimensions %s and %s are not compatible" % (self, other)) def merge_with(self, other): """Returns a Dimension that combines the information in `self` and `other`. Dimensions are combined as follows: ```python tf.Dimension(n) .merge_with(tf.Dimension(n)) == tf.Dimension(n) tf.Dimension(n) .merge_with(tf.Dimension(None)) == tf.Dimension(n) tf.Dimension(None).merge_with(tf.Dimension(n)) == tf.Dimension(n) tf.Dimension(None).merge_with(tf.Dimension(None)) == tf.Dimension(None) tf.Dimension(n) .merge_with(tf.Dimension(m)) # raises ValueError for n != m ``` Args: other: Another Dimension. Returns: A Dimension containing the combined information of `self` and `other`. Raises: ValueError: If `self` and `other` are not compatible (see is_compatible_with). """ other = as_dimension(other) self.assert_is_compatible_with(other) if self._value is None: return Dimension(other.value) else: return Dimension(self._value) def __add__(self, other): """Returns the sum of `self` and `other`. Dimensions are summed as follows: ```python tf.Dimension(m) + tf.Dimension(n) == tf.Dimension(m + n) tf.Dimension(m) + tf.Dimension(None) == tf.Dimension(None) tf.Dimension(None) + tf.Dimension(n) == tf.Dimension(None) tf.Dimension(None) + tf.Dimension(None) == tf.Dimension(None) ``` Args: other: Another Dimension. Returns: A Dimension whose value is the sum of `self` and `other`. """ other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(self._value + other.value) def __sub__(self, other): """Returns the subtraction of `other` from `self`. Dimensions are subtracted as follows: ```python tf.Dimension(m) - tf.Dimension(n) == tf.Dimension(m - n) tf.Dimension(m) - tf.Dimension(None) == tf.Dimension(None) tf.Dimension(None) - tf.Dimension(n) == tf.Dimension(None) tf.Dimension(None) - tf.Dimension(None) == tf.Dimension(None) ``` Args: other: Another Dimension. Returns: A Dimension whose value is the subtraction of sum of `other` from `self`. """ other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(self._value - other.value) def __mul__(self, other): """Returns the product of `self` and `other`. Dimensions are summed as follows: ```python tf.Dimension(m) * tf.Dimension(n) == tf.Dimension(m * n) tf.Dimension(m) * tf.Dimension(None) == tf.Dimension(None) tf.Dimension(None) * tf.Dimension(n) == tf.Dimension(None) tf.Dimension(None) * tf.Dimension(None) == tf.Dimension(None) ``` Args: other: Another Dimension. Returns: A Dimension whose value is the product of `self` and `other`. """ other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(self._value * other.value) def __floordiv__(self, other): """Returns the quotient of `self` and `other` rounded down. Dimensions are divided as follows: ```python tf.Dimension(m) // tf.Dimension(n) == tf.Dimension(m // n) tf.Dimension(m) // tf.Dimension(None) == tf.Dimension(None) tf.Dimension(None) // tf.Dimension(n) == tf.Dimension(None) tf.Dimension(None) // tf.Dimension(None) == tf.Dimension(None) ``` Args: other: Another `Dimension`. Returns: A `Dimension` whose value is the integer quotient of `self` and `other`. """ other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(self._value // other.value) def __div__(self, other): """DEPRECATED: Use `__floordiv__` via `x // y` instead. This function exists only for backwards compatibility purposes; new code should use `__floordiv__` via the syntax `x // y`. Using `x // y` communicates clearly that the result rounds down, and is forward compatible to Python 3. Args: other: Another `Dimension`. Returns: A `Dimension` whose value is the integer quotient of `self` and `other`. """ return self // other def __mod__(self, other): """Returns `self` modulo `other. Dimension moduli are computed as follows: ```python tf.Dimension(m) % tf.Dimension(n) == tf.Dimension(m % n) tf.Dimension(m) % tf.Dimension(None) == tf.Dimension(None) tf.Dimension(None) % tf.Dimension(n) == tf.Dimension(None) tf.Dimension(None) % tf.Dimension(None) == tf.Dimension(None) ``` Args: other: Another Dimension. Returns: A Dimension whose value is `self` modulo `other`. """ other = as_dimension(other) if self._value is None or other.value is None: return Dimension(None) else: return Dimension(self._value % other.value) def __lt__(self, other): """Returns True if `self` is known to be less than `other`. Dimensions are compared as follows: ```python (tf.Dimension(m) < tf.Dimension(n)) == (m < n) (tf.Dimension(m) < tf.Dimension(None)) == None (tf.Dimension(None) < tf.Dimension(n)) == None (tf.Dimension(None) < tf.Dimension(None)) == None ``` Args: other: Another Dimension. Returns: The value of `self.value < other.value` if both are known, otherwise None. """ other = as_dimension(other) if self._value is None or other.value is None: return None else: return self._value < other.value def __le__(self, other): """Returns True if `self` is known to be less than or equal to `other`. Dimensions are compared as follows: ```python (tf.Dimension(m) <= tf.Dimension(n)) == (m <= n) (tf.Dimension(m) <= tf.Dimension(None)) == None (tf.Dimension(None) <= tf.Dimension(n)) == None (tf.Dimension(None) <= tf.Dimension(None)) == None ``` Args: other: Another Dimension. Returns: The value of `self.value <= other.value` if both are known, otherwise None. """ other = as_dimension(other) if self._value is None or other.value is None: return None else: return self._value <= other.value def __gt__(self, other): """Returns True if `self` is known to be greater than `other`. Dimensions are compared as follows: ```python (tf.Dimension(m) > tf.Dimension(n)) == (m > n) (tf.Dimension(m) > tf.Dimension(None)) == None (tf.Dimension(None) > tf.Dimension(n)) == None (tf.Dimension(None) > tf.Dimension(None)) == None ``` Args: other: Another Dimension. Returns: The value of `self.value > other.value` if both are known, otherwise None. """ other = as_dimension(other) if self._value is None or other.value is None: return None else: return self._value > other.value def __ge__(self, other): """Returns True if `self` is known to be greater than or equal to `other`. Dimensions are compared as follows: ```python (tf.Dimension(m) >= tf.Dimension(n)) == (m >= n) (tf.Dimension(m) >= tf.Dimension(None)) == None (tf.Dimension(None) >= tf.Dimension(n)) == None (tf.Dimension(None) >= tf.Dimension(None)) == None ``` Args: other: Another Dimension. Returns: The value of `self.value >= other.value` if both are known, otherwise None. """ other = as_dimension(other) if self._value is None or other.value is None: return None else: return self._value >= other.value def as_dimension(value): """Converts the given value to a Dimension. A Dimension input will be returned unmodified. An input of `None` will be converted to an unknown Dimension. An integer input will be converted to a Dimension with that value. Args: value: The value to be converted. Returns: A Dimension corresponding to the given value. """ if isinstance(value, Dimension): return value else: return Dimension(value) class TensorShape(object): """Represents the shape of a `Tensor`. A `TensorShape` represents a possibly-partial shape specification for a `Tensor`. It may be one of the following: * *Fully-known shape:* has a known number of dimensions and a known size for each dimension. e.g. `TensorShape([16, 256])` * *Partially-known shape:* has a known number of dimensions, and an unknown size for one or more dimension. e.g. `TensorShape([None, 256])` * *Unknown shape:* has an unknown number of dimensions, and an unknown size in all dimensions. e.g. `TensorShape(None)` If a tensor is produced by an operation of type `"Foo"`, its shape may be inferred if there is a registered shape function for `"Foo"`. See @{$adding_an_op#shape-functions-in-c$`Shape functions in C++`} for details of shape functions and how to register them. Alternatively, the shape may be set explicitly using @{tf.Tensor.set_shape}. """ def __init__(self, dims): """Creates a new TensorShape with the given dimensions. Args: dims: A list of Dimensions, or None if the shape is unspecified. DEPRECATED: A single integer is treated as a singleton list. Raises: TypeError: If dims cannot be converted to a list of dimensions. """ # TODO(irving): Eliminate the single integer special case. if dims is None: self._dims = None elif isinstance(dims, compat.bytes_or_text_types): raise TypeError("A string has ambiguous TensorShape, please wrap in a " "list or convert to an int: %s" % dims) elif isinstance(dims, tensor_shape_pb2.TensorShapeProto): if dims.unknown_rank: self._dims = None else: self._dims = [ # Protos store variable-size dimensions as -1 as_dimension(dim.size if dim.size != -1 else None) for dim in dims.dim ] elif isinstance(dims, TensorShape): self._dims = dims.dims else: try: dims_iter = iter(dims) except TypeError: # Treat as a singleton dimension self._dims = [as_dimension(dims)] else: # Got a list of dimensions self._dims = [as_dimension(d) for d in dims_iter] def __repr__(self): return "TensorShape(%r)" % self._dims def __str__(self): if self.ndims is None: return "<unknown>" elif self.ndims == 1: return "(%s,)" % self._dims[0] else: return "(%s)" % ", ".join(str(d) for d in self._dims) @property def dims(self): """Returns a list of Dimensions, or None if the shape is unspecified.""" return self._dims @property def ndims(self): """Returns the rank of this shape, or None if it is unspecified.""" if self._dims is None: return None else: return len(self._dims) def __len__(self): """Returns the rank of this shape, or raises ValueError if unspecified.""" if self._dims is None: raise ValueError("Cannot take the length of Shape with unknown rank.") return len(self._dims) def __bool__(self): """Returns True if this shape contains non-zero information.""" return self._dims is not None # Python 3 wants __bool__, Python 2.7 wants __nonzero__ __nonzero__ = __bool__ def __iter__(self): """Returns `self.dims` if the rank is known, otherwise raises ValueError.""" if self._dims is None: raise ValueError("Cannot iterate over a shape with unknown rank.") else: return iter(self._dims) def __getitem__(self, key): """Returns the value of a dimension or a shape, depending on the key. Args: key: If `key` is an integer, returns the dimension at that index; otherwise if `key` is a slice, returns a TensorShape whose dimensions are those selected by the slice from `self`. Returns: A dimension if `key` is an integer, or a `TensorShape` if `key` is a slice. Raises: ValueError: If `key` is a slice, and any of its elements are negative, or if `self` is completely unknown and the step is set. """ if self._dims is not None: if isinstance(key, slice): return TensorShape(self._dims[key]) else: return self._dims[key] else: if isinstance(key, slice): start = key.start if key.start is not None else 0 stop = key.stop if key.step is not None: # TODO(mrry): Handle these maybe. raise ValueError("Steps are not yet handled") if stop is None: # NOTE(mrry): This implies that TensorShape(None) is compatible with # TensorShape(None)[1:], which is obviously not true. It would be # possible to track the number of dimensions symbolically, # and perhaps we should do that. return unknown_shape() elif start < 0 or stop < 0: # TODO(mrry): Handle this better, as it will be useful for handling # suffixes of otherwise unknown shapes. return unknown_shape() else: return unknown_shape(ndims=stop - start) else: return Dimension(None) def num_elements(self): """Returns the total number of elements, or none for incomplete shapes.""" if self.is_fully_defined(): size = 1 for dim in self._dims: size *= dim.value return size else: return None def merge_with(self, other): """Returns a `TensorShape` combining the information in `self` and `other`. The dimensions in `self` and `other` are merged elementwise, according to the rules defined for `Dimension.merge_with()`. Args: other: Another `TensorShape`. Returns: A `TensorShape` containing the combined information of `self` and `other`. Raises: ValueError: If `self` and `other` are not compatible. """ other = as_shape(other) if self._dims is None: return other else: try: self.assert_same_rank(other) new_dims = [] for i, dim in enumerate(self._dims): new_dims.append(dim.merge_with(other[i])) return TensorShape(new_dims) except ValueError: raise ValueError("Shapes %s and %s are not compatible" % (self, other)) def concatenate(self, other): """Returns the concatenation of the dimension in `self` and `other`. *N.B.* If either `self` or `other` is completely unknown, concatenation will discard information about the other shape. In future, we might support concatenation that preserves this information for use with slicing. Args: other: Another `TensorShape`. Returns: A `TensorShape` whose dimensions are the concatenation of the dimensions in `self` and `other`. """ # TODO(mrry): Handle the case where we concatenate a known shape with a # completely unknown shape, so that we can use the partial information. other = as_shape(other) if self._dims is None or other.dims is None: return unknown_shape() else: return TensorShape(self._dims + other.dims) def assert_same_rank(self, other): """Raises an exception if `self` and `other` do not have compatible ranks. Args: other: Another `TensorShape`. Raises: ValueError: If `self` and `other` do not represent shapes with the same rank. """ other = as_shape(other) if self.ndims is not None and other.ndims is not None: if self.ndims != other.ndims: raise ValueError("Shapes %s and %s must have the same rank" % (self, other)) def assert_has_rank(self, rank): """Raises an exception if `self` is not compatible with the given `rank`. Args: rank: An integer. Raises: ValueError: If `self` does not represent a shape with the given `rank`. """ if self.ndims not in (None, rank): raise ValueError("Shape %s must have rank %d" % (self, rank)) def with_rank(self, rank): """Returns a shape based on `self` with the given rank. This method promotes a completely unknown shape to one with a known rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with the given rank. Raises: ValueError: If `self` does not represent a shape with the given `rank`. """ try: return self.merge_with(unknown_shape(ndims=rank)) except ValueError: raise ValueError("Shape %s must have rank %d" % (self, rank)) def with_rank_at_least(self, rank): """Returns a shape based on `self` with at least the given rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with at least the given rank. Raises: ValueError: If `self` does not represent a shape with at least the given `rank`. """ if self.ndims is not None and self.ndims < rank: raise ValueError("Shape %s must have rank at least %d" % (self, rank)) else: return self def with_rank_at_most(self, rank): """Returns a shape based on `self` with at most the given rank. Args: rank: An integer. Returns: A shape that is at least as specific as `self` with at most the given rank. Raises: ValueError: If `self` does not represent a shape with at most the given `rank`. """ if self.ndims is not None and self.ndims > rank: raise ValueError("Shape %s must have rank at most %d" % (self, rank)) else: return self def is_compatible_with(self, other): """Returns True iff `self` is compatible with `other`. Two possibly-partially-defined shapes are compatible if there exists a fully-defined shape that both shapes can represent. Thus, compatibility allows the shape inference code to reason about partially-defined shapes. For example: * TensorShape(None) is compatible with all shapes. * TensorShape([None, None]) is compatible with all two-dimensional shapes, such as TensorShape([32, 784]), and also TensorShape(None). It is not compatible with, for example, TensorShape([None]) or TensorShape([None, None, None]). * TensorShape([32, None]) is compatible with all two-dimensional shapes with size 32 in the 0th dimension, and also TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32]), TensorShape([32, None, 1]) or TensorShape([64, None]). * TensorShape([32, 784]) is compatible with itself, and also TensorShape([32, None]), TensorShape([None, 784]), TensorShape([None, None]) and TensorShape(None). It is not compatible with, for example, TensorShape([32, 1, 784]) or TensorShape([None]). The compatibility relation is reflexive and symmetric, but not transitive. For example, TensorShape([32, 784]) is compatible with TensorShape(None), and TensorShape(None) is compatible with TensorShape([4, 4]), but TensorShape([32, 784]) is not compatible with TensorShape([4, 4]). Args: other: Another TensorShape. Returns: True iff `self` is compatible with `other`. """ other = as_shape(other) if self._dims is not None and other.dims is not None: if self.ndims != other.ndims: return False for x_dim, y_dim in zip(self._dims, other.dims): if not x_dim.is_compatible_with(y_dim): return False return True def assert_is_compatible_with(self, other): """Raises exception if `self` and `other` do not represent the same shape. This method can be used to assert that there exists a shape that both `self` and `other` represent. Args: other: Another TensorShape. Raises: ValueError: If `self` and `other` do not represent the same shape. """ if not self.is_compatible_with(other): raise ValueError("Shapes %s and %s are incompatible" % (self, other)) def most_specific_compatible_shape(self, other): """Returns the most specific TensorShape compatible with `self` and `other`. * TensorShape([None, 1]) is the most specific TensorShape compatible with both TensorShape([2, 1]) and TensorShape([5, 1]). Note that TensorShape(None) is also compatible with above mentioned TensorShapes. * TensorShape([1, 2, 3]) is the most specific TensorShape compatible with both TensorShape([1, 2, 3]) and TensorShape([1, 2, 3]). There are more less specific TensorShapes compatible with above mentioned TensorShapes, e.g. TensorShape([1, 2, None]), TensorShape(None). Args: other: Another `TensorShape`. Returns: A `TensorShape` which is the most specific compatible shape of `self` and `other`. """ other = as_shape(other) if self._dims is None or other.dims is None or self.ndims != other.ndims: return unknown_shape() dims = [(Dimension(None))] * self.ndims for i, (d1, d2) in enumerate(zip(self._dims, other.dims)): if d1 is not None and d2 is not None and d1 == d2: dims[i] = d1 return TensorShape(dims) def is_fully_defined(self): """Returns True iff `self` is fully defined in every dimension.""" return (self._dims is not None and all(dim.value is not None for dim in self._dims)) def assert_is_fully_defined(self): """Raises an exception if `self` is not fully defined in every dimension. Raises: ValueError: If `self` does not have a known value for every dimension. """ if not self.is_fully_defined(): raise ValueError("Shape %s is not fully defined" % self) def as_list(self): """Returns a list of integers or `None` for each dimension. Returns: A list of integers or `None` for each dimension. Raises: ValueError: If `self` is an unknown shape with an unknown rank. """ if self._dims is None: raise ValueError("as_list() is not defined on an unknown TensorShape.") return [dim.value for dim in self._dims] def as_proto(self): """Returns this shape as a `TensorShapeProto`.""" if self._dims is None: return tensor_shape_pb2.TensorShapeProto(unknown_rank=True) else: return tensor_shape_pb2.TensorShapeProto(dim=[ tensor_shape_pb2.TensorShapeProto.Dim(size=-1 if d.value is None else d.value) for d in self._dims ]) def __eq__(self, other): """Returns True if `self` is equivalent to `other`.""" try: other = as_shape(other) except TypeError: return NotImplemented return self._dims == other.dims def __ne__(self, other): """Returns True if `self` is known to be different from `other`.""" try: other = as_shape(other) except TypeError: return NotImplemented if self.ndims is None or other.ndims is None: raise ValueError("The inequality of unknown TensorShapes is undefined.") if self.ndims != other.ndims: return True return self._dims != other.dims def as_shape(shape): """Converts the given object to a TensorShape.""" if isinstance(shape, TensorShape): return shape else: return TensorShape(shape) def unknown_shape(ndims=None): """Returns an unknown TensorShape, optionally with a known rank. Args: ndims: (Optional) If specified, the number of dimensions in the shape. Returns: An unknown TensorShape. """ if ndims is None: return TensorShape(None) else: return TensorShape([Dimension(None)] * ndims) def scalar(): """Returns a shape representing a scalar.""" return TensorShape([]) def vector(length): """Returns a shape representing a vector. Args: length: The length of the vector, which may be None if unknown. Returns: A TensorShape representing a vector of the given length. """ return TensorShape([length]) def matrix(rows, cols): """Returns a shape representing a matrix. Args: rows: The number of rows in the matrix, which may be None if unknown. cols: The number of columns in the matrix, which may be None if unknown. Returns: A TensorShape representing a matrix of the given size. """ return TensorShape([rows, cols])
apache-2.0
liyitest/rr
openstack_dashboard/dashboards/project/firewalls/workflows.py
13
13303
# Copyright 2013, Big Switch Networks, 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. from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon.utils import validators from horizon import workflows from openstack_dashboard import api port_validator = validators.validate_port_or_colon_separated_port_range class AddRuleAction(workflows.Action): name = forms.CharField( max_length=80, label=_("Name"), required=False) description = forms.CharField( max_length=80, label=_("Description"), required=False) protocol = forms.ChoiceField( label=_("Protocol"), choices=[('tcp', _('TCP')), ('udp', _('UDP')), ('icmp', _('ICMP')), ('any', _('ANY'))],) action = forms.ChoiceField( label=_("Action"), choices=[('allow', _('ALLOW')), ('deny', _('DENY'))],) source_ip_address = forms.IPField( label=_("Source IP Address/Subnet"), version=forms.IPv4 | forms.IPv6, required=False, mask=True) destination_ip_address = forms.IPField( label=_("Destination IP Address/Subnet"), version=forms.IPv4 | forms.IPv6, required=False, mask=True) source_port = forms.CharField( max_length=80, label=_("Source Port/Port Range"), required=False, validators=[port_validator]) destination_port = forms.CharField( max_length=80, label=_("Destination Port/Port Range"), required=False, validators=[port_validator]) shared = forms.BooleanField( label=_("Shared"), initial=False, required=False) enabled = forms.BooleanField( label=_("Enabled"), initial=True, required=False) def __init__(self, request, *args, **kwargs): super(AddRuleAction, self).__init__(request, *args, **kwargs) class Meta(object): name = _("AddRule") permissions = ('openstack.services.network',) help_text = _("Create a firewall rule.\n\n" "Protocol and action must be specified. " "Other fields are optional.") class AddRuleStep(workflows.Step): action_class = AddRuleAction contributes = ("name", "description", "protocol", "action", "source_ip_address", "source_port", "destination_ip_address", "destination_port", "enabled", "shared") def contribute(self, data, context): context = super(AddRuleStep, self).contribute(data, context) if data: if context['protocol'] == 'any': del context['protocol'] for field in ['source_port', 'destination_port', 'source_ip_address', 'destination_ip_address']: if not context[field]: del context[field] return context class AddRule(workflows.Workflow): slug = "addrule" name = _("Add Rule") finalize_button_name = _("Add") success_message = _('Added Rule "%s".') failure_message = _('Unable to add Rule "%s".') success_url = "horizon:project:firewalls:index" # fwaas is designed to support a wide range of vendor # firewalls. Considering the multitude of vendor firewall # features in place today, firewall_rule definition can # involve more complex configuration over time. Hence, # a workflow instead of a single form is used for # firewall_rule add to be ready for future extension. default_steps = (AddRuleStep,) def format_status_message(self, message): return message % self.context.get('name') def handle(self, request, context): try: api.fwaas.rule_create(request, **context) return True except Exception as e: msg = self.format_status_message(self.failure_message) + str(e) exceptions.handle(request, msg) return False class SelectRulesAction(workflows.Action): rule = forms.MultipleChoiceField( label=_("Rules"), required=False, widget=forms.CheckboxSelectMultiple(), help_text=_("Create a policy with selected rules.")) class Meta(object): name = _("Rules") permissions = ('openstack.services.network',) help_text = _("Select rules for your policy.") def populate_rule_choices(self, request, context): try: tenant_id = self.request.user.tenant_id rules = api.fwaas.rule_list_for_tenant(request, tenant_id) rules = sorted(rules, key=lambda rule: rule.name_or_id) rule_list = [(rule.id, rule.name_or_id) for rule in rules if not rule.firewall_policy_id] except Exception as e: rule_list = [] exceptions.handle(request, _('Unable to retrieve rules (%(error)s).') % { 'error': str(e)}) return rule_list class SelectRulesStep(workflows.Step): action_class = SelectRulesAction template_name = "project/firewalls/_update_rules.html" contributes = ("firewall_rules",) def contribute(self, data, context): if data: rules = self.workflow.request.POST.getlist("rule") if rules: rules = [r for r in rules if r != ''] context['firewall_rules'] = rules return context class SelectRoutersAction(workflows.Action): router = forms.MultipleChoiceField( label=_("Routers"), required=False, widget=forms.CheckboxSelectMultiple(), help_text=_("Create a firewall with selected routers.")) class Meta(object): name = _("Routers") permissions = ('openstack.services.network',) help_text = _("Select routers for your firewall.") def populate_router_choices(self, request, context): try: tenant_id = self.request.user.tenant_id routers_list = api.fwaas.firewall_unassociated_routers_list( request, tenant_id) except Exception as e: routers_list = [] exceptions.handle(request, _('Unable to retrieve routers (%(error)s).') % { 'error': str(e)}) routers_list = [(router.id, router.name_or_id) for router in routers_list] return routers_list class SelectRoutersStep(workflows.Step): action_class = SelectRoutersAction template_name = "project/firewalls/_update_routers.html" contributes = ("router_ids", "all_routers_selected", "Select No Routers") def contribute(self, data, context): if data: routers = self.workflow.request.POST.getlist("router") if routers: routers = [r for r in routers if r != ''] context['router_ids'] = routers else: context['router_ids'] = [] return context class AddPolicyAction(workflows.Action): name = forms.CharField(max_length=80, label=_("Name")) description = forms.CharField(max_length=80, label=_("Description"), required=False) shared = forms.BooleanField(label=_("Shared"), initial=False, required=False) audited = forms.BooleanField(label=_("Audited"), initial=False, required=False) def __init__(self, request, *args, **kwargs): super(AddPolicyAction, self).__init__(request, *args, **kwargs) class Meta(object): name = _("AddPolicy") permissions = ('openstack.services.network',) help_text = _("Create a firewall policy with an ordered list " "of firewall rules.\n\n" "A name must be given. Firewall rules are " "added in the order placed under the Rules tab.") class AddPolicyStep(workflows.Step): action_class = AddPolicyAction contributes = ("name", "description", "shared", "audited") def contribute(self, data, context): context = super(AddPolicyStep, self).contribute(data, context) if data: return context class AddPolicy(workflows.Workflow): slug = "addpolicy" name = _("Add Policy") finalize_button_name = _("Add") success_message = _('Added Policy "%s".') failure_message = _('Unable to add Policy "%s".') success_url = "horizon:project:firewalls:index" default_steps = (AddPolicyStep, SelectRulesStep) def format_status_message(self, message): return message % self.context.get('name') def handle(self, request, context): try: api.fwaas.policy_create(request, **context) return True except Exception as e: msg = self.format_status_message(self.failure_message) + str(e) exceptions.handle(request, msg) return False class AddFirewallAction(workflows.Action): name = forms.CharField(max_length=80, label=_("Name"), required=False) description = forms.CharField(max_length=80, label=_("Description"), required=False) firewall_policy_id = forms.ChoiceField(label=_("Policy")) shared = forms.BooleanField(label=_("Shared"), initial=False, required=False) admin_state_up = forms.ChoiceField(choices=[(True, _('UP')), (False, _('DOWN'))], label=_("Admin State")) def __init__(self, request, *args, **kwargs): super(AddFirewallAction, self).__init__(request, *args, **kwargs) firewall_policy_id_choices = [('', _("Select a Policy"))] try: tenant_id = self.request.user.tenant_id policies = api.fwaas.policy_list_for_tenant(request, tenant_id) policies = sorted(policies, key=lambda policy: policy.name) except Exception as e: exceptions.handle( request, _('Unable to retrieve policy list (%(error)s).') % { 'error': str(e)}) policies = [] for p in policies: firewall_policy_id_choices.append((p.id, p.name_or_id)) self.fields['firewall_policy_id'].choices = firewall_policy_id_choices # only admin can set 'shared' attribute to True if not request.user.is_superuser: self.fields['shared'].widget.attrs['disabled'] = 'disabled' class Meta(object): name = _("AddFirewall") permissions = ('openstack.services.network',) help_text = _("Create a firewall based on a policy.\n\n" "A policy must be selected. " "Other fields are optional.") class AddFirewallStep(workflows.Step): action_class = AddFirewallAction contributes = ("name", "firewall_policy_id", "description", "shared", "admin_state_up") def contribute(self, data, context): context = super(AddFirewallStep, self).contribute(data, context) context['admin_state_up'] = (context['admin_state_up'] == 'True') return context class AddFirewall(workflows.Workflow): slug = "addfirewall" name = _("Add Firewall") finalize_button_name = _("Add") success_message = _('Added Firewall "%s".') failure_message = _('Unable to add Firewall "%s".') success_url = "horizon:project:firewalls:index" # fwaas is designed to support a wide range of vendor # firewalls. Considering the multitude of vendor firewall # features in place today, firewall definition can # involve more complex configuration over time. Hence, # a workflow instead of a single form is used for # firewall_rule add to be ready for future extension. default_steps = (AddFirewallStep, ) def format_status_message(self, message): return message % self.context.get('name') def handle(self, request, context): try: api.fwaas.firewall_create(request, **context) return True except Exception as e: msg = self.format_status_message(self.failure_message) + str(e) exceptions.handle(request, msg) return False
apache-2.0
digitalemagine/django-localflavor-it
django_localflavor_it/util.py
101
1791
from django.utils.encoding import smart_text def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26] def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_text(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_text((10 - total % 10) % 10)
bsd-3-clause
ldoktor/avocado-vt
virt.py
4
9628
import os import sys import logging import imp try: import queue as Queue except ImportError: import Queue from autotest.client import test import six from avocado.core import exceptions from virttest import asset from virttest import bootstrap from virttest import data_dir from virttest import env_process from virttest import funcatexit from virttest import utils_env from virttest import utils_misc from virttest import utils_params from virttest import version class virt(test.test): """ Shared test class infrastructure for tests such as the KVM test. It comprises a subtest load system, use of parameters, and an env file, all code that can be reused among those virt tests. """ version = 1 env_version = utils_env.get_env_version() def initialize(self, params): # Change the value of the preserve_srcdir attribute according to # the value present on the configuration file (defaults to yes) if params.get("preserve_srcdir", "yes") == "yes": self.preserve_srcdir = True virtdir = os.path.dirname(sys.modules[__name__].__file__) self.virtdir = os.path.join(virtdir, "shared") # Place where virt software will be built/linked self.builddir = os.path.join( virtdir, 'backends', params.get("vm_type")) self.background_errors = Queue.Queue() def verify_background_errors(self): """ Verify if there are any errors that happened on background threads. :raise Exception: Any exception stored on the background_errors queue. """ try: exc = self.background_errors.get(block=False) except Queue.Empty: pass else: six.reraise(exc[1], None, exc[2]) def run_once(self, params): # Convert params to a Params object params = utils_params.Params(params) # If a dependency test prior to this test has failed, let's fail # it right away as TestNA. if params.get("dependency_failed") == 'yes': raise exceptions.TestSkipError("Test dependency failed") # Report virt test version logging.info(version.get_pretty_version_info()) # Report the parameters we've received and write them as keyvals logging.debug("Test parameters:") keys = list(params.keys()) keys.sort() for key in keys: logging.debug(" %s = %s", key, params[key]) self.write_test_keyval({key: params[key]}) # Set the log file dir for the logging mechanism used by kvm_subprocess # (this must be done before unpickling env) utils_misc.set_log_file_dir(self.debugdir) # Open the environment file custom_env_path = params.get("custom_env_path", "") if custom_env_path: env_path = custom_env_path else: env_path = params.get("vm_type") env_filename = os.path.join(self.bindir, "backends", env_path, params.get("env", "env")) env = utils_env.Env(env_filename, self.env_version) other_subtests_dirs = params.get("other_tests_dirs", "") test_passed = False t_type = None try: try: try: subtest_dirs = [] bin_dir = self.bindir for d in other_subtests_dirs.split(): # If d starts with a "/" an absolute path will be assumed # else the relative path will be searched in the bin_dir subtestdir = os.path.join(bin_dir, d, "tests") if not os.path.isdir(subtestdir): raise exceptions.TestError("Directory %s not" " exist." % (subtestdir)) subtest_dirs += data_dir.SubdirList(subtestdir, bootstrap.test_filter) # Verify if we have the correspondent source file for it for generic_subdir in asset.get_test_provider_subdirs('generic'): subtest_dirs += data_dir.SubdirList(generic_subdir, bootstrap.test_filter) for multi_host_migration_subdir in asset.get_test_provider_subdirs( 'multi_host_migration'): subtest_dirs += data_dir.SubdirList(multi_host_migration_subdir, bootstrap.test_filter) for specific_subdir in asset.get_test_provider_subdirs(params.get("vm_type")): subtest_dirs += data_dir.SubdirList(specific_subdir, bootstrap.test_filter) subtest_dir = None # Get the test routine corresponding to the specified # test type logging.debug("Searching for test modules that match " "'type = %s' and 'provider = %s' " "on this cartesian dict", params.get("type"), params.get("provider", None)) t_types = params.get("type").split() provider = params.get("provider", None) if provider is not None: subtest_dirs = [ d for d in subtest_dirs if provider in d] # Make sure we can load provider_lib in tests for s in subtest_dirs: if os.path.dirname(s) not in sys.path: sys.path.insert(0, os.path.dirname(s)) test_modules = {} for t_type in t_types: for d in subtest_dirs: module_path = os.path.join(d, "%s.py" % t_type) if os.path.isfile(module_path): subtest_dir = d break if subtest_dir is None: msg = ("Could not find test file %s.py on tests" "dirs %s" % (t_type, subtest_dirs)) raise exceptions.TestError(msg) # Load the test module f, p, d = imp.find_module(t_type, [subtest_dir]) test_modules[t_type] = imp.load_module(t_type, f, p, d) f.close() # Preprocess try: params = env_process.preprocess(self, params, env) finally: env.save() # Run the test function for t_type in t_types: test_module = test_modules[t_type] run_func = utils_misc.get_test_entrypoint_func( t_type, test_module) try: run_func(self, params, env) self.verify_background_errors() finally: env.save() test_passed = True error_message = funcatexit.run_exitfuncs(env, t_type) if error_message: raise exceptions.TestWarn("funcatexit failed with: %s" % error_message) except Exception as e: if t_type is not None: error_message = funcatexit.run_exitfuncs(env, t_type) if error_message: logging.error(error_message) logging.error("Test failed: %s: %s", e.__class__.__name__, e) try: env_process.postprocess_on_error( self, params, env) finally: env.save() raise finally: # Postprocess try: try: env_process.postprocess(self, params, env) except Exception as e: if test_passed: raise logging.error("Exception raised during " "postprocessing: %s", e) finally: env.save() except Exception as e: if params.get("abort_on_error") != "yes": raise # Abort on error logging.info("Aborting job (%s)", e) if params.get("vm_type") == "qemu": for vm in env.get_all_vms(): if vm.is_dead(): continue logging.info("VM '%s' is alive.", vm.name) for m in vm.monitors: logging.info( "'%s' has a %s monitor unix socket at: %s", vm.name, m.protocol, m.filename) logging.info( "The command line used to start '%s' was:\n%s", vm.name, vm.make_create_command()) raise exceptions.JobError("Abort requested (%s)" % e)
gpl-2.0
Hummer12007/pomu
pomu/util/remote.py
1
1214
""" Utilities for remotes """ from portage.versions import best from pomu.util.pkg import ver_str, cpv_split from pomu.util.portage import misc_dirs from pomu.util.result import Result def filelist_to_cpvs(tree): """Converts a list of files to list of cpvs""" res = [] for opath in tree: comps = opath.split('/')[1:] if (opath.endswith('/') or any(opath.startswith('/' + x + '/') for x in misc_dirs) or len(comps) != 3 or not comps[2].endswith('.ebuild')): continue category, name, ebuild = comps[0], comps[1], comps[2][:-7] c, n, ver = cpv_split(ebuild) if not category or n != name: continue res.append((category, name, ver)) return res def get_full_cpv(cpvs, name, category=None, version=None): cpvl = filter(lambda x: x[1] == name and (not category or x[0] == category), cpvs) if not cpvl: return Result.Err() if version: cpvl = list(filter(lambda x: x[2] == version, cpvl))[:1] b = best(list('{}/{}-{}'.format(c, n, v) for c, n, v in cpvl)) if b: cat, name, ver = cpv_split(b) return Result.Ok((cat, name, ver)) return Result.Err()
gpl-2.0
jiangzhixiao/odoo
addons/document/__openerp__.py
260
2096
# -*- 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/>. # ############################################################################## { 'name': 'Document Management System', 'version': '2.1', 'category': 'Knowledge Management', 'description': """ This is a complete document management system. ============================================== * User Authentication * Document Indexation:- .pptx and .docx files are not supported in Windows platform. * Dashboard for Document that includes: * New Files (list) * Files by Resource Type (graph) * Files by Partner (graph) * Files Size by Month (graph) """, 'author': 'OpenERP SA', 'website': 'https://www.odoo.com', 'depends': ['knowledge', 'mail'], 'data': [ 'security/document_security.xml', 'document_view.xml', 'document_data.xml', 'wizard/document_configuration_view.xml', 'security/ir.model.access.csv', 'report/document_report_view.xml', 'views/document.xml', ], 'demo': [ 'document_demo.xml' ], 'test': ['test/document_test2.yml'], 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
jayceyxc/hue
apps/metastore/src/metastore/forms.py
2
2753
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from django import forms from django.utils.translation import ugettext as _, ugettext_lazy as _t from desktop.lib.django_forms import simple_formset_factory, DependencyAwareForm from desktop.lib.django_forms import ChoiceOrOtherField, MultiForm, SubmitButton from filebrowser.forms import PathField from beeswax import common from beeswax.server.dbms import NoSuchObjectException from beeswax.models import SavedQuery class DbForm(forms.Form): """For 'show tables'""" database = forms.ChoiceField(required=False, label='', choices=(('default', 'default'),), initial=0, widget=forms.widgets.Select(attrs={'class': 'input-medium'})) def __init__(self, *args, **kwargs): databases = kwargs.pop('databases') super(DbForm, self).__init__(*args, **kwargs) self.fields['database'].choices = ((db, db) for db in databases) class LoadDataForm(forms.Form): """Form used for loading data into an existing table.""" path = PathField(label=_t("Path")) overwrite = forms.BooleanField(required=False, initial=False, label=_t("Overwrite?")) is_embeddable = forms.BooleanField(required=False, initial=False) def __init__(self, table_obj, *args, **kwargs): """ @param table_obj is a hive_metastore.thrift Table object, used to add fields corresponding to partition keys. """ super(LoadDataForm, self).__init__(*args, **kwargs) self.partition_columns = dict() for i, column in enumerate(table_obj.partition_keys): # We give these numeric names because column names # may be unpleasantly arbitrary. name = "partition_%d" % i char_field = forms.CharField(required=True, label=_t("%(column_name)s (partition key with type %(column_type)s)") % {'column_name': column.name, 'column_type': column.type}) self.fields[name] = char_field self.partition_columns[name] = column.name
apache-2.0
coderbone/SickRage-alt
lib/tornado/test/queues_test.py
29
13046
# 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 __future__ import absolute_import, division, print_function from datetime import timedelta from random import random from tornado import gen, queues from tornado.gen import TimeoutError from tornado.testing import gen_test, AsyncTestCase from tornado.test.util import unittest, skipBefore35, exec_test class QueueBasicTest(AsyncTestCase): def test_repr_and_str(self): q = queues.Queue(maxsize=1) self.assertIn(hex(id(q)), repr(q)) self.assertNotIn(hex(id(q)), str(q)) q.get() for q_str in repr(q), str(q): self.assertTrue(q_str.startswith('<Queue')) self.assertIn('maxsize=1', q_str) self.assertIn('getters[1]', q_str) self.assertNotIn('putters', q_str) self.assertNotIn('tasks', q_str) q.put(None) q.put(None) # Now the queue is full, this putter blocks. q.put(None) for q_str in repr(q), str(q): self.assertNotIn('getters', q_str) self.assertIn('putters[1]', q_str) self.assertIn('tasks=2', q_str) def test_order(self): q = queues.Queue() for i in [1, 3, 2]: q.put_nowait(i) items = [q.get_nowait() for _ in range(3)] self.assertEqual([1, 3, 2], items) @gen_test def test_maxsize(self): self.assertRaises(TypeError, queues.Queue, maxsize=None) self.assertRaises(ValueError, queues.Queue, maxsize=-1) q = queues.Queue(maxsize=2) self.assertTrue(q.empty()) self.assertFalse(q.full()) self.assertEqual(2, q.maxsize) self.assertTrue(q.put(0).done()) self.assertTrue(q.put(1).done()) self.assertFalse(q.empty()) self.assertTrue(q.full()) put2 = q.put(2) self.assertFalse(put2.done()) self.assertEqual(0, (yield q.get())) # Make room. self.assertTrue(put2.done()) self.assertFalse(q.empty()) self.assertTrue(q.full()) class QueueGetTest(AsyncTestCase): @gen_test def test_blocking_get(self): q = queues.Queue() q.put_nowait(0) self.assertEqual(0, (yield q.get())) def test_nonblocking_get(self): q = queues.Queue() q.put_nowait(0) self.assertEqual(0, q.get_nowait()) def test_nonblocking_get_exception(self): q = queues.Queue() self.assertRaises(queues.QueueEmpty, q.get_nowait) @gen_test def test_get_with_putters(self): q = queues.Queue(1) q.put_nowait(0) put = q.put(1) self.assertEqual(0, (yield q.get())) self.assertIsNone((yield put)) @gen_test def test_blocking_get_wait(self): q = queues.Queue() q.put(0) self.io_loop.call_later(0.01, q.put, 1) self.io_loop.call_later(0.02, q.put, 2) self.assertEqual(0, (yield q.get(timeout=timedelta(seconds=1)))) self.assertEqual(1, (yield q.get(timeout=timedelta(seconds=1)))) @gen_test def test_get_timeout(self): q = queues.Queue() get_timeout = q.get(timeout=timedelta(seconds=0.01)) get = q.get() with self.assertRaises(TimeoutError): yield get_timeout q.put_nowait(0) self.assertEqual(0, (yield get)) @gen_test def test_get_timeout_preempted(self): q = queues.Queue() get = q.get(timeout=timedelta(seconds=0.01)) q.put(0) yield gen.sleep(0.02) self.assertEqual(0, (yield get)) @gen_test def test_get_clears_timed_out_putters(self): q = queues.Queue(1) # First putter succeeds, remainder block. putters = [q.put(i, timedelta(seconds=0.01)) for i in range(10)] put = q.put(10) self.assertEqual(10, len(q._putters)) yield gen.sleep(0.02) self.assertEqual(10, len(q._putters)) self.assertFalse(put.done()) # Final waiter is still active. q.put(11) self.assertEqual(0, (yield q.get())) # get() clears the waiters. self.assertEqual(1, len(q._putters)) for putter in putters[1:]: self.assertRaises(TimeoutError, putter.result) @gen_test def test_get_clears_timed_out_getters(self): q = queues.Queue() getters = [q.get(timedelta(seconds=0.01)) for _ in range(10)] get = q.get() self.assertEqual(11, len(q._getters)) yield gen.sleep(0.02) self.assertEqual(11, len(q._getters)) self.assertFalse(get.done()) # Final waiter is still active. q.get() # get() clears the waiters. self.assertEqual(2, len(q._getters)) for getter in getters: self.assertRaises(TimeoutError, getter.result) @skipBefore35 @gen_test def test_async_for(self): q = queues.Queue() for i in range(5): q.put(i) namespace = exec_test(globals(), locals(), """ async def f(): results = [] async for i in q: results.append(i) if i == 4: return results """) results = yield namespace['f']() self.assertEqual(results, list(range(5))) class QueuePutTest(AsyncTestCase): @gen_test def test_blocking_put(self): q = queues.Queue() q.put(0) self.assertEqual(0, q.get_nowait()) def test_nonblocking_put_exception(self): q = queues.Queue(1) q.put(0) self.assertRaises(queues.QueueFull, q.put_nowait, 1) @gen_test def test_put_with_getters(self): q = queues.Queue() get0 = q.get() get1 = q.get() yield q.put(0) self.assertEqual(0, (yield get0)) yield q.put(1) self.assertEqual(1, (yield get1)) @gen_test def test_nonblocking_put_with_getters(self): q = queues.Queue() get0 = q.get() get1 = q.get() q.put_nowait(0) # put_nowait does *not* immediately unblock getters. yield gen.moment self.assertEqual(0, (yield get0)) q.put_nowait(1) yield gen.moment self.assertEqual(1, (yield get1)) @gen_test def test_blocking_put_wait(self): q = queues.Queue(1) q.put_nowait(0) self.io_loop.call_later(0.01, q.get) self.io_loop.call_later(0.02, q.get) futures = [q.put(0), q.put(1)] self.assertFalse(any(f.done() for f in futures)) yield futures @gen_test def test_put_timeout(self): q = queues.Queue(1) q.put_nowait(0) # Now it's full. put_timeout = q.put(1, timeout=timedelta(seconds=0.01)) put = q.put(2) with self.assertRaises(TimeoutError): yield put_timeout self.assertEqual(0, q.get_nowait()) # 1 was never put in the queue. self.assertEqual(2, (yield q.get())) # Final get() unblocked this putter. yield put @gen_test def test_put_timeout_preempted(self): q = queues.Queue(1) q.put_nowait(0) put = q.put(1, timeout=timedelta(seconds=0.01)) q.get() yield gen.sleep(0.02) yield put # No TimeoutError. @gen_test def test_put_clears_timed_out_putters(self): q = queues.Queue(1) # First putter succeeds, remainder block. putters = [q.put(i, timedelta(seconds=0.01)) for i in range(10)] put = q.put(10) self.assertEqual(10, len(q._putters)) yield gen.sleep(0.02) self.assertEqual(10, len(q._putters)) self.assertFalse(put.done()) # Final waiter is still active. q.put(11) # put() clears the waiters. self.assertEqual(2, len(q._putters)) for putter in putters[1:]: self.assertRaises(TimeoutError, putter.result) @gen_test def test_put_clears_timed_out_getters(self): q = queues.Queue() getters = [q.get(timedelta(seconds=0.01)) for _ in range(10)] get = q.get() q.get() self.assertEqual(12, len(q._getters)) yield gen.sleep(0.02) self.assertEqual(12, len(q._getters)) self.assertFalse(get.done()) # Final waiters still active. q.put(0) # put() clears the waiters. self.assertEqual(1, len(q._getters)) self.assertEqual(0, (yield get)) for getter in getters: self.assertRaises(TimeoutError, getter.result) @gen_test def test_float_maxsize(self): # Non-int maxsize must round down: http://bugs.python.org/issue21723 q = queues.Queue(maxsize=1.3) self.assertTrue(q.empty()) self.assertFalse(q.full()) q.put_nowait(0) q.put_nowait(1) self.assertFalse(q.empty()) self.assertTrue(q.full()) self.assertRaises(queues.QueueFull, q.put_nowait, 2) self.assertEqual(0, q.get_nowait()) self.assertFalse(q.empty()) self.assertFalse(q.full()) yield q.put(2) put = q.put(3) self.assertFalse(put.done()) self.assertEqual(1, (yield q.get())) yield put self.assertTrue(q.full()) class QueueJoinTest(AsyncTestCase): queue_class = queues.Queue def test_task_done_underflow(self): q = self.queue_class() self.assertRaises(ValueError, q.task_done) @gen_test def test_task_done(self): q = self.queue_class() for i in range(100): q.put_nowait(i) self.accumulator = 0 @gen.coroutine def worker(): while True: item = yield q.get() self.accumulator += item q.task_done() yield gen.sleep(random() * 0.01) # Two coroutines share work. worker() worker() yield q.join() self.assertEqual(sum(range(100)), self.accumulator) @gen_test def test_task_done_delay(self): # Verify it is task_done(), not get(), that unblocks join(). q = self.queue_class() q.put_nowait(0) join = q.join() self.assertFalse(join.done()) yield q.get() self.assertFalse(join.done()) yield gen.moment self.assertFalse(join.done()) q.task_done() self.assertTrue(join.done()) @gen_test def test_join_empty_queue(self): q = self.queue_class() yield q.join() yield q.join() @gen_test def test_join_timeout(self): q = self.queue_class() q.put(0) with self.assertRaises(TimeoutError): yield q.join(timeout=timedelta(seconds=0.01)) class PriorityQueueJoinTest(QueueJoinTest): queue_class = queues.PriorityQueue @gen_test def test_order(self): q = self.queue_class(maxsize=2) q.put_nowait((1, 'a')) q.put_nowait((0, 'b')) self.assertTrue(q.full()) q.put((3, 'c')) q.put((2, 'd')) self.assertEqual((0, 'b'), q.get_nowait()) self.assertEqual((1, 'a'), (yield q.get())) self.assertEqual((2, 'd'), q.get_nowait()) self.assertEqual((3, 'c'), (yield q.get())) self.assertTrue(q.empty()) class LifoQueueJoinTest(QueueJoinTest): queue_class = queues.LifoQueue @gen_test def test_order(self): q = self.queue_class(maxsize=2) q.put_nowait(1) q.put_nowait(0) self.assertTrue(q.full()) q.put(3) q.put(2) self.assertEqual(3, q.get_nowait()) self.assertEqual(2, (yield q.get())) self.assertEqual(0, q.get_nowait()) self.assertEqual(1, (yield q.get())) self.assertTrue(q.empty()) class ProducerConsumerTest(AsyncTestCase): @gen_test def test_producer_consumer(self): q = queues.Queue(maxsize=3) history = [] # We don't yield between get() and task_done(), so get() must wait for # the next tick. Otherwise we'd immediately call task_done and unblock # join() before q.put() resumes, and we'd only process the first four # items. @gen.coroutine def consumer(): while True: history.append((yield q.get())) q.task_done() @gen.coroutine def producer(): for item in range(10): yield q.put(item) consumer() yield producer() yield q.join() self.assertEqual(list(range(10)), history) if __name__ == '__main__': unittest.main()
gpl-3.0
ehealthafrica-ci/onadata
onadata/apps/logger/management/commands/publish_xls.py
5
2725
import os from optparse import make_option from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from django.utils.translation import ugettext_lazy, ugettext as _ from pyxform.builder import create_survey_from_xls from onadata.apps.logger.models.xform import XForm from onadata.libs.utils.logger_tools import publish_xls_form from onadata.libs.utils.viewer_tools import django_file class Command(BaseCommand): args = 'xls_file username' help = ugettext_lazy("Publish an XLS file with the option of replacing an" "existing one") option_list = BaseCommand.option_list + ( make_option('-r', '--replace', action='store_true', dest='replace', help=ugettext_lazy("Replace existing form if any")),) def handle(self, *args, **options): try: xls_filepath = args[0] except IndexError: raise CommandError(_("You must provide the path to the xls file.")) # make sure path exists if not os.path.exists(xls_filepath): raise CommandError( _("The xls file '%s' does not exist.") % xls_filepath) try: username = args[1] except IndexError: raise CommandError(_( "You must provide the username to publish the form to.")) # make sure user exists try: user = User.objects.get(username=username) except User.DoesNotExist: raise CommandError(_("The user '%s' does not exist.") % username) # wasteful but we need to get the id_string beforehand survey = create_survey_from_xls(xls_filepath) # check if a form with this id_string exists for this user form_already_exists = XForm.objects.filter( user=user, id_string=survey.id_string).count() > 0 # id_string of form to replace, if any id_string = None if form_already_exists: if 'replace' in options and options['replace']: id_string = survey.id_string self.stdout.write(_("Form already exist, replacing ..\n")) else: raise CommandError(_( "The form with id_string '%s' already exists, use the -r " "option to replace it.") % survey.id_string) else: self.stdout.write(_("Form does NOT exist, publishing ..\n")) # publish xls_file = django_file( xls_filepath, 'xls_file', 'application/vnd.ms-excel') publish_xls_form(xls_file, user, id_string) self.stdout.write(_("Done..\n"))
bsd-2-clause
boompieman/iim_project
project_python2/lib/python2.7/site-packages/IPython/utils/wildcard.py
29
4654
# -*- coding: utf-8 -*- """Support for wildcard pattern matching in object inspection. Authors ------- - Jörgen Stenarson <jorgen.stenarson@bostream.nu> - Thomas Kluyver """ #***************************************************************************** # Copyright (C) 2005 Jörgen Stenarson <jorgen.stenarson@bostream.nu> # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part of this software. #***************************************************************************** import re import types from IPython.utils.dir2 import dir2 from .py3compat import iteritems def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]): """Return dictionaries mapping lower case typename (e.g. 'tuple') to type objects from the types package, and vice versa.""" typenamelist = [tname for tname in dir(types) if tname.endswith("Type")] typestr2type, type2typestr = {}, {} for tname in typenamelist: name = tname[:-4].lower() # Cut 'Type' off the end of the name obj = getattr(types, tname) typestr2type[name] = obj if name not in dont_include_in_type2typestr: type2typestr[obj] = name return typestr2type, type2typestr typestr2type, type2typestr = create_typestr2type_dicts() def is_type(obj, typestr_or_type): """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It can take strings or actual python types for the second argument, i.e. 'tuple'<->TupleType. 'all' matches all types. TODO: Should be extended for choosing more than one type.""" if typestr_or_type == "all": return True if type(typestr_or_type) == type: test_type = typestr_or_type else: test_type = typestr2type.get(typestr_or_type, False) if test_type: return isinstance(obj, test_type) return False def show_hidden(str, show_all=False): """Return true for strings starting with single _ if show_all is true.""" return show_all or str.startswith("__") or not str.startswith("_") def dict_dir(obj): """Produce a dictionary of an object's attributes. Builds on dir2 by checking that a getattr() call actually succeeds.""" ns = {} for key in dir2(obj): # This seemingly unnecessary try/except is actually needed # because there is code out there with metaclasses that # create 'write only' attributes, where a getattr() call # will fail even if the attribute appears listed in the # object's dictionary. Properties can actually do the same # thing. In particular, Traits use this pattern try: ns[key] = getattr(obj, key) except AttributeError: pass return ns def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True, show_all=True): """Filter a namespace dictionary by name pattern and item type.""" pattern = name_pattern.replace("*",".*").replace("?",".") if ignore_case: reg = re.compile(pattern+"$", re.I) else: reg = re.compile(pattern+"$") # Check each one matches regex; shouldn't be hidden; of correct type. return dict((key,obj) for key, obj in iteritems(ns) if reg.match(key) \ and show_hidden(key, show_all) \ and is_type(obj, type_pattern) ) def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): """Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.""" pattern_list=filter.split(".") if len(pattern_list) == 1: return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=show_all) else: # This is where we can change if all objects should be searched or # only modules. Just change the type_pattern to module to search only # modules filtered = filter_ns(namespace, name_pattern=pattern_list[0], type_pattern="all", ignore_case=ignore_case, show_all=show_all) results = {} for name, obj in iteritems(filtered): ns = list_namespace(dict_dir(obj), type_pattern, ".".join(pattern_list[1:]), ignore_case=ignore_case, show_all=show_all) for inner_name, inner_obj in iteritems(ns): results["%s.%s"%(name,inner_name)] = inner_obj return results
gpl-3.0
jh23453/privacyidea
privacyidea/lib/tokens/ocra.py
3
13809
# -*- coding: utf-8 -*- # # http://www.privacyidea.org # 2015-09-03 Initial writeup. # Cornelius Kölbel <cornelius@privacyidea.org> # # # This code is free software; you can redistribute it and/or # modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE # License as published by the Free Software Foundation; either # version 3 of the License, or any later version. # # This code 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/>. # __doc__ = """ The OCRA class provides an OCRA object, that can handle all OCRA tasks and do all calculations. http://tools.ietf.org/html/rfc6287 The OCRA class is tested in tests/test_lib_tokens_tiqr.py """ # TODO: Mutual Challenges Response not implemented, yet. from privacyidea.lib.crypto import (geturandom, get_rand_digit_str, get_alphanum_str) from privacyidea.lib.tokens.HMAC import HmacOtp from hashlib import sha1, sha256, sha512 import binascii import struct SHA_FUNC = {"SHA1": sha1, "SHA256": sha256, "SHA512": sha512} class OCRASuite(object): def __init__(self, ocrasuite): """ Check if the given *ocrasuite* is a valid ocrasuite according to chapter 6 of RFC6287. If it is not a valid OCRA Suite an exception is raised. :param ocrasuite: The OCRAsuite :type ocrasuite: basestring :return: bool """ ocrasuite = ocrasuite.upper() algo_crypto_data = ocrasuite.split(":") if len(algo_crypto_data) != 3: raise Exception("The OCRAsuite consists of three fields " "'algorithm', 'cryptofunction' and 'datainput' " "delimited by ':'") self.algorithm = algo_crypto_data[0] self.cryptofunction = algo_crypto_data[1] self.datainput = algo_crypto_data[2] # Test algorithm if self.algorithm != "OCRA-1": raise Exception("Error in algorithm. At the moment only version " "OCRA-1 is supported.") # Test cryptofunction hotp_sha_trunc = self.cryptofunction.split("-") if len(hotp_sha_trunc) != 3: raise Exception("The cryptofunction consists of three fields " "'HOTP', 'SHA' and 'Truncation' " "delimited by '-'") hotp = hotp_sha_trunc[0] self.sha = hotp_sha_trunc[1] self.truncation = int(hotp_sha_trunc[2]) if hotp != "HOTP": raise Exception("Only HOTP is allowed. You specified {0!s}".format(hotp)) if self.sha not in ["SHA1", "SHA256", "SHA512"]: raise Exception("Only SHA1, SHA256 or SHA512 is allowed. You " "specified %s" % self.sha) if self.truncation not in [0, 4, 5, 6, 7, 8, 9, 10]: raise Exception("Only truncation of 0 or 4-10 is allowed. " "You specified %s" % self.truncation) ######################################################## # test datainput counter_input_signature = self.datainput.split("-") if len(counter_input_signature) not in [1, 2, 3]: raise Exception("Error in datainput. The datainput must consist " "of 1, 2 or 3 fields separated by '-'") if len(counter_input_signature) == 1: self.counter = None self.challenge = counter_input_signature[0] self.signature = None elif len(counter_input_signature) == 2: if counter_input_signature[0] == "C": self.counter = counter_input_signature[0] self.challenge = counter_input_signature[1] self.signature = None else: self.counter = None self.challenge = counter_input_signature[0] self.signature = counter_input_signature[1] elif len(counter_input_signature) == 3: self.counter = counter_input_signature[0] self.challenge = counter_input_signature[1] self.signature = counter_input_signature[2] if self.counter != "C": raise Exception("The counter in the datainput must be 'C'") # test challenge # the first two characters of the challenge need to be Q[A|N|H] self.challenge_type = self.challenge[:2] if self.challenge_type not in ["QA", "QH", "QN"]: raise Exception("Error in challenge. The challenge must start " "with QA, QN or QH. You specified %s" % self.challenge) self.challenge_length = 0 try: self.challenge_length = int(self.challenge[2:]) except ValueError: raise Exception("The last characters in the challenge must be a " "number. You specified %s" % self.challenge) if self.challenge_length < 4 or self.challenge_length > 64: raise Exception("The length of the challenge must be specified " "between 4 and 64. You specified %s" % self.challenge_length) # signature if not self.signature: self.signature_type = None else: self.signature_type = self.signature[0] if self.signature_type not in ["P", "S", "T"]: raise Exception("The signature needs to be P, S or T. You " "specified %s" % self.signature_type) if self.signature_type == "P": # P is followed by a Hashing Algorithm SHA1, SHA256, SHA512 self.signature_hash = self.signature[1:] if self.signature_hash not in ["SHA1", "SHA256", "SHA512"]: raise Exception("The signature hash needs to be SHA1, SHA256 " "or SHA512") elif self.signature_type == "S": # Allowed Session length is 64, 128, 256 or 512 try: self.session_length = int(self.signature[1:]) except ValueError: raise Exception("The session length needs to be a number.") if self.session_length not in [64, 128, 256, 512]: raise Exception("The session length needs to be 64, 128, " "256 or 512") elif self.signature_type == "T": # Allowed timestamp is [1-59]S, [1-56]M, [0-48]H self.time_frame = self.signature[-1:] if self.time_frame not in ["S", "M", "H"]: raise Exception("The time in the signature must be 'S', 'M' or " "'H'") self.time_value = self.signature[1:-1] try: self.time_value = int(self.time_value) except ValueError: raise Exception("You must specify a valid number in the " "timestamp in the signature.") if self.time_value < 0 or self.time_value > 59: raise Exception("You must specify a time value between 0 and " "59.") def create_challenge(self): """ Depending on the self.challenge_type and the self.challenge_length we create a challenge :return: a challenge string """ ret = None if self.challenge_type == "QH": ret = geturandom(length=self.challenge_length, hex=True) elif self.challenge_type == "QA": ret = get_alphanum_str(self.challenge_length) elif self.challenge_type == "QN": ret = get_rand_digit_str(length=self.challenge_length) if not ret: # pragma: no cover raise Exception("OCRA.create_challenge failed. Obviously no good " "challenge_type!") return ret class OCRA(object): def __init__(self, ocrasuite, key=None, security_object=None): """ Creates an OCRA Object that can be used to calculate OTP response or verify a response. :param ocrasuite: The ocrasuite description :type ocrasuite: basestring :param security_object: A privacyIDEA security object, that can be used to look up the key in the database :type security_object: secObject as defined in privacyidea.lib.crypto :param key: The HMAC Key :type key: binary :return: OCRA Object """ self.ocrasuite_obj = OCRASuite(ocrasuite) self.ocrasuite = str(ocrasuite) self.key = key self.security_obj = security_object digits = self.ocrasuite_obj.truncation self.hmac_obj = HmacOtp(secObj=self.security_obj, digits=digits, hashfunc=SHA_FUNC.get(self.ocrasuite_obj.sha)) def create_data_input(self, question, pin=None, pin_hash=None, counter=None, timesteps=None): """ Create the data_input to be used in the HMAC function In case of QN the question would be "111111" In case of QA the question would be "123ASD" In case of QH the question would be "BEEF" The question is transformed internally. :param question: The question can be :type question: basestring :param pin_hash: The hash of the pin :type pin_hash: basestring (hex) :param timesteps: timestemps :type timesteps: hex string :return: data_input :rytpe: binary """ # In case the ocrasuite comes as a unicode (like from the webui) we # need to convert it! data_input = str(self.ocrasuite) + b'\0' # Check for counter if self.ocrasuite_obj.counter == "C": if counter: counter = int(counter) counter = struct.pack('>Q', int(counter)) data_input += counter else: raise Exception("The ocrasuite {0!s} requires a counter".format( self.ocrasuite)) # Check for Question if self.ocrasuite_obj.challenge_type == "QN": # In case of QN question = '{0:x}'.format(int(question)) question += '0' * (len(question) % 2) question = binascii.unhexlify(question) question += '\0' * (128-len(question)) data_input += question elif self.ocrasuite_obj.challenge_type == "QA": question += '\0' * (128-len(question)) data_input += question elif self.ocrasuite_obj.challenge_type == "QH": # pragma: no cover # TODO: Implement OCRA QH raise NotImplementedError("OCRA Questsion QH not implemented, yet.") # in case of PIN if self.ocrasuite_obj.signature_type == "P": if pin_hash: data_input += binascii.unhexlify(pin_hash) elif pin: pin_hash = SHA_FUNC.get(self.ocrasuite_obj.signature_hash)( pin).digest() data_input += pin_hash else: raise Exception("The ocrasuite {0!s} requires a PIN!".format( self.ocrasuite)) elif self.ocrasuite_obj.signature_type == "T": if not timesteps: raise Exception("The ocrasuite {0!s} requires timesteps".format( self.ocrasuite)) # In case of Time timesteps = int(timesteps, 16) timesteps = struct.pack('>Q', int(timesteps)) data_input += timesteps elif self.ocrasuite_obj.signature_type == "S": # pragma: no cover # In case of session # TODO: Session not yet implemented raise NotImplementedError("OCRA Session not implemented, yet.") return data_input def get_response(self, question, pin=None, pin_hash=None, counter=None, timesteps=None): """ Create an OTP response from the given input values. :param question: :param pin: :param pin_hash: :param counter: :return: """ data_input = self.create_data_input(question, pin=pin, pin_hash=pin_hash, counter=counter, timesteps=timesteps) r = self.hmac_obj.generate(key=self.key, challenge=binascii.hexlify(data_input)) return r def check_response(self, response, question=None, pin=None, pin_hash=None, counter=None, timesteps=None): """ Check the given *response* if it is the correct response to the challenge/question. :param response: :param question: :param pin: :param pin_hash: :param counter: :param timesteps: :return: """ r = self.get_response(question, pin=pin, pin_hash=pin_hash, counter=counter, timesteps=timesteps) if r == response: return 1 else: return -1
agpl-3.0
thomasyu888/synapsePythonClient
synapseclient/core/cache.py
1
14358
# Note: Even though this has Sphinx format, this is not meant to be part of the public docs """ ************ File Caching ************ Implements a cache on local disk for Synapse file entities and other objects with a `FileHandle <https://docs.synapse.org/rest/org/sagebionetworks/repo/model/file/FileHandle.html>`_. This is part of the internal implementation of the client and should not be accessed directly by users of the client. """ import collections.abc import datetime import json import math import operator import os import re import shutil import typing from synapseclient.core.lock import Lock from synapseclient.core import utils CACHE_ROOT_DIR = os.path.join('~', '.synapseCache') def epoch_time_to_iso(epoch_time): """ Convert seconds since unix epoch to a string in ISO format """ return None if epoch_time is None else utils.datetime_to_iso(utils.from_unix_epoch_time_secs(epoch_time)) def iso_time_to_epoch(iso_time): """ Convert an ISO formatted time into seconds since unix epoch """ return None if iso_time is None else utils.to_unix_epoch_time_secs(utils.iso_to_datetime(iso_time)) def compare_timestamps(modified_time, cached_time): """ Compare two ISO formatted timestamps, with a special case when cached_time ends in .000Z. For backward compatibility, we always write .000 for milliseconds into the cache. We then match a cached time ending in .000Z, meaning zero milliseconds with a modified time with any number of milliseconds. :param modified_time: float representing seconds since unix epoch :param cached_time: string holding a ISO formatted time """ if cached_time is None or modified_time is None: return False if cached_time.endswith(".000Z"): return cached_time == epoch_time_to_iso(math.floor(modified_time)) else: return cached_time == epoch_time_to_iso(modified_time) def _get_modified_time(path): if os.path.exists(path): return os.path.getmtime(path) return None class Cache: """ Represent a cache in which files are accessed by file handle ID. """ def __setattr__(self, key, value): # expand out home shortcut ('~') and environment variables when setting cache_root_dir if key == "cache_root_dir": value = os.path.expandvars(os.path.expanduser(value)) # create the cache_root_dir if it does not already exist if not os.path.exists(value): os.makedirs(value) self.__dict__[key] = value def __init__(self, cache_root_dir=CACHE_ROOT_DIR, fanout=1000): # set root dir of cache in which meta data will be stored and files # will be stored here by default, but other locations can be specified self.cache_root_dir = cache_root_dir self.fanout = fanout self.cache_map_file_name = ".cacheMap" def get_cache_dir(self, file_handle_id): if isinstance(file_handle_id, collections.abc.Mapping): if 'dataFileHandleId' in file_handle_id: file_handle_id = file_handle_id['dataFileHandleId'] elif 'concreteType' in file_handle_id \ and 'id' in file_handle_id \ and file_handle_id['concreteType'].startswith('org.sagebionetworks.repo.model.file'): file_handle_id = file_handle_id['id'] return os.path.join(self.cache_root_dir, str(int(file_handle_id) % self.fanout), str(file_handle_id)) def _read_cache_map(self, cache_dir): cache_map_file = os.path.join(cache_dir, self.cache_map_file_name) if not os.path.exists(cache_map_file): return {} with open(cache_map_file, 'r') as f: try: cache_map = json.load(f) except json.decoder.JSONDecodeError: # a corrupt cache map file that is not parseable as JSON is treated # as if it does not exist at all (will be overwritten). return {} return cache_map def _write_cache_map(self, cache_dir, cache_map): if not os.path.exists(cache_dir): os.makedirs(cache_dir) cache_map_file = os.path.join(cache_dir, self.cache_map_file_name) with open(cache_map_file, 'w') as f: json.dump(cache_map, f) f.write('\n') # For compatibility with R's JSON parser def contains(self, file_handle_id, path): """ Given a file and file_handle_id, return True if an unmodified cached copy of the file exists at the exact path given or False otherwise. :param file_handle_id: :param path: file path at which to look for a cached copy """ cache_dir = self.get_cache_dir(file_handle_id) if not os.path.exists(cache_dir): return False with Lock(self.cache_map_file_name, dir=cache_dir): cache_map = self._read_cache_map(cache_dir) path = utils.normalize_path(path) cached_time = cache_map.get(path, None) if cached_time: return compare_timestamps(_get_modified_time(path), cached_time) return False def get(self, file_handle_id, path=None): """ Retrieve a file with the given file handle from the cache. :param file_handle_id: :param path: If the given path is None, look for a cached copy of the file in the cache directory. If the path is a directory, look there for a cached copy. If a full file-path is given, only check whether that exact file exists and is unmodified since it was cached. :returns: Either a file path, if an unmodified cached copy of the file exists in the specified location or None if it does not """ cache_dir = self.get_cache_dir(file_handle_id) if not os.path.exists(cache_dir): return None with Lock(self.cache_map_file_name, dir=cache_dir): cache_map = self._read_cache_map(cache_dir) path = utils.normalize_path(path) # If the caller specifies a path and that path exists in the cache # but has been modified, we need to indicate no match by returning # None. The logic for updating a synapse entity depends on this to # determine the need to upload a new file. if path is not None: # If we're given a path to a directory, look for a cached file in that directory if os.path.isdir(path): matching_unmodified_directory = None removed_entry_from_cache = False # determines if cache_map needs to be rewritten to disk # iterate a copy of cache_map to allow modifying original cache_map for cached_file_path, cached_time in dict(cache_map).items(): if path == os.path.dirname(cached_file_path): # compare_timestamps has an implicit check for whether the path exists if compare_timestamps(_get_modified_time(cached_file_path), cached_time): # "break" instead of "return" to write removed invalid entries to disk if necessary matching_unmodified_directory = cached_file_path break else: # remove invalid cache entries pointing to files that that no longer exist # or have been modified del cache_map[cached_file_path] removed_entry_from_cache = True if removed_entry_from_cache: # write cache_map with non-existent entries removed self._write_cache_map(cache_dir, cache_map) if matching_unmodified_directory is not None: return matching_unmodified_directory # if we're given a full file path, look up a matching file in the cache else: cached_time = cache_map.get(path, None) if cached_time: return path if compare_timestamps(_get_modified_time(path), cached_time) else None # return most recently cached and unmodified file OR # None if there are no unmodified files for cached_file_path, cached_time in sorted(cache_map.items(), key=operator.itemgetter(1), reverse=True): if compare_timestamps(_get_modified_time(cached_file_path), cached_time): return cached_file_path return None def add(self, file_handle_id, path): """ Add a file to the cache """ if not path or not os.path.exists(path): raise ValueError("Can't find file \"%s\"" % path) cache_dir = self.get_cache_dir(file_handle_id) with Lock(self.cache_map_file_name, dir=cache_dir): cache_map = self._read_cache_map(cache_dir) path = utils.normalize_path(path) # write .000 milliseconds for backward compatibility cache_map[path] = epoch_time_to_iso(math.floor(_get_modified_time(path))) self._write_cache_map(cache_dir, cache_map) return cache_map def remove(self, file_handle_id, path=None, delete=None): """ Remove a file from the cache. :param file_handle_id: Will also extract file handle id from either a File or file handle :param path: If the given path is None, remove (and potentially delete) all cached copies. If the path is that of a file in the .cacheMap file, remove it. :returns: A list of files removed """ removed = [] cache_dir = self.get_cache_dir(file_handle_id) # if we've passed an entity and not a path, get path from entity if path is None and isinstance(file_handle_id, collections.abc.Mapping) and 'path' in file_handle_id: path = file_handle_id['path'] with Lock(self.cache_map_file_name, dir=cache_dir): cache_map = self._read_cache_map(cache_dir) if path is None: for path in cache_map: if delete is True and os.path.exists(path): os.remove(path) removed.append(path) cache_map = {} else: path = utils.normalize_path(path) if path in cache_map: if delete is True and os.path.exists(path): os.remove(path) del cache_map[path] removed.append(path) self._write_cache_map(cache_dir, cache_map) return removed def _cache_dirs(self): """ Generate a list of all cache dirs, directories of the form: [cache.cache_root_dir]/949/59949 """ for item1 in os.listdir(self.cache_root_dir): path1 = os.path.join(self.cache_root_dir, item1) if os.path.isdir(path1) and re.match('\\d+', item1): for item2 in os.listdir(path1): path2 = os.path.join(path1, item2) if os.path.isdir(path2) and re.match('\\d+', item2): yield path2 def purge( self, before_date: typing.Union[datetime.datetime, int] = None, after_date: typing.Union[datetime.datetime, int] = None, dry_run: bool = False ): """ Purge the cache. Use with caution. Deletes files whose cache maps were last updated in a specified period. Deletes .cacheMap files and files stored in the cache.cache_root_dir, but does not delete files stored outside the cache. Either the before_date or after_date must be specified. If both are passed, files between the two dates are selected for removal. Dates must either be a timezone naive Python datetime.datetime instance or the number of seconds since the unix epoch. For example to delete all the files modified in January 2021, either of the following can be used:: # using offset naive datetime objects cache.purge(after_date=datetime.datetime(2021, 1, 1), before_date=datetime.datetime(2021, 2, 1)) # using seconds since the unix epoch cache.purge(after_date=1609459200, before_date=1612137600) :param before_date: if specified, all files before this date will be removed :param after_date: if specified, all files after this date will be removed :param dry_run: if dry_run is True, then the selected files are printed rather than removed :returns: the number of files selected for removal """ if before_date is None and after_date is None: raise ValueError("Either before date or after date should be provided") if isinstance(before_date, datetime.datetime): before_date = utils.to_unix_epoch_time_secs(before_date) if isinstance(after_date, datetime.datetime): after_date = utils.to_unix_epoch_time_secs(after_date) if before_date and after_date and before_date < after_date: raise ValueError("Before date should be larger than after date") count = 0 for cache_dir in self._cache_dirs(): # _get_modified_time returns None if the cache map file doesn't # exist and n > None evaluates to True in python 2.7(wtf?). I'm guessing it's # OK to purge directories in the cache that have no .cacheMap file last_modified_time = _get_modified_time(os.path.join(cache_dir, self.cache_map_file_name)) if last_modified_time is None or ( (not before_date or before_date > last_modified_time) and (not after_date or after_date < last_modified_time)): if dry_run: print(cache_dir) else: shutil.rmtree(cache_dir) count += 1 return count
apache-2.0
beckastar/django
tests/admin_custom_urls/models.py
20
2503
from functools import update_wrapper from django.contrib import admin from django.core.urlresolvers import reverse from django.db import models from django.http import HttpResponseRedirect from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Action(models.Model): name = models.CharField(max_length=50, primary_key=True) description = models.CharField(max_length=70) def __str__(self): return self.name class ActionAdmin(admin.ModelAdmin): """ A ModelAdmin for the Action model that changes the URL of the add_view to '<app name>/<model name>/!add/' The Action model has a CharField PK. """ list_display = ('name', 'description') def remove_url(self, name): """ Remove all entries named 'name' from the ModelAdmin instance URL patterns list """ return [url for url in super(ActionAdmin, self).get_urls() if url.name != name] def get_urls(self): # Add the URL of our custom 'add_view' view to the front of the URLs # list. Remove the existing one(s) first from django.conf.urls import patterns, url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name view_name = '%s_%s_add' % info return patterns('', url(r'^!add/$', wrap(self.add_view), name=view_name), ) + self.remove_url(view_name) class Person(models.Model): name = models.CharField(max_length=20) class PersonAdmin(admin.ModelAdmin): def response_post_save_add(self, request, obj): return HttpResponseRedirect( reverse('admin:admin_custom_urls_person_history', args=[obj.pk])) def response_post_save_change(self, request, obj): return HttpResponseRedirect( reverse('admin:admin_custom_urls_person_delete', args=[obj.pk])) class Car(models.Model): name = models.CharField(max_length=20) class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return super(CarAdmin, self).response_add( request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk])) admin.site.register(Action, ActionAdmin) admin.site.register(Person, PersonAdmin) admin.site.register(Car, CarAdmin)
bsd-3-clause
StackVista/sts-agent-integrations-core
splunk_event/check.py
1
2417
""" Events as generic events from splunk. StackState. """ # 3rd party from utils.splunk.splunk import SplunkTelemetryInstanceConfig, SavedSearches from utils.splunk.splunk_telemetry import SplunkTelemetryInstance, SplunkTelemetrySavedSearch from utils.splunk.splunk_telemetry_base import SplunkTelemetryBase class EventSavedSearch(SplunkTelemetrySavedSearch): last_events_at_epoch_time = set() def __init__(self, instance_config, saved_search_instance): super(EventSavedSearch, self).__init__(instance_config, saved_search_instance) self.optional_fields = { "event_type": "event_type", "source_type_name": "_sourcetype", "msg_title": "msg_title", "msg_text": "msg_text", } class SplunkEvent(SplunkTelemetryBase): SERVICE_CHECK_NAME = "splunk.event_information" def __init__(self, name, init_config, agentConfig, instances=None): super(SplunkEvent, self).__init__(name, init_config, agentConfig, "splunk_event", instances) def _apply(self, **kwargs): self.event(kwargs) def get_instance(self, instance, current_time): metric_instance_config = SplunkTelemetryInstanceConfig(instance, self.init_config, { 'default_request_timeout_seconds': 5, 'default_search_max_retry_count': 3, 'default_search_seconds_between_retries': 1, 'default_verify_ssl_certificate': False, 'default_batch_size': 1000, 'default_saved_searches_parallel': 3, 'default_initial_history_time_seconds': 0, 'default_max_restart_history_seconds': 86400, 'default_max_query_chunk_seconds': 300, 'default_initial_delay_seconds': 0, 'default_unique_key_fields': ["_bkt", "_cd"], 'default_app': "search", 'default_parameters': { "force_dispatch": True, "dispatch.now": True } }) saved_searches = [] if instance['saved_searches'] is not None: saved_searches = instance['saved_searches'] event_saved_searches = SavedSearches([ EventSavedSearch(metric_instance_config, saved_search_instance) for saved_search_instance in saved_searches ]) return SplunkTelemetryInstance(current_time, instance, metric_instance_config, event_saved_searches)
bsd-3-clause
cjb/curveship
gui-curveship.py
1
13368
#!/usr/bin/env python 'An interactive fiction system offering control over the narrative discourse.' __author__ = 'Nick Montfort' __copyright__ = 'Copyright 2011 Nick Montfort' __license__ = 'ISC' __version__ = '0.5.0.0' __status__ = 'Development' import sys import os import time import optparse import clarifier import command_map import discourse_model import joker import microplanner import preparer import presenter import recognizer import reply_planner import world_model base_path = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0, os.path.join(base_path, "lib")) if base_path: os.chdir(base_path) from game import Game from level import CurveshipLevel from level import StaticLevel from display import Display class Multistream(object): 'Encapsulates multiple output streams.' def __init__(self, streams, log=None): self.streams = streams self.log = log def close(self): """Close each of the streams. If one or more of the streams returns some exit status, the maximum value is returned by this method.""" overall_status = None for stream in self.streams: status = stream.close() if status is not None: overall_status = max(overall_status, status) return overall_status def write(self, string): 'Write string to each of the streams.' for stream in self.streams: stream.write(string) class Main(): def __init__(self, argv): self.game_over = False self.display = Display() self.level = None self.main(argv) def start_log(self, out_streams): 'Open a log file named with the next available integer.' log_files = [os.path.splitext(l)[0] for l in os.listdir('logs/') if os.path.splitext(l)[1] == '.log'] if len(log_files) == 0: latest = 0 else: latest = max([int(log_file) for log_file in log_files]) log_file = 'logs/' + str(latest + 1) + '.log' try: log = file(log_file, 'w') except IOError, err: msg = ('Unable to open log file "' + log_file + '" for ' + 'writing due to this error: ' + str(err)) raise joker.StartupError(msg) # So that we output to the screen and the log file: out_streams.streams.append(log) # And indicate that this stream is the log file: out_streams.log = log presenter.present('\nLogged to: ' + log_file + '\nSession started ' + time.strftime("%Y-%m-%d %H:%M:%S"), out_streams) return out_streams def initialize(self, if_file, spin_files, out_streams): 'Load all files and present the header and prologue.' for startup_string in joker.session_startup(__version__): presenter.center(startup_string, out_streams) fiction = joker.load_fiction(if_file, ['discourse', 'items'], discourse_model.FICTION_DEFAULTS) presenter.center('fiction: ' + if_file, out_streams) world = world_model.World(fiction) world.set_concepts(fiction.concepts) for i in dir(fiction): if i[:8] == 'COMMAND_': setattr(command_map, i.partition('_')[2], getattr(fiction, i)) delattr(fiction, i) for (key, value) in discourse_model.SPIN_DEFAULTS.items(): if key not in fiction.discourse['spin']: fiction.discourse['spin'][key] = value while len(spin_files) > 0: next_file = spin_files.pop(0) new_spin = joker.load_spin(fiction.discourse['spin'], next_file) fiction.discourse['spin'].update(new_spin) presenter.center('spin: ' + next_file, out_streams) presenter.present('\n', out_streams) presenter.present('', out_streams) discourse = discourse_model.Discourse(fiction.discourse) reply = joker.show_frontmatter(discourse) if 'prologue' in discourse.metadata: reply += '\n\n' + joker.show_prologue(discourse.metadata) presenter.present(reply, out_streams) return (world, discourse) def handle_input(self, user_input, world, discourse, in_stream, out_streams): """Deal with input obtained, sending it to the appropriate module. The commanded character's concept is used when trying to recognize commands.""" c_concept = world.concept[discourse.spin['commanded']] user_input = recognizer.recognize(user_input, discourse, c_concept) presentation = "" if user_input.unrecognized: user_input = clarifier.clarify(user_input, c_concept, discourse, in_stream, out_streams) if user_input.command: user_input, id_list, world = self.simulator(user_input, world, discourse.spin['commanded']) if hasattr(world.item['@cosmos'], 'update_spin'): discourse.spin = world.item['@cosmos'].update_spin(world, discourse) spin = discourse.spin if hasattr(world.item['@cosmos'], 'use_spin'): spin = world.item['@cosmos'].use_spin(world, discourse.spin) f_concept = world.concept[spin['focalizer']] tale, discourse = self.teller(id_list, f_concept, discourse) presentation = presenter.present(tale, out_streams) elif user_input.directive: texts, world, discourse = joker.joke(user_input.normal, world, discourse) for text in texts: if text is not None: presentation = presenter.present(text, out_streams) discourse.input_list.update(user_input) return (user_input, world, discourse, presentation) def each_turn(self, world, discourse, in_stream, out_streams): 'Obtain and processes input, if the session is interactive.' if discourse.spin['commanded'] is None: if hasattr(world.item['@cosmos'], 'interval'): world.item['@cosmos'].interval() _, id_list, world = self.simulator(None, world, discourse.spin['commanded']) focal_concept = world.concept[discourse.spin['focalizer']] reply_text, discourse = self.teller(id_list, focal_concept, discourse) presenter.present(reply_text, out_streams) else: if (hasattr(discourse, 'initial_inputs') and len(discourse.initial_inputs) > 0): input_string = discourse.initial_inputs.pop(0) user_input = preparer.tokenize(input_string, discourse.separator) presenter.present('[> ' + input_string, out_streams, '', '') else: user_input = preparer.prepare(discourse.separator, discourse.typo.prompt, in_stream, out_streams) # After each input, present a newline all by itself. presenter.present('\n', out_streams, '', '') while len(user_input.tokens) > 0 and world.running: (user_input, world, discourse) = self.handle_input(user_input, world, discourse, in_stream, out_streams) presenter.present(discourse.input_list.show(1), out_streams.log) return (world, discourse) def simulator(self, user_input, world, commanded, actions_to_do=None): 'Simulate the IF world using the Action from user input.' if actions_to_do is None: actions_to_do = [] done_list = [] start_time = world.ticks for tag in world.item: if (world.item[tag].actor and not tag == commanded and world.item[tag].alive): # The commanded character does not act automatically. That is, # his, her, or its "act" method is not called. new_actions = world.item[tag].act(command_map, world.concept[tag]) actions_to_do.extend(new_actions) if commanded is not None and user_input is not None: commanded = world.item[commanded] c_action = commanded.do_command(user_input.normal, command_map, world) if c_action is not None: c_action.cause = '"' + ' '.join(user_input.normal) + '"' actions_to_do.append(c_action) if user_input is not None: user_input.caused = c_action.id current_time = start_time while len(actions_to_do) > 0 and world.running: action = actions_to_do.pop(0) to_be_done = action.do(world) done_list.append(action.id) if action.final: world.running = False actions_to_do = to_be_done + actions_to_do if action.end > current_time: world.advance_clock(action.end - current_time) current_time = action.end return user_input, done_list, world def teller(self, id_list, concept, discourse): 'Narrate actions based on the concept. Update the discourse.' reply_plan = reply_planner.plan(id_list, concept, discourse) section = microplanner.specify(reply_plan, concept, discourse) output = section.realize(concept, discourse) return output, discourse def parse_command_line(self, argv): 'Improved option/argument parsing and help thanks to Andrew Plotkin.' parser = optparse.OptionParser(usage='[options] fiction.py [ spin.py ... ]') parser.add_option('--auto', dest='autofile', help='read inputs from FILE', metavar='FILE') parser.add_option('--nodebug', action='store_false', dest='debug', help='disable debugging directives', default=True) opts, args = parser.parse_args(argv[1:]) if not args: parser.print_usage() msg = ('At least one argument (the fiction file name) is ' + 'needed; any other file names are processed in order ' + 'as spin files.') raise joker.StartupError(msg) return opts, args def main(self, argv, in_stream=sys.stdin, out_stream=sys.stdout): "Set up a session and run Curveship's main loop." return_code = 0 out_streams = Multistream([out_stream]) opts, args = self.parse_command_line(argv) out_streams = self.start_log(out_streams) self.world, self.discourse = self.initialize(args[0], args[1:], out_streams) self.discourse.debug = opts.debug if opts.autofile is not None: auto = open(opts.autofile, 'r+') self.discourse.initial_inputs = auto.readlines() auto.close() if len(self.world.act) > 0: _, id_list, self.world = self.simulator(None, self.world, self.discourse.spin['commanded'], self.world.act.values()) focal_concept = self.world.concept[self.discourse.spin['focalizer']] reply_text, discourse = self.teller(id_list, focal_concept, self.discourse) initial_text = presenter.present(reply_text, out_streams) # Game().static_level() Game().curve_level(self, preparer, self.world, discourse, initial_text) try: if len(self.world.act) > 0: _, id_list, world = self.simulator(None, self.world, discourse.spin['commanded'], self.world.act.values()) focal_concept = world.concept[discourse.spin['focalizer']] reply_text, discourse = self.teller(id_list, focal_concept, discourse) presenter.present(reply_text, out_streams) while world.running: previous_time = time.time() world, discourse = self.each_turn(world, discourse, in_stream, out_streams) out_streams.log.write('#' + str(time.time() - previous_time)) for step in range(8): self.display.show_frame() except joker.StartupError, err: presenter.present(err.msg, Multistream([sys.stderr])) return_code = 2 except KeyboardInterrupt, err: presenter.present('\n', out_streams) return_code = 2 except EOFError, err: presenter.present('\n', out_streams) return_code = 2 finally: in_stream.close() out_streams.close() return return_code if __name__ == '__main__': sys.exit(Main(sys.argv))
isc
phassoa/openelisglobal-core
liquibase/OE2.7/CILNSPMassive/scripts/testResult.py
6
3241
#!/usr/bin/env python # -*- coding: utf-8 -*- def convert_type_to_symbole( type): if type == 'Numeric' or type == 'numeric' : return 'N' if type == 'Free Text': return 'R' if type == 'Select list': return 'D' if type == 'multi': return 'M' return type def esc_char(name): if "'" in name: return "$$" + name + "$$" else: return "'" + name + "'" def get_split_names( name ): split_name_list = name.split("/") for i in range(0, len(split_name_list)): split_name_list[i] = split_name_list[i].strip() return split_name_list def get_comma_split_names( name ): split_name_list = [name] if ',' in name: split_name_list = name.split(",") elif ';' in name: split_name_list = name.split(";") for i in range(0, len(split_name_list)): split_name_list[i] = split_name_list[i].strip() return split_name_list test_names = [] sample_types = [] select = [] type = [] descriptions = [] name_file = open('testName.txt','r') sample_type_file = open("sampleType.txt") select_file = open("selectList.txt", 'r') result_type_file = open("resultType.txt", 'r') results = open("MassiveTestResults.sql", 'w') for line in name_file: test_names.append(line.strip()) name_file.close() for line in sample_type_file: sample_types.append(line.strip()) sample_type_file.close() for line in select_file: select.append(line.strip()) select_file.close() for line in result_type_file: type.append( line.strip()) result_type_file.close() nextVal = " VALUES ( nextval( 'test_result_seq' ) " order = 10 for row in range(0, len(test_names)): if len(test_names[row]) > 1: #it's a new entry result_type = convert_type_to_symbole(type[row]) description = esc_char(test_names[row] + "(" + sample_types[row] + ")") if description not in descriptions: descriptions.append(description) if result_type == 'D' or result_type == 'M': split_selections = get_comma_split_names( select[row]) for j in range(0, len(split_selections)): dictionary_select = " ( select max(id) from clinlims.dictionary where dict_entry =" + esc_char(split_selections[j].strip()) + " ) " results.write("INSERT INTO test_result( id, test_id, tst_rslt_type, value , lastupdated, sort_order)\n\t") results.write( nextVal + ", ( select id from clinlims.test where description = " + description + " ) , '") results.write( result_type + "' , " + dictionary_select + " , now() , " + str(order) + ");\n") order += 10 else: results.write("INSERT INTO test_result( id, test_id, tst_rslt_type, value , lastupdated, sort_order)\n\t") results.write( nextVal + ", ( select id from clinlims.test where description = " + description + " ) , '") results.write( result_type + "' , null , now() , " + str(order) + ");\n") order += 10 print "Done results in MassiveTestResults.sql"
mpl-2.0
zjx-immersion/BDD-Test-Node
node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input_test.py
604
3207
#!/usr/bin/env python # Copyright 2013 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. """Unit tests for the input.py file.""" import gyp.input import unittest import sys class TestFindCycles(unittest.TestCase): def setUp(self): self.nodes = {} for x in ('a', 'b', 'c', 'd', 'e'): self.nodes[x] = gyp.input.DependencyGraphNode(x) def _create_dependency(self, dependent, dependency): dependent.dependencies.append(dependency) dependency.dependents.append(dependent) def test_no_cycle_empty_graph(self): for label, node in self.nodes.iteritems(): self.assertEquals([], node.FindCycles()) def test_no_cycle_line(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['d']) for label, node in self.nodes.iteritems(): self.assertEquals([], node.FindCycles()) def test_no_cycle_dag(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['a'], self.nodes['c']) self._create_dependency(self.nodes['b'], self.nodes['c']) for label, node in self.nodes.iteritems(): self.assertEquals([], node.FindCycles()) def test_cycle_self_reference(self): self._create_dependency(self.nodes['a'], self.nodes['a']) self.assertEquals([(self.nodes['a'], self.nodes['a'])], self.nodes['a'].FindCycles()) def test_cycle_two_nodes(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['a']) self.assertEquals([(self.nodes['a'], self.nodes['b'], self.nodes['a'])], self.nodes['a'].FindCycles()) self.assertEquals([(self.nodes['b'], self.nodes['a'], self.nodes['b'])], self.nodes['b'].FindCycles()) def test_two_cycles(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['a']) self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['b']) cycles = self.nodes['a'].FindCycles() self.assertTrue( (self.nodes['a'], self.nodes['b'], self.nodes['a']) in cycles) self.assertTrue( (self.nodes['b'], self.nodes['c'], self.nodes['b']) in cycles) self.assertEquals(2, len(cycles)) def test_big_cycle(self): self._create_dependency(self.nodes['a'], self.nodes['b']) self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['d']) self._create_dependency(self.nodes['d'], self.nodes['e']) self._create_dependency(self.nodes['e'], self.nodes['a']) self.assertEquals([(self.nodes['a'], self.nodes['b'], self.nodes['c'], self.nodes['d'], self.nodes['e'], self.nodes['a'])], self.nodes['a'].FindCycles()) if __name__ == '__main__': unittest.main()
apache-2.0
baylee-d/osf.io
addons/mendeley/migrations/0001_initial.py
56
1509
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-03-23 20:34 from __future__ import unicode_literals from django.db import migrations, models import osf.models.base import osf.utils.datetime_aware_jsonfield class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='NodeSettings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_id', models.CharField(db_index=True, default=osf.models.base.generate_object_id, max_length=24, unique=True)), ('deleted', models.BooleanField(default=False)), ('list_id', models.TextField(blank=True, null=True)), ], options={ 'abstract': False, }, ), migrations.CreateModel( name='UserSettings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('_id', models.CharField(db_index=True, default=osf.models.base.generate_object_id, max_length=24, unique=True)), ('deleted', models.BooleanField(default=False)), ('oauth_grants', osf.utils.datetime_aware_jsonfield.DateTimeAwareJSONField(blank=True, default=dict)), ], options={ 'abstract': False, }, ), ]
apache-2.0
ulope/django
django/contrib/auth/tests/test_models.py
34
7989
from django.contrib.auth import get_user_model from django.contrib.auth.models import AbstractUser, Group, Permission, User, UserManager from django.contrib.auth.tests.utils import skipIfCustomUser from django.contrib.contenttypes.models import ContentType from django.core import mail from django.db.models.signals import post_save from django.test import TestCase, override_settings @skipIfCustomUser @override_settings(USE_TZ=False) class NaturalKeysTestCase(TestCase): fixtures = ['authtestdata.json'] def test_user_natural_key(self): staff_user = User.objects.get(username='staff') self.assertEqual(User.objects.get_by_natural_key('staff'), staff_user) self.assertEqual(staff_user.natural_key(), ('staff',)) def test_group_natural_key(self): users_group = Group.objects.create(name='users') self.assertEqual(Group.objects.get_by_natural_key('users'), users_group) @skipIfCustomUser @override_settings(USE_TZ=False) class LoadDataWithoutNaturalKeysTestCase(TestCase): fixtures = ['regular.json'] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username='my_username') group = Group.objects.get(name='my_group') self.assertEqual(group, user.groups.get()) @skipIfCustomUser @override_settings(USE_TZ=False) class LoadDataWithNaturalKeysTestCase(TestCase): fixtures = ['natural.json'] def test_user_is_created_and_added_to_group(self): user = User.objects.get(username='my_username') group = Group.objects.get(name='my_group') self.assertEqual(group, user.groups.get()) class LoadDataWithNaturalKeysAndMultipleDatabasesTestCase(TestCase): multi_db = True def test_load_data_with_user_permissions(self): # Create test contenttypes for both databases default_objects = [ ContentType.objects.db_manager('default').create( model='examplemodela', name='example model a', app_label='app_a', ), ContentType.objects.db_manager('default').create( model='examplemodelb', name='example model b', app_label='app_b', ), ] other_objects = [ ContentType.objects.db_manager('other').create( model='examplemodelb', name='example model b', app_label='app_b', ), ContentType.objects.db_manager('other').create( model='examplemodela', name='example model a', app_label='app_a', ), ] # Now we create the test UserPermission Permission.objects.db_manager("default").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=default_objects[1], ) Permission.objects.db_manager("other").create( name="Can delete example model b", codename="delete_examplemodelb", content_type=other_objects[0], ) perm_default = Permission.objects.get_by_natural_key( 'delete_examplemodelb', 'app_b', 'examplemodelb', ) perm_other = Permission.objects.db_manager('other').get_by_natural_key( 'delete_examplemodelb', 'app_b', 'examplemodelb', ) self.assertEqual(perm_default.content_type_id, default_objects[1].id) self.assertEqual(perm_other.content_type_id, other_objects[0].id) @skipIfCustomUser class UserManagerTestCase(TestCase): def test_create_user(self): email_lowercase = 'normal@normal.com' user = User.objects.create_user('user', email_lowercase) self.assertEqual(user.email, email_lowercase) self.assertEqual(user.username, 'user') self.assertFalse(user.has_usable_password()) def test_create_user_email_domain_normalize_rfc3696(self): # According to http://tools.ietf.org/html/rfc3696#section-3 # the "@" symbol can be part of the local part of an email address returned = UserManager.normalize_email(r'Abc\@DEF@EXAMPLE.com') self.assertEqual(returned, r'Abc\@DEF@example.com') def test_create_user_email_domain_normalize(self): returned = UserManager.normalize_email('normal@DOMAIN.COM') self.assertEqual(returned, 'normal@domain.com') def test_create_user_email_domain_normalize_with_whitespace(self): returned = UserManager.normalize_email('email\ with_whitespace@D.COM') self.assertEqual(returned, 'email\ with_whitespace@d.com') def test_empty_username(self): self.assertRaisesMessage( ValueError, 'The given username must be set', User.objects.create_user, username='' ) class AbstractUserTestCase(TestCase): def test_email_user(self): # valid send_mail parameters kwargs = { "fail_silently": False, "auth_user": None, "auth_password": None, "connection": None, "html_message": None, } abstract_user = AbstractUser(email='foo@bar.com') abstract_user.email_user(subject="Subject here", message="This is a message", from_email="from@domain.com", **kwargs) # Test that one message has been sent. self.assertEqual(len(mail.outbox), 1) # Verify that test email contains the correct attributes: message = mail.outbox[0] self.assertEqual(message.subject, "Subject here") self.assertEqual(message.body, "This is a message") self.assertEqual(message.from_email, "from@domain.com") self.assertEqual(message.to, [abstract_user.email]) def test_last_login_default(self): user1 = User.objects.create(username='user1') self.assertIsNone(user1.last_login) user2 = User.objects.create_user(username='user2') self.assertIsNone(user2.last_login) class IsActiveTestCase(TestCase): """ Tests the behavior of the guaranteed is_active attribute """ @skipIfCustomUser def test_builtin_user_isactive(self): user = User.objects.create(username='foo', email='foo@bar.com') # is_active is true by default self.assertEqual(user.is_active, True) user.is_active = False user.save() user_fetched = User.objects.get(pk=user.pk) # the is_active flag is saved self.assertFalse(user_fetched.is_active) @override_settings(AUTH_USER_MODEL='auth.IsActiveTestUser1') def test_is_active_field_default(self): """ tests that the default value for is_active is provided """ UserModel = get_user_model() user = UserModel(username='foo') self.assertEqual(user.is_active, True) # you can set the attribute - but it will not save user.is_active = False # there should be no problem saving - but the attribute is not saved user.save() user_fetched = UserModel._default_manager.get(pk=user.pk) # the attribute is always true for newly retrieved instance self.assertEqual(user_fetched.is_active, True) @skipIfCustomUser class TestCreateSuperUserSignals(TestCase): """ Simple test case for ticket #20541 """ def post_save_listener(self, *args, **kwargs): self.signals_count += 1 def setUp(self): self.signals_count = 0 post_save.connect(self.post_save_listener, sender=User) def tearDown(self): post_save.disconnect(self.post_save_listener, sender=User) def test_create_user(self): User.objects.create_user("JohnDoe") self.assertEqual(self.signals_count, 1) def test_create_superuser(self): User.objects.create_superuser("JohnDoe", "mail@example.com", "1") self.assertEqual(self.signals_count, 1)
bsd-3-clause
chromium/chromium
third_party/blink/renderer/bindings/scripts/interface_dependency_resolver.py
5
18762
# Copyright (C) 2013 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. """Resolve interface dependencies, producing a merged IdlDefinitions object. This library computes interface dependencies (partial interfaces and includes), reads the dependency files, and merges them to the IdlDefinitions for the main IDL file, producing an IdlDefinitions object representing the entire interface. Design doc: http://www.chromium.org/developers/design-documents/idl-compiler#TOC-Dependency-resolution """ import os.path from utilities import idl_filename_to_component, is_valid_component_dependency, merge_dict_recursively # The following extended attributes can be applied to a dependency interface, # and are then applied to the individual members when merging. # Note that this moves the extended attribute from the interface to the member, # which changes the semantics and yields different code than the same extended # attribute on the main interface. DEPENDENCY_EXTENDED_ATTRIBUTES = frozenset([ 'CrossOriginIsolated', 'DirectSocketEnabled', 'RuntimeEnabled', 'SecureContext', ]) class InterfaceDependencyResolver(object): def __init__(self, interfaces_info, reader): """Initialize dependency resolver. Args: interfaces_info: dict of interfaces information, from compute_dependencies.py reader: IdlReader, used for reading dependency files """ self.interfaces_info = interfaces_info self.reader = reader def resolve_dependencies(self, definitions, component): """Resolve dependencies, merging them into IDL definitions of main file. Dependencies consist of 'partial interface' for the same interface as in the main file, and mixins that this interface 'includes'. These are merged into the main IdlInterface, as the main IdlInterface implements all these members. Partial interfaces and mixins are added to IdlDefinitions, but not merged into the main IdlInterface, as these are only referenced (their members are introspected, but not implemented in this interface). Inherited extended attributes are also added to the main IdlInterface. Modifies definitions in place by adding parsed dependencies. Args: definitions: IdlDefinitions object, modified in place component: string, describing where the above definitions are defined, 'core' or 'modules'. See KNOWN_COMPONENTS in utilities.py Returns: A dictionary whose key is component and value is IdlDefinitions object whose dependency is resolved. Raises: Exception: A given IdlDefinitions object doesn't have any interfaces, or a given IdlDefinitions object has incorrect referenced interfaces. """ # TODO(crbug.com/579896): we need to resolve dependency when we # support partial dictionary. if not definitions.interfaces: raise Exception('No need to resolve any dependencies of ' 'this definition: %s, because this should ' 'have a dictionary.' % definitions.idl_name) target_interface = next(iter(definitions.interfaces.values())) interface_name = target_interface.name interface_info = self.interfaces_info[interface_name] if 'inherited_extended_attributes' in interface_info: target_interface.extended_attributes.update( interface_info['inherited_extended_attributes']) resolved_definitions = merge_interface_dependencies( definitions, component, target_interface, interface_info['dependencies_full_paths'] + interface_info['dependencies_other_component_full_paths'], self.reader) inherit_unforgeable_attributes(resolved_definitions, self.interfaces_info) for referenced_interface_name in \ interface_info['referenced_interfaces']: referenced_definitions = self.reader.read_idl_definitions( self.interfaces_info[referenced_interface_name]['full_path']) for referenced_component in referenced_definitions: if not is_valid_component_dependency(component, referenced_component): raise Exception('This definitions: %s is defined in %s ' 'but reference interface:%s is defined ' 'in %s' % (definitions.idl_name, component, referenced_interface_name, referenced_component)) resolved_definitions[component].update( referenced_definitions[component]) return resolved_definitions def merge_interface_dependencies(definitions, component, target_interface, dependency_idl_filenames, reader): """Merge dependencies ('partial interface' and 'implements') in dependency_idl_filenames into target_interface. Args: definitions: IdlDefinitions object, modified in place component: string, describing where the above definitions are defined, 'core' or 'modules'. See KNOWN_COMPONENTS in utilities.py target_interface: IdlInterface object, modified in place dependency_idl_filenames: Idl filenames which depend on the above definitions. reader: IdlReader object. Returns: A dictionary whose key is component and value is IdlDefinitions object whose dependency is resolved. """ resolved_definitions = {component: definitions} # Sort so order consistent, so can compare output from run to run. for dependency_idl_filename in sorted(dependency_idl_filenames): dependency_definitions = reader.read_idl_file(dependency_idl_filename) dependency_component = idl_filename_to_component( dependency_idl_filename) dependency_interface = next( iter(dependency_definitions.interfaces.values())) transfer_extended_attributes(dependency_interface, dependency_idl_filename) # We need to use different checkdeps here for partial interface and # inheritance. if dependency_interface.is_partial: # Case: dependency_interface is a partial interface of # target_interface. # So, # - A partial interface defined in modules can update # the original interface defined in core. # However, # - A partial interface defined in core cannot update # the original interface defined in modules. if not is_valid_component_dependency(dependency_component, component): raise Exception( 'The partial interface:%s in %s cannot update ' 'the original interface:%s in %s' % (dependency_interface.name, dependency_component, target_interface.name, component)) if dependency_component in resolved_definitions: # When merging a new partial interfaces, should not overwrite # ImpelemntedAs extended attributes in merged partial # interface. # See also the below "if 'ImplementedAs' not in ... " line's # comment. dependency_interface.extended_attributes.pop( 'ImplementedAs', None) resolved_definitions[dependency_component].update( dependency_definitions) continue dependency_interface.extended_attributes.update( target_interface.extended_attributes) assert target_interface == \ definitions.interfaces[dependency_interface.name] # A partial interface should use its original interface's # ImplementedAs. If the original interface doesn't have, # remove ImplementedAs defined in the partial interface. # Because partial interface needs the original interface's # cpp class to obtain partial interface's cpp class. # e.g.. V8WindowPartial.cpp: # DOMWindow* impl = V8Window::ToImpl(holder); # DOMWindowQuota* cpp_value(DOMWindowQuota::webkitStorageInfo(impl)); # TODO(tasak): remove ImplementedAs extended attributes # from all partial interfaces. Instead, rename all cpp/header # files correctly. ImplementedAs should not be allowed in # partial interfaces. if 'ImplementedAs' not in target_interface.extended_attributes: dependency_interface.extended_attributes.pop( 'ImplementedAs', None) dependency_interface.original_interface = target_interface target_interface.partial_interfaces.append(dependency_interface) resolved_definitions[dependency_component] = dependency_definitions else: # Case: |target_interface| includes |dependency_interface| mixin. # So, # - An interface defined in modules can include any interface mixin # defined in core. # However, # - An interface defined in core cannot include an interface mixin # defined in modules. if not dependency_interface.is_mixin: raise Exception( 'The interface:%s cannot include ' 'the non-mixin interface: %s.' % (target_interface.name, dependency_interface.name)) if not is_valid_component_dependency(component, dependency_component): raise Exception( 'The interface:%s in %s cannot include ' 'the interface mixin:%s in %s.' % (target_interface.name, component, dependency_interface.name, dependency_component)) # merges partial interfaces resolved_definitions[component].update(dependency_definitions) # Mixins are also merged into the target interface, so Code # Generator can just iterate over one list (and not need to handle # 'includes' itself). target_interface.merge(dependency_interface) return resolved_definitions def transfer_extended_attributes(dependency_interface, dependency_idl_filename): """Transfer extended attributes from dependency interface onto members. Merging consists of storing certain interface-level data in extended attributes of the *members* (because there is no separate dependency interface post-merging). The data storing consists of: * moving certain extended attributes from the dependency interface to its members (deleting the extended attribute from the interface) * storing the C++ class of the implementation in an internal extended attribute of each member, [PartialInterfaceImplementedAs] No return: modifies dependency_interface in place. """ merged_extended_attributes = {} for key in DEPENDENCY_EXTENDED_ATTRIBUTES: if key not in dependency_interface.extended_attributes: continue merged_extended_attributes[key] = \ dependency_interface.extended_attributes[key] # Remove the merged attributes from the original dependency interface. # This ensures that if other dependency interfaces are merged onto this # one, its extended_attributes do not leak through # (https://crbug.com/603782). del dependency_interface.extended_attributes[key] # A partial interface's members are implemented as static member functions # in a separate C++ class. This class name is stored in # [PartialInterfaceImplementedAs] which is copied from [ImplementedAs] on # the partial interface definition. # # Note that implemented interfaces do *not* need [ImplementedAs], since # they are implemented on the C++ object |impl| itself, just like members of # the main interface definition, so the bindings do not need to know in # which class implemented interfaces are implemented. # # Currently [LegacyTreatAsPartialInterface] can be used to have partial # interface behavior on mixins, but this is being removed as legacy cruft: # http://crbug.com/360435 # # Note that [ImplementedAs] is used with different meanings on interfaces # and members: # for Blink class name and function name (or constant name), respectively. # Thus we do not want to copy this from the interface to the member, but # instead extract it and handle it separately. if dependency_interface.is_partial: if 'ImplementedAs' not in dependency_interface.extended_attributes: raise ValueError('Partial interface in %s must have ImplementedAs.' % dependency_idl_filename) merged_extended_attributes['PartialInterfaceImplementedAs'] = \ dependency_interface.extended_attributes.pop('ImplementedAs') elif 'LegacyTreatAsPartialInterface' in \ dependency_interface.extended_attributes: merged_extended_attributes['PartialInterfaceImplementedAs'] = ( dependency_interface.extended_attributes.pop( 'ImplementedAs', dependency_interface.name)) def update_attributes(attributes, extras): for key, value in extras.items(): if key not in attributes: attributes[key] = value for attribute in dependency_interface.attributes: update_attributes(attribute.extended_attributes, merged_extended_attributes) for constant in dependency_interface.constants: update_attributes(constant.extended_attributes, merged_extended_attributes) for operation in dependency_interface.operations: update_attributes(operation.extended_attributes, merged_extended_attributes) def inherit_unforgeable_attributes(resolved_definitions, interfaces_info): """Inherits [LegacyUnforgeable] attributes and updates the arguments accordingly. For each interface in |resolved_definitions|, collects all [LegacyUnforgeable] attributes in ancestor interfaces and adds them to the interface. 'referenced_interfaces' and 'cpp_includes' in |interfaces_info| are updated accordingly. """ def collect_unforgeable_attributes_in_ancestors(interface_name, component): if not interface_name: # unforgeable_attributes, referenced_interfaces, cpp_includes return [], [], set() interface = interfaces_info[interface_name] unforgeable_attributes, referenced_interfaces, cpp_includes = \ collect_unforgeable_attributes_in_ancestors( interface.get('parent'), component) this_unforgeable = interface.get('unforgeable_attributes', []) for attr in this_unforgeable: if attr.defined_in is None: attr.defined_in = interface_name unforgeable_attributes.extend(this_unforgeable) this_referenced = [ attr.idl_type.base_type for attr in this_unforgeable if attr.idl_type.base_type in interface.get( 'referenced_interfaces', []) ] referenced_interfaces.extend(this_referenced) cpp_includes.update( interface.get('cpp_includes', {}).get(component, {})) return unforgeable_attributes, referenced_interfaces, cpp_includes for component, definitions in resolved_definitions.items(): for interface_name, interface in definitions.interfaces.items(): interface_info = interfaces_info[interface_name] inherited_unforgeable_attributes, referenced_interfaces, cpp_includes = \ collect_unforgeable_attributes_in_ancestors( interface_info.get('parent'), component) # This loop may process the same interface many times, so it's # possible that we're adding the same attributes twice or more. # So check if there is a duplicate. for attr in inherited_unforgeable_attributes: if attr not in interface.attributes: interface.attributes.append(attr) referenced_interfaces.extend( interface_info.get('referenced_interfaces', [])) interface_info['referenced_interfaces'] = sorted( set(referenced_interfaces)) merge_dict_recursively(interface_info, {'cpp_includes': { component: cpp_includes }})
bsd-3-clause
gpaes/apm_planner
libs/mavlink/share/pyshared/pymavlink/generator/gen_all.py
31
1511
#!/usr/bin/env python ''' Use mavgen.py on all available MAVLink XML definitions to generate C and Python MAVLink routines for sending and parsing the protocol Copyright Pete Hollands 2011 Released under GNU GPL version 3 or later ''' import os, sys, glob, re from mavgen import mavgen # allow import from the parent directory, where mavutil.py is sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')) class options: """ a class to simulate the options of mavgen OptionsParser""" def __init__(self, lang, output, wire_protocol): self.language = lang self.wire_protocol = wire_protocol self.output = output protocols = [ '0.9', '1.0' ] for protocol in protocols : xml_directory = './message_definitions/v'+protocol print "xml_directory is", xml_directory xml_file_names = glob.glob(xml_directory+'/*.xml') for xml_file in xml_file_names: print "xml file is ", xml_file opts = options(lang = "C", output = "C/include_v"+protocol, \ wire_protocol=protocol) args = [] args.append(xml_file) mavgen(opts, args) xml_file_base = os.path.basename(xml_file) xml_file_base = re.sub("\.xml","", xml_file_base) print "xml_file_base is", xml_file_base opts = options(lang = "python", \ output="python/mavlink_"+xml_file_base+"_v"+protocol+".py", \ wire_protocol=protocol) mavgen(opts,args)
agpl-3.0
bqlabs/horus
src/horus/gui/workbench/calibration/pages/capture_page.py
2
4180
# -*- coding: utf-8 -*- # This file is part of the Horus Project __author__ = 'Jesús Arroyo Torrens <jesus.arroyo@bq.com>' __copyright__ = 'Copyright (C) 2014-2016 Mundo Reader S.L.' __license__ = 'GNU General Public License v2 http://www.gnu.org/licenses/gpl2.html' import wx._core from horus.util import resources from horus.gui.engine import image_capture, image_detection, camera_intrinsics from horus.gui.workbench.calibration.pages.page import Page from horus.gui.util.image_view import ImageView from horus.gui.util.video_view import VideoView class CapturePage(Page): def __init__(self, parent, start_callback=None): Page.__init__(self, parent, title=_("Camera intrinsics (advanced)"), desc=_("Default values are recommended. To perform the calibration, " "click over the video panel and press " "space bar to perform the captures."), left=_("Reset"), right=_("Start"), button_left_callback=self.initialize, button_right_callback=start_callback, view_progress=True) self.right_button.Hide() # Elements self.video_view = VideoView(self.panel, self.get_image) self.rows, self.columns = 3, 5 self.panel_grid = [] self.current_grid = 0 self.image_grid_panel = wx.Panel(self.panel) self.grid_sizer = wx.GridSizer(self.rows, self.columns, 3, 3) for panel in xrange(self.rows * self.columns): self.panel_grid.append(ImageView(self.image_grid_panel)) self.panel_grid[panel].Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.grid_sizer.Add(self.panel_grid[panel], 0, wx.ALL | wx.EXPAND) self.image_grid_panel.SetSizer(self.grid_sizer) # Layout self.panel_box.Add(self.video_view, 2, wx.ALL | wx.EXPAND, 2) self.panel_box.Add(self.image_grid_panel, 3, wx.ALL | wx.EXPAND, 3) self.Layout() # Events self.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.video_view.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.image_grid_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press) def initialize(self): self.desc_text.SetLabel( _("Default values are recommended. To perform the calibration, " "click over the video panel and press " "space bar to perform the captures.")) self.current_grid = 0 self.gauge.SetValue(0) camera_intrinsics.reset() for panel in xrange(self.rows * self.columns): self.panel_grid[panel].SetBackgroundColour((221, 221, 221)) self.panel_grid[panel].set_image(wx.Image(resources.get_path_for_image("void.png"))) def play(self): self.gauge.SetValue(0) self.video_view.play() self.image_grid_panel.SetFocus() self.GetParent().Layout() self.Layout() def stop(self): self.initialize() self.video_view.stop() def reset(self): self.video_view.reset() def get_image(self): image = image_capture.capture_pattern() chessboard = image_detection.detect_pattern(image) return chessboard def on_key_press(self, event): if event.GetKeyCode() == 32: # spacebar self.video_view.stop() image = camera_intrinsics.capture() if image is not None: self.add_frame_to_grid(image) if self.current_grid <= self.rows * self.columns: self.gauge.SetValue(self.current_grid * 100.0 / self.rows / self.columns) self.video_view.play() def add_frame_to_grid(self, image): if self.current_grid < (self.columns * self.rows): self.panel_grid[self.current_grid].set_frame(image) self.current_grid += 1 if self.current_grid is (self.columns * self.rows): self.desc_text.SetLabel(_("Press space bar to continue")) if self.button_right_callback is not None: self.button_right_callback()
gpl-2.0
ultimateprogramer/formhub
restservice/services/bamboo.py
5
1454
from pybamboo.dataset import Dataset from pybamboo.connection import Connection from restservice.RestServiceInterface import RestServiceInterface from utils.bamboo import get_new_bamboo_dataset, get_bamboo_url class ServiceDefinition(RestServiceInterface): id = u'bamboo' verbose_name = u'bamboo POST' def send(self, url, parsed_instance): xform = parsed_instance.instance.xform rows = [parsed_instance.to_dict_for_mongo()] # prefix meta columns names for bamboo prefix = (u'%(id_string)s_%(id)s' % {'id_string': xform.id_string, 'id': xform.id}) for row in rows: for col, value in row.items(): if col.startswith('_') or col.startswith('meta_') \ or col.startswith('meta/'): new_col = (u'%(prefix)s%(col)s' % {'prefix': prefix, 'col': col}) row.update({new_col: value}) del(row[col]) # create dataset on bamboo first (including current submission) if not xform.bamboo_dataset: dataset_id = get_new_bamboo_dataset(xform, force_last=True) xform.bamboo_dataset = dataset_id xform.save() else: dataset = Dataset(connection=Connection(url=get_bamboo_url(xform)), dataset_id=xform.bamboo_dataset) dataset.update_data(rows=rows)
bsd-2-clause
ruibarreira/linuxtrail
usr/lib/python2.7/dist-packages/defusedxml/sax.py
53
1462
# defusedxml # # Copyright (c) 2013 by Christian Heimes <christian@python.org> # Licensed to PSF under a Contributor Agreement. # See http://www.python.org/psf/license for licensing details. """Defused xml.sax """ from __future__ import print_function, absolute_import from xml.sax import InputSource as _InputSource from xml.sax import ErrorHandler as _ErrorHandler from . import expatreader __origin__ = "xml.sax" def parse(source, handler, errorHandler=_ErrorHandler(), forbid_dtd=False, forbid_entities=True, forbid_external=True): parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) parser.forbid_dtd = forbid_dtd parser.forbid_entities = forbid_entities parser.forbid_external = forbid_external parser.parse(source) def parseString(string, handler, errorHandler=_ErrorHandler(), forbid_dtd=False, forbid_entities=True, forbid_external=True): from io import BytesIO if errorHandler is None: errorHandler = _ErrorHandler() parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) parser.forbid_dtd = forbid_dtd parser.forbid_entities = forbid_entities parser.forbid_external = forbid_external inpsrc = _InputSource() inpsrc.setByteStream(BytesIO(string)) parser.parse(inpsrc) def make_parser(parser_list=[]): return expatreader.create_parser()
gpl-3.0
silly-wacky-3-town-toon/SOURCE-COD
toontown/coghq/DistributedBattleFactoryAI.py
1
2839
from toontown.coghq import DistributedLevelBattleAI from direct.directnotify import DirectNotifyGlobal from direct.fsm import State from direct.fsm import ClassicFSM, State from toontown.battle.BattleBase import * import CogDisguiseGlobals from toontown.toonbase.ToonPythonUtil import addListsByValue class DistributedBattleFactoryAI(DistributedLevelBattleAI.DistributedLevelBattleAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedBattleFactoryAI') def __init__(self, air, battleMgr, pos, suit, toonId, zoneId, level, battleCellId, roundCallback = None, finishCallback = None, maxSuits = 4): DistributedLevelBattleAI.DistributedLevelBattleAI.__init__(self, air, battleMgr, pos, suit, toonId, zoneId, level, battleCellId, 'FactoryReward', roundCallback, finishCallback, maxSuits) self.battleCalc.setSkillCreditMultiplier(1) if self.bossBattle: self.level.d_setForemanConfronted(toonId) self.fsm.addState(State.State('FactoryReward', self.enterFactoryReward, self.exitFactoryReward, ['Resume'])) playMovieState = self.fsm.getStateNamed('PlayMovie') playMovieState.addTransition('FactoryReward') def getTaskZoneId(self): return self.level.factoryId def handleToonsWon(self, toons): for toon in toons: recovered, notRecovered = self.air.questManager.recoverItems(toon, self.suitsKilled, self.getTaskZoneId()) self.toonItems[toon.doId][0].extend(recovered) self.toonItems[toon.doId][1].extend(notRecovered) meritArray = self.air.promotionMgr.recoverMerits(toon, self.suitsKilled, self.getTaskZoneId(), getFactoryMeritMultiplier(self.getTaskZoneId())) if toon.doId in self.helpfulToons: self.toonMerits[toon.doId] = addListsByValue(self.toonMerits[toon.doId], meritArray) else: self.notify.debug('toon %d not helpful, skipping merits' % toon.doId) if self.bossBattle: self.toonParts[toon.doId] = self.air.cogSuitMgr.recoverPart(toon, self.level.factoryType, self.suitTrack, self.getTaskZoneId(), toons) self.notify.debug('toonParts = %s' % self.toonParts) def enterFactoryReward(self): self.joinableFsm.request('Unjoinable') self.runableFsm.request('Unrunable') self.resetResponses() self.assignRewards() self.bossDefeated = 1 self.level.setVictors(self.activeToons[:]) self.timer.startCallback(BUILDING_REWARD_TIMEOUT, self.serverRewardDone) return None def exitFactoryReward(self): return None def enterResume(self): DistributedLevelBattleAI.DistributedLevelBattleAI.enterResume(self) if self.bossBattle and self.bossDefeated: self.battleMgr.level.b_setDefeated()
apache-2.0
paasmaker/paasmaker
paasmaker/common/api/noderegister.py
2
6840
# # Paasmaker - Platform as a Service # # 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/. # import logging import time import paasmaker from apirequest import APIRequest, APIResponse import tornado from pubsub import pub logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) class NodeRegisterAPIRequest(APIRequest): """ This API call is used to register a node. It's intended for internal use only, and you should not call it from your code. """ def async_build_payload(self, payload, callback): # Basic information. # So here's my number... call me maybe? payload['name'] = self.configuration.get_flat('my_name') payload['route'] = self.configuration.get_flat('my_route') payload['apiport'] = self.configuration.get_flat('http_port') payload['start_time'] = self.configuration.start_time # Send along the node tags. tags = {} # The node roles. roles = {} roles['heart'] = self.configuration.is_heart() roles['pacemaker'] = self.configuration.is_pacemaker() roles['router'] = self.configuration.is_router() tags['roles'] = roles # Include node tags. payload['tags'] = tags logger.debug("Sending node tags: %s", str(tags)) # For hearts, send along instance statuses. if self.configuration.is_heart(): statuses = self.configuration.instances.get_instance_list() payload['instances'] = statuses logger.debug("Sending instance states: %s", str(statuses)) # Now delve into and fetch the asynchronous information. def payload_completed(): # Called when all information has been gathered. callback(payload) def got_runtimes(runtimes): # Got the runtimes from the configuration object. tags['runtimes'] = runtimes payload_completed() def start_runtimes(): if self.configuration.is_heart() or self.configuration.is_pacemaker(): self.configuration.get_runtimes(got_runtimes) else: payload_completed() def got_tags(dynamic_tags): tags['node'] = dynamic_tags start_runtimes() def start_tags(): self.configuration.get_dynamic_tags(got_tags) def got_stats(stats): payload['stats'] = stats payload['score'] = self.configuration.get_node_score(payload['stats']) start_tags() # Kick off the chain. self.configuration.get_node_stats(got_stats) def get_endpoint(self): return '/node/register?bypass_ssl=true' def process_response(self, response): """ This overriden process_response() function stores the nodes new UUID into our configuration. """ if response.success: # Save our nodes UUID. self.configuration.set_node_uuid(response.data['node']['uuid']) else: logger.error("Unable to register with master!") for error in response.errors: logger.error(error) class NodeUpdateAPIRequest(NodeRegisterAPIRequest): """ Update our node record on the master. This is a subclass of the NodeRegisterAPIRequest that sends along the existing UUID. """ def async_build_payload(self, payload, callback): def completed_parent_payload(parent_payload): payload['uuid'] = self.configuration.get_node_uuid() callback(payload) super(NodeUpdateAPIRequest, self).async_build_payload(payload, completed_parent_payload) def get_endpoint(self): return '/node/update?bypass_ssl=true' class NodeShutdownAPIRequest(NodeUpdateAPIRequest): """ Notify the master that we're shutting down, and allow it to take the appropriate shutdown actions. """ def get_endpoint(self): return '/node/shutdown?bypass_ssl=true' class NodeUpdatePeriodicManager(object): """ A class to periodically contact the master node and let that node know that we're still alive, and update it on anything that it might have missed. """ def __init__(self, configuration): self.configuration = configuration # Create the periodic handler. self.periodic = tornado.ioloop.PeriodicCallback( self._node_report_in, configuration.get_flat('node_report_interval'), io_loop=configuration.io_loop ) # Flag to store if the periodic has started. self.started = False # Flag to indicate that it's currently reporting to the master. self.reporting = False # Flag to indicate that it should attempt to report in again # immediately once it's done this report (because there is newer data). self.followreport = False # Flag to indicate if this is the first registration for this # node (since server startup - not the first time ever). self.firstregister = True # Report in now. self.trigger() def trigger(self): """ Trigger off a report to the master. If a report is already in progress, records that one must occur as soon as this one finishes. """ if self.reporting: # Already reporting, indicate that it should follow # this report with another one immediately. self.followreport = True else: # Trigger the update now. self._node_report_in() def stop(self): """ Stop periodically calling back to the master. Generally only used before shutting down the node. """ self.periodic.stop() self.started = False def _node_report_in(self): # Register the node with the server. self.reporting = True # Reset the follow flag. self.followreport = False # Determine the type and make the request. if self.configuration.get_node_uuid(): request = paasmaker.common.api.NodeUpdateAPIRequest(self.configuration) request.send(self._on_registration_complete) else: request = paasmaker.common.api.NodeRegisterAPIRequest(self.configuration) request.send(self._on_registration_complete) def _on_registration_complete(self, response): # Start up the periodic if it's not already been done. if not self.started: self.started = True self.periodic.start() # Determine what happened. if not response.success or len(response.errors) > 0: logger.error("Unable to register with the master node.") for error in response.errors: logger.error(error) # TODO: This relies on an internal variable, but saves us having # to recreate the periodic. logger.info("Waiting for 5 seconds and then we'll try again.") self.periodic.callback_time = 5000 self.periodic.stop() self.periodic.start() pub.sendMessage('node.registrationerror') else: logger.info("Successfully registered or updated with master.") # Reset the callback time. self.periodic.callback_time = self.configuration.get_flat('node_report_interval') self.periodic.stop() self.periodic.start() if self.firstregister: self.firstregister = False pub.sendMessage('node.firstregistration') else: pub.sendMessage('node.registrationupdate') self.reporting = False if self.followreport: # Go again! self.trigger()
mpl-2.0
tvalacarta/tvalacarta
python/main-classic/servers/eitb.py
2
1215
# -*- coding: utf-8 -*- #------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para eitb # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ #------------------------------------------------------------ from core import logger from core import scrapertools from lib import youtube_dl def get_video_url( page_url , premium = False , user="" , password="", video_password="", page_data="" ): logger.info("[eitb.py] get_video_url(page_url='%s')" % page_url) ydl = youtube_dl.YoutubeDL({'outtmpl': u'%(id)s%(ext)s'}) result = ydl.extract_info(page_url, download=False) video_urls = [] if 'formats' in result: for entry in result['formats']: logger.info("entry="+repr(entry)) if 'http' in entry['format']: video_urls.append([scrapertools.safe_unicode(entry['format']).encode('utf-8'), scrapertools.safe_unicode(entry['url']).encode('utf-8')]) #logger.info('Append: {}'.format(entry['url'])) video_urls.reverse() return video_urls # Encuentra vídeos del servidor en el texto pasado def find_videos(data): encontrados = set() devuelve = [] return devuelve
gpl-3.0
arista-eosplus/ansible-modules-extras
system/zfs.py
67
14130
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Johan Wiren <johan.wiren.se@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/>. # DOCUMENTATION = ''' --- module: zfs short_description: Manage zfs description: - Manages ZFS file systems on Solaris and FreeBSD. Can manage file systems, volumes and snapshots. See zfs(1M) for more information about the properties. version_added: "1.1" options: name: description: - File system, snapshot or volume name e.g. C(rpool/myfs) required: true state: description: - Whether to create (C(present)), or remove (C(absent)) a file system, snapshot or volume. required: true choices: [present, absent] aclinherit: description: - The aclinherit property. required: False choices: [discard,noallow,restricted,passthrough,passthrough-x] aclmode: description: - The aclmode property. required: False choices: [discard,groupmask,passthrough] atime: description: - The atime property. required: False choices: ['on','off'] canmount: description: - The canmount property. required: False choices: ['on','off','noauto'] casesensitivity: description: - The casesensitivity property. required: False choices: [sensitive,insensitive,mixed] checksum: description: - The checksum property. required: False choices: ['on','off',fletcher2,fletcher4,sha256] compression: description: - The compression property. required: False choices: ['on','off',lzjb,gzip,gzip-1,gzip-2,gzip-3,gzip-4,gzip-5,gzip-6,gzip-7,gzip-8,gzip-9,lz4,zle] copies: description: - The copies property. required: False choices: [1,2,3] dedup: description: - The dedup property. required: False choices: ['on','off'] devices: description: - The devices property. required: False choices: ['on','off'] exec: description: - The exec property. required: False choices: ['on','off'] jailed: description: - The jailed property. required: False choices: ['on','off'] logbias: description: - The logbias property. required: False choices: [latency,throughput] mountpoint: description: - The mountpoint property. required: False nbmand: description: - The nbmand property. required: False choices: ['on','off'] normalization: description: - The normalization property. required: False choices: [none,formC,formD,formKC,formKD] origin: description: - Name of the snapshot to clone required: False version_added: "2.0" primarycache: description: - The primarycache property. required: False choices: [all,none,metadata] quota: description: - The quota property. required: False readonly: description: - The readonly property. required: False choices: ['on','off'] recordsize: description: - The recordsize property. required: False refquota: description: - The refquota property. required: False refreservation: description: - The refreservation property. required: False reservation: description: - The reservation property. required: False secondarycache: description: - The secondarycache property. required: False choices: [all,none,metadata] setuid: description: - The setuid property. required: False choices: ['on','off'] shareiscsi: description: - The shareiscsi property. required: False choices: ['on','off'] sharenfs: description: - The sharenfs property. required: False sharesmb: description: - The sharesmb property. required: False snapdir: description: - The snapdir property. required: False choices: [hidden,visible] sync: description: - The sync property. required: False choices: ['standard','always','disabled'] utf8only: description: - The utf8only property. required: False choices: ['on','off'] volsize: description: - The volsize property. required: False volblocksize: description: - The volblocksize property. required: False vscan: description: - The vscan property. required: False choices: ['on','off'] xattr: description: - The xattr property. required: False choices: ['on','off'] zoned: description: - The zoned property. required: False choices: ['on','off'] author: "Johan Wiren (@johanwiren)" ''' EXAMPLES = ''' # Create a new file system called myfs in pool rpool - zfs: name=rpool/myfs state=present # Create a new volume called myvol in pool rpool. - zfs: name=rpool/myvol state=present volsize=10M # Create a snapshot of rpool/myfs file system. - zfs: name=rpool/myfs@mysnapshot state=present # Create a new file system called myfs2 with snapdir enabled - zfs: name=rpool/myfs2 state=present snapdir=enabled # Create a new file system by cloning a snapshot - zfs: name=rpool/cloned_fs state=present origin=rpool/myfs@mysnapshot # Destroy a filesystem - zfs: name=rpool/myfs state=absent ''' import os class Zfs(object): def __init__(self, module, name, properties): self.module = module self.name = name self.properties = properties self.changed = False self.immutable_properties = [ 'casesensitivity', 'normalization', 'utf8only' ] def exists(self): cmd = [self.module.get_bin_path('zfs', True)] cmd.append('list') cmd.append('-t all') cmd.append(self.name) (rc, out, err) = self.module.run_command(' '.join(cmd)) if rc == 0: return True else: return False def create(self): if self.module.check_mode: self.changed = True return properties = self.properties volsize = properties.pop('volsize', None) volblocksize = properties.pop('volblocksize', None) origin = properties.pop('origin', None) if "@" in self.name: action = 'snapshot' elif origin: action = 'clone' else: action = 'create' cmd = [self.module.get_bin_path('zfs', True)] cmd.append(action) if createparent: cmd.append('-p') if volblocksize: cmd.append('-b %s' % volblocksize) if properties: for prop, value in properties.iteritems(): cmd.append('-o %s="%s"' % (prop, value)) if volsize: cmd.append('-V') cmd.append(volsize) if origin: cmd.append(origin) cmd.append(self.name) (rc, err, out) = self.module.run_command(' '.join(cmd)) if rc == 0: self.changed = True else: self.module.fail_json(msg=out) def destroy(self): if self.module.check_mode: self.changed = True return cmd = [self.module.get_bin_path('zfs', True)] cmd.append('destroy') cmd.append(self.name) (rc, err, out) = self.module.run_command(' '.join(cmd)) if rc == 0: self.changed = True else: self.module.fail_json(msg=out) def set_property(self, prop, value): if self.module.check_mode: self.changed = True return cmd = self.module.get_bin_path('zfs', True) args = [cmd, 'set', prop + '=' + value, self.name] (rc, err, out) = self.module.run_command(args) if rc == 0: self.changed = True else: self.module.fail_json(msg=out) def set_properties_if_changed(self): current_properties = self.get_current_properties() for prop, value in self.properties.iteritems(): if current_properties[prop] != value: if prop in self.immutable_properties: self.module.fail_json(msg='Cannot change property %s after creation.' % prop) else: self.set_property(prop, value) def get_current_properties(self): def get_properties_by_name(propname): cmd = [self.module.get_bin_path('zfs', True)] cmd += ['get', '-H', propname, self.name] rc, out, err = self.module.run_command(cmd) return [l.split('\t')[1:3] for l in out.splitlines()] properties = dict(get_properties_by_name('all')) if 'share.*' in properties: # Some ZFS pools list the sharenfs and sharesmb properties # hierarchically as share.nfs and share.smb respectively. del properties['share.*'] for p, v in get_properties_by_name('share.all'): alias = p.replace('.', '') # share.nfs -> sharenfs (etc) properties[alias] = v return properties def run_command(self, cmd): progname = cmd[0] cmd[0] = module.get_bin_path(progname, True) return module.run_command(cmd) def main(): # FIXME: should use dict() constructor like other modules, required=False is default module = AnsibleModule( argument_spec = { 'name': {'required': True}, 'state': {'required': True, 'choices':['present', 'absent']}, 'aclinherit': {'required': False, 'choices':['discard', 'noallow', 'restricted', 'passthrough', 'passthrough-x']}, 'aclmode': {'required': False, 'choices':['discard', 'groupmask', 'passthrough']}, 'atime': {'required': False, 'choices':['on', 'off']}, 'canmount': {'required': False, 'choices':['on', 'off', 'noauto']}, 'casesensitivity': {'required': False, 'choices':['sensitive', 'insensitive', 'mixed']}, 'checksum': {'required': False, 'choices':['on', 'off', 'fletcher2', 'fletcher4', 'sha256']}, 'compression': {'required': False, 'choices':['on', 'off', 'lzjb', 'gzip', 'gzip-1', 'gzip-2', 'gzip-3', 'gzip-4', 'gzip-5', 'gzip-6', 'gzip-7', 'gzip-8', 'gzip-9', 'lz4', 'zle']}, 'copies': {'required': False, 'choices':['1', '2', '3']}, 'createparent': {'required': False, 'choices':['on', 'off']}, 'dedup': {'required': False, 'choices':['on', 'off']}, 'devices': {'required': False, 'choices':['on', 'off']}, 'exec': {'required': False, 'choices':['on', 'off']}, # Not supported #'groupquota': {'required': False}, 'jailed': {'required': False, 'choices':['on', 'off']}, 'logbias': {'required': False, 'choices':['latency', 'throughput']}, 'mountpoint': {'required': False}, 'nbmand': {'required': False, 'choices':['on', 'off']}, 'normalization': {'required': False, 'choices':['none', 'formC', 'formD', 'formKC', 'formKD']}, 'origin': {'required': False}, 'primarycache': {'required': False, 'choices':['all', 'none', 'metadata']}, 'quota': {'required': False}, 'readonly': {'required': False, 'choices':['on', 'off']}, 'recordsize': {'required': False}, 'refquota': {'required': False}, 'refreservation': {'required': False}, 'reservation': {'required': False}, 'secondarycache': {'required': False, 'choices':['all', 'none', 'metadata']}, 'setuid': {'required': False, 'choices':['on', 'off']}, 'shareiscsi': {'required': False, 'choices':['on', 'off']}, 'sharenfs': {'required': False}, 'sharesmb': {'required': False}, 'snapdir': {'required': False, 'choices':['hidden', 'visible']}, 'sync': {'required': False, 'choices':['standard', 'always', 'disabled']}, # Not supported #'userquota': {'required': False}, 'utf8only': {'required': False, 'choices':['on', 'off']}, 'volsize': {'required': False}, 'volblocksize': {'required': False}, 'vscan': {'required': False, 'choices':['on', 'off']}, 'xattr': {'required': False, 'choices':['on', 'off']}, 'zoned': {'required': False, 'choices':['on', 'off']}, }, supports_check_mode=True ) state = module.params.pop('state') name = module.params.pop('name') # Get all valid zfs-properties properties = dict() for prop, value in module.params.iteritems(): if prop in ['CHECKMODE']: continue if value: properties[prop] = value result = {} result['name'] = name result['state'] = state zfs = Zfs(module, name, properties) if state == 'present': if zfs.exists(): zfs.set_properties_if_changed() else: zfs.create() elif state == 'absent': if zfs.exists(): zfs.destroy() result.update(zfs.properties) result['changed'] = zfs.changed module.exit_json(**result) # import module snippets from ansible.module_utils.basic import * main()
gpl-3.0
SimonTheCoder/server_monitor
wmonitor.py
1
2078
#!/usr/bin/python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk from monitor import Monitor import threading def refresh_host(server_list_file = None): if server_list_file is None: server_list_file = "servers.list" list_store = builder.get_object("host_ListStore") list_store.clear() #list_store.append([True,"a","1.1.1.1",3.14159]) list_store.append([False,"refresh ...","",0]) #window.queue_draw() file_chooser = builder.get_object("server_list_file_chooser") server_list_file = file_chooser.get_filename() if server_list_file is None: server_list_file = "server.list" file_chooser.set_filename(server_list_file) print "chooser: " + server_list_file m = Monitor(server_list_file) print "%d servers in list." % len(m.server_list) results = m.check_all() list_store.clear() for i in results: list_store.append([i.state == i.SERVER_STATE_UP,i.host,i.ip,i.time]) print(len(list_store)) class Handler: def onButtonClick(self, button): print "refresh clicked." #Gtk.main_quit() list_store = builder.get_object("host_ListStore") list_store.clear() list_store.append([False,"refresh ...","",0]) refresh_thread = threading.Thread(target = refresh_host) refresh_thread.setDaemon(True) refresh_thread.start() def onCopy1stIP(self, button): print "copy to clipboard." clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) list_store = builder.get_object("host_ListStore") clipboard.set_text(list_store[0][2], -1) def onDeleteWindow(self, *args): Gtk.main_quit(*args) def onIpEdited(self,arg1, arg2, arg3): print "ip clicked" def onServerFileChoosed(self, *args): print "file choosed" builder = Gtk.Builder() builder.add_from_file("monitor_ui.glade") builder.connect_signals(Handler()) window = builder.get_object("main_window") #window = builder.get_object("window2") window.show_all() Gtk.main()
gpl-2.0
vipints/genomeutils
gfftools/GFFParser.py
1
20125
#!/usr/bin/env python """ Extract genome annotation from a GFF (a tab delimited format for storing sequence features and annotations) file. Requirements: Numpy :- http://numpy.org/ Copyright (C) 2009-2012 Friedrich Miescher Laboratory of the Max Planck Society, Tubingen, Germany. 2012-2015 Memorial Sloan Kettering Cancer Center, New York City, USA. """ import re import os import sys import urllib import numpy as np import helper as utils from collections import defaultdict def attribute_tags(col9): """ Split the key-value tags from the attribute column, it takes column number 9 from GTF/GFF file @args col9: attribute column from GFF file @type col9: str """ info = defaultdict(list) is_gff = False if not col9: return is_gff, info # trim the line ending semi-colon ucsc may have some white-space col9 = col9.rstrip(';| ') # attributes from 9th column atbs = col9.split(" ; ") if len(atbs) == 1: atbs = col9.split("; ") if len(atbs) == 1: atbs = col9.split(";") # check the GFF3 pattern which has key value pairs like: gff3_pat = re.compile("\w+=") # sometime GTF have: gene_id uc002zkg.1; gtf_pat = re.compile("\s?\w+\s") key_vals = [] if gff3_pat.match(atbs[0]): # gff3 pattern is_gff = True key_vals = [at.split('=') for at in atbs] elif gtf_pat.match(atbs[0]): # gtf pattern for at in atbs: key_vals.append(at.strip().split(" ",1)) else: # to handle attribute column has only single value key_vals.append(['ID', atbs[0]]) # get key, val items for item in key_vals: key, val = item # replace the double qoutes from feature identifier val = re.sub('"', '', val) # replace the web formating place holders to plain text format info[key].extend([urllib.unquote(v) for v in val.split(',') if v]) return is_gff, info def spec_features_keywd(gff_parts): """ Specify the feature key word according to the GFF specifications @args gff_parts: attribute field key @type gff_parts: str """ for t_id in ["transcript_id", "transcriptId", "proteinId"]: try: gff_parts["info"]["Parent"] = gff_parts["info"][t_id] break except KeyError: pass for g_id in ["gene_id", "geneid", "geneId", "name", "gene_name", "genename"]: try: gff_parts["info"]["GParent"] = gff_parts["info"][g_id] break except KeyError: pass ## TODO key words for flat_name in ["Transcript", "CDS"]: if gff_parts["info"].has_key(flat_name): # parents if gff_parts['type'] in [flat_name] or re.search(r'transcript', gff_parts['type'], re.IGNORECASE): if not gff_parts['id']: gff_parts['id'] = gff_parts['info'][flat_name][0] #gff_parts["info"]["ID"] = [gff_parts["id"]] # children elif gff_parts["type"] in ["intron", "exon", "three_prime_UTR", "coding_exon", "five_prime_UTR", "CDS", "stop_codon", "start_codon"]: gff_parts["info"]["Parent"] = gff_parts["info"][flat_name] break return gff_parts def Parse(ga_file): """ Parsing GFF/GTF file based on feature relationship, it takes the input file. @args ga_file: input file name @type ga_file: str """ child_map = defaultdict(list) parent_map = dict() ga_handle = utils.open_file(ga_file) for rec in ga_handle: rec = rec.strip('\n\r') # skip empty line fasta identifier and commented line if not rec or rec[0] in ['#', '>']: continue # skip the genome sequence if not re.search('\t', rec): continue parts = rec.split('\t') assert len(parts) >= 8, rec # process the attribute column (9th column) ftype, tags = attribute_tags(parts[-1]) if not tags: # skip the line if no attribute column. continue # extract fields if parts[1]: tags["source"] = parts[1] if parts[7]: tags["phase"] = parts[7] gff_info = dict() gff_info['info'] = dict(tags) gff_info["is_gff3"] = ftype gff_info['chr'] = parts[0] gff_info['score'] = parts[5] if parts[3] and parts[4]: gff_info['location'] = [int(parts[3]) , int(parts[4])] gff_info['type'] = parts[2] gff_info['id'] = tags.get('ID', [''])[0] if parts[6] in ['?', '.']: parts[6] = None gff_info['strand'] = parts[6] # key word according to the GFF spec. if not ftype: gff_info = spec_features_keywd(gff_info) # link the feature relationships if gff_info['info'].has_key('Parent'): for p in gff_info['info']['Parent']: if p == gff_info['id']: gff_info['id'] = '' break rec_category = 'child' elif gff_info['id']: rec_category = 'parent' else: rec_category = 'record' # depends on the record category organize the features if rec_category == 'child': for p in gff_info['info']['Parent']: # create the data structure based on source and feature id child_map[(gff_info['chr'], gff_info['info']['source'], p)].append( dict( type = gff_info['type'], location = gff_info['location'], strand = gff_info['strand'], score = gff_info['score'], ID = gff_info['id'], gene_id = gff_info['info'].get('GParent', ''), read_cov = gff_info['info'].get('cov', '') )) elif rec_category == 'parent': parent_map[(gff_info['chr'], gff_info['info']['source'], gff_info['id'])] = dict( type = gff_info['type'], location = gff_info['location'], strand = gff_info['strand'], score = gff_info['score'], read_cov = gff_info['info'].get('cov', ''), name = tags.get('Name', [''])[0]) elif rec_category == 'record': #TODO how to handle plain records? considering_soon = 1 ga_handle.close() # depends on file type create parent feature if not ftype: parent_map, child_map = create_missing_feature_type(parent_map, child_map) # connecting parent child relations gene_mat = format_gene_models(parent_map, child_map) return gene_mat def format_gene_models(parent_nf_map, child_nf_map): """ Genarate GeneObject based on the parsed file contents @args parent_nf_map: parent features with source and chromosome information @type parent_nf_map: collections defaultdict @args child_nf_map: transctipt and exon information are encoded @type child_nf_map: collections defaultdict """ g_cnt = 0 gene = np.zeros((len(parent_nf_map),), dtype = utils.init_gene()) for pkey, pdet in parent_nf_map.items(): # considering only gene features #if not re.search(r'gene', pdet.get('type', '')): # continue # infer the gene start and stop if not there in the if not pdet.get('location', []): GNS, GNE = [], [] # multiple number of transcripts for L1 in child_nf_map[pkey]: GNS.append(L1.get('location', [])[0]) GNE.append(L1.get('location', [])[1]) GNS.sort() GNE.sort() pdet['location'] = [GNS[0], GNE[-1]] orient = pdet.get('strand', '') gene[g_cnt]['id'] = g_cnt +1 gene[g_cnt]['chr'] = pkey[0] gene[g_cnt]['source'] = pkey[1] gene[g_cnt]['name'] = pkey[-1] gene[g_cnt]['start'] = pdet.get('location', [])[0] gene[g_cnt]['stop'] = pdet.get('location', [])[1] gene[g_cnt]['strand'] = orient gene[g_cnt]['score'] = pdet.get('score','') # default value gene[g_cnt]['is_alt_spliced'] = gene[g_cnt]['is_alt'] = 0 if len(child_nf_map[pkey]) > 1: gene[g_cnt]['is_alt_spliced'] = gene[g_cnt]['is_alt'] = 1 # complete sub-feature for all transcripts dim = len(child_nf_map[pkey]) TRS = np.zeros((dim,), dtype=np.object) TR_TYP = np.zeros((dim,), dtype=np.object) EXON = np.zeros((dim,), dtype=np.object) UTR5 = np.zeros((dim,), dtype=np.object) UTR3 = np.zeros((dim,), dtype=np.object) CDS = np.zeros((dim,), dtype=np.object) TISc = np.zeros((dim,), dtype=np.object) TSSc = np.zeros((dim,), dtype=np.object) CLV = np.zeros((dim,), dtype=np.object) CSTOP = np.zeros((dim,), dtype=np.object) TSTAT = np.zeros((dim,), dtype=np.object) TRINFO = np.zeros((dim,), dtype=np.object) # fetching corresponding transcripts for xq, Lv1 in enumerate(child_nf_map[pkey]): TID = Lv1.get('ID', '') TRS[xq]= np.array([TID]) TYPE = Lv1.get('type', '') TR_TYP[xq] = np.array('') TR_TYP[xq] = np.array(TYPE) if TYPE else TR_TYP[xq] orient = Lv1.get('strand', '') # fetching different sub-features child_feat = defaultdict(list) for Lv2 in child_nf_map[(pkey[0], pkey[1], TID)]: E_TYP = Lv2.get('type', '') child_feat[E_TYP].append(Lv2.get('location')) # make general ascending order of coordinates if orient == '-': for etype, excod in child_feat.items(): if len(excod) > 1: if excod[0][0] > excod[-1][0]: excod.reverse() child_feat[etype] = excod # make exon coordinate from cds and utr regions if not child_feat.get('exon'): if child_feat.get('CDS'): exon_cod = utils.make_Exon_cod( orient, NonetoemptyList(child_feat.get('five_prime_UTR')), NonetoemptyList(child_feat.get('CDS')), NonetoemptyList(child_feat.get('three_prime_UTR'))) child_feat['exon'] = exon_cod else: # TODO only UTR's # searching through keys to find a pattern describing exon feature ex_key_pattern = [k for k in child_feat if k.endswith("exon")] if ex_key_pattern: child_feat['exon'] = child_feat[ex_key_pattern[0]] # stop_codon are seperated from CDS, add the coordinates based on strand if child_feat.get('stop_codon'): if orient == '+': if child_feat.get('stop_codon')[0][0] - child_feat.get('CDS')[-1][1] == 1: child_feat['CDS'][-1] = [child_feat.get('CDS')[-1][0], child_feat.get('stop_codon')[0][1]] else: child_feat['CDS'].append(child_feat.get('stop_codon')[0]) elif orient == '-': if child_feat.get('CDS')[0][0] - child_feat.get('stop_codon')[0][1] == 1: child_feat['CDS'][0] = [child_feat.get('stop_codon')[0][0], child_feat.get('CDS')[0][1]] else: child_feat['CDS'].insert(0, child_feat.get('stop_codon')[0]) # transcript signal sites TIS, cdsStop, TSS, cleave = [], [], [], [] cds_status, exon_status, utr_status = 0, 0, 0 if child_feat.get('exon'): TSS = [child_feat.get('exon')[-1][1]] TSS = [child_feat.get('exon')[0][0]] if orient == '+' else TSS cleave = [child_feat.get('exon')[0][0]] cleave = [child_feat.get('exon')[-1][1]] if orient == '+' else cleave exon_status = 1 if child_feat.get('CDS'): if orient == '+': TIS = [child_feat.get('CDS')[0][0]] cdsStop = [child_feat.get('CDS')[-1][1]-3] else: TIS = [child_feat.get('CDS')[-1][1]] cdsStop = [child_feat.get('CDS')[0][0]+3] cds_status = 1 # cds phase calculation child_feat['CDS'] = utils.add_CDS_phase(orient, child_feat.get('CDS')) # sub-feature status if child_feat.get('three_prime_UTR') or child_feat.get('five_prime_UTR'): utr_status =1 if utr_status == cds_status == exon_status == 1: t_status = 1 else: t_status = 0 # add sub-feature # make array for export to different out TSTAT[xq] = t_status EXON[xq] = np.array(child_feat.get('exon'), np.float64) UTR5[xq] = np.array(NonetoemptyList(child_feat.get('five_prime_UTR'))) UTR3[xq] = np.array(NonetoemptyList(child_feat.get('three_prime_UTR'))) CDS[xq] = np.array(NonetoemptyList(child_feat.get('CDS'))) TISc[xq] = np.array(TIS) CSTOP[xq] = np.array(cdsStop) TSSc[xq] = np.array(TSS) CLV[xq] = np.array(cleave) if Lv1.get('cov', ''): TRINFO[xq] = np.array(Lv1.get('cov', '')) ## including the transcript read coverage # add sub-features to the parent gene feature gene[g_cnt]['transcript_status'] = TSTAT gene[g_cnt]['transcripts'] = TRS gene[g_cnt]['exons'] = EXON gene[g_cnt]['utr5_exons'] = UTR5 gene[g_cnt]['cds_exons'] = CDS gene[g_cnt]['utr3_exons'] = UTR3 gene[g_cnt]['transcript_type'] = TR_TYP gene[g_cnt]['tis'] = TISc gene[g_cnt]['cdsStop'] = CSTOP gene[g_cnt]['tss'] = TSSc gene[g_cnt]['cleave'] = CLV gene[g_cnt]['transcript_info'] = TRINFO gene[g_cnt]['gene_info'] = dict( ID = pkey[-1], Name = pdet.get('name'), Source = pkey[1], ) # few empty fields // TODO fill this: gene[g_cnt]['anno_id'] = [] gene[g_cnt]['confgenes_id'] = [] gene[g_cnt]['alias'] = '' gene[g_cnt]['name2'] = [] gene[g_cnt]['chr_num'] = [] gene[g_cnt]['paralogs'] = [] gene[g_cnt]['transcript_valid'] = [] gene[g_cnt]['exons_confirmed'] = [] gene[g_cnt]['tis_conf'] = [] gene[g_cnt]['tis_info'] = [] gene[g_cnt]['cdsStop_conf'] = [] gene[g_cnt]['cdsStop_info'] = [] gene[g_cnt]['tss_info'] = [] gene[g_cnt]['tss_conf'] = [] gene[g_cnt]['cleave_info'] = [] gene[g_cnt]['cleave_conf'] = [] gene[g_cnt]['polya_info'] = [] gene[g_cnt]['polya_conf'] = [] gene[g_cnt]['is_valid'] = [] gene[g_cnt]['transcript_complete'] = [] gene[g_cnt]['is_complete'] = [] gene[g_cnt]['is_correctly_gff3_referenced'] = '' gene[g_cnt]['splicegraph'] = [] g_cnt += 1 ## deleting empty gene records from the main array XPFLG=0 for XP, ens in enumerate(gene): if ens[0]==0: XPFLG=1 break if XPFLG==1: XQC = range(XP, len(gene)+1) gene = np.delete(gene, XQC) return gene def NonetoemptyList(XS): """ Convert a None type to empty list @args XS: None type @type XS: str """ return [] if XS is None else XS def create_missing_feature_type(p_feat, c_feat): """ GFF/GTF file defines only child features. This function tries to create the parent feature from the information provided in the attribute column. example: chr21 hg19_knownGene exon 9690071 9690100 0.000000 + . gene_id "uc002zkg.1"; transcript_id "uc002zkg.1"; chr21 hg19_knownGene exon 9692178 9692207 0.000000 + . gene_id "uc021wgt.1"; transcript_id "uc021wgt.1"; chr21 hg19_knownGene exon 9711935 9712038 0.000000 + . gene_id "uc011abu.2"; transcript_id "uc011abu.2"; This function gets the parsed feature annotations. @args p_feat: Parent feature map @type p_feat: collections defaultdict @args c_feat: Child feature map @type c_feat: collections defaultdict """ child_n_map = defaultdict(list) for fid, det in c_feat.items(): # get the details from grand child GID = STRD = SCR = None SPOS, EPOS = [], [] TYP = dict() for gchild in det: GID = gchild.get('gene_id', [''])[0] SPOS.append(gchild.get('location', [])[0]) EPOS.append(gchild.get('location', [])[1]) STRD = gchild.get('strand', '') SCR = gchild.get('score', '') read_cov = None try: read_cov = gchild.get('read_cov', '')[0] ## read coverage to the transcript except: pass if gchild.get('type', '') == "gene": ## gencode GTF file has this problem continue TYP[gchild.get('type', '')] = 1 SPOS.sort() EPOS.sort() # infer transcript type transcript_type = 'transcript' transcript_type = 'mRNA' if TYP.get('CDS', '') or TYP.get('cds', '') else transcript_type # gene id and transcript id are same transcript_id = fid[-1] if GID == transcript_id: transcript_id = 'Transcript:' + str(GID) # level -1 feature type p_feat[(fid[0], fid[1], GID)] = dict( type = 'gene', location = [], ## infer location based on multiple transcripts strand = STRD, name = GID ) # level -2 feature type child_n_map[(fid[0], fid[1], GID)].append( dict( type = transcript_type, location = [SPOS[0], EPOS[-1]], strand = STRD, score = SCR, ID = transcript_id, cov = read_cov, gene_id = '' )) # reorganizing the grand child for gchild in det: child_n_map[(fid[0], fid[1], transcript_id)].append( dict( type = gchild.get('type', ''), location = gchild.get('location'), strand = gchild.get('strand'), ID = gchild.get('ID'), score = gchild.get('score'), gene_id = '' )) return p_feat, child_n_map
bsd-3-clause
wileeam/airflow
tests/utils/test_operator_helpers.py
4
3285
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import unittest from datetime import datetime from unittest import mock from airflow.utils import operator_helpers class TestOperatorHelpers(unittest.TestCase): def setUp(self): super().setUp() self.dag_id = 'dag_id' self.task_id = 'task_id' self.execution_date = '2017-05-21T00:00:00' self.dag_run_id = 'dag_run_id' self.owner = ['owner1', 'owner2'] self.email = ['email1@test.com'] self.context = { 'dag_run': mock.MagicMock( name='dag_run', run_id=self.dag_run_id, execution_date=datetime.strptime(self.execution_date, '%Y-%m-%dT%H:%M:%S'), ), 'task_instance': mock.MagicMock( name='task_instance', task_id=self.task_id, dag_id=self.dag_id, execution_date=datetime.strptime(self.execution_date, '%Y-%m-%dT%H:%M:%S'), ), 'task': mock.MagicMock( name='task', owner=self.owner, email=self.email ) } def test_context_to_airflow_vars_empty_context(self): self.assertDictEqual(operator_helpers.context_to_airflow_vars({}), {}) def test_context_to_airflow_vars_all_context(self): self.assertDictEqual( operator_helpers.context_to_airflow_vars(self.context), { 'airflow.ctx.dag_id': self.dag_id, 'airflow.ctx.execution_date': self.execution_date, 'airflow.ctx.task_id': self.task_id, 'airflow.ctx.dag_run_id': self.dag_run_id, 'airflow.ctx.dag_owner': 'owner1,owner2', 'airflow.ctx.dag_email': 'email1@test.com' } ) self.assertDictEqual( operator_helpers.context_to_airflow_vars(self.context, in_env_var_format=True), { 'AIRFLOW_CTX_DAG_ID': self.dag_id, 'AIRFLOW_CTX_EXECUTION_DATE': self.execution_date, 'AIRFLOW_CTX_TASK_ID': self.task_id, 'AIRFLOW_CTX_DAG_RUN_ID': self.dag_run_id, 'AIRFLOW_CTX_DAG_OWNER': 'owner1,owner2', 'AIRFLOW_CTX_DAG_EMAIL': 'email1@test.com' } ) if __name__ == '__main__': unittest.main()
apache-2.0
ronkyo/mi-instrument
mi/instrument/wetlabs/fluorometer/flord_d/test/sample_data.py
9
1311
from mi.instrument.wetlabs.fluorometer.flort_d.driver import NEWLINE SAMPLE_MNU_RESPONSE = "Ser BBFL2W-993" + NEWLINE + \ "Ver Triplet5.20" + NEWLINE + \ "Ave 1" + NEWLINE + \ "Pkt 0" + NEWLINE + \ "M1d 0" + NEWLINE + \ "M2d 0" + NEWLINE + \ "M1s 1.000E+00" + NEWLINE + \ "M2s 1.000E+00" + NEWLINE + \ "Seq 0" + NEWLINE + \ "Rat 19200" + NEWLINE + \ "Set 0" + NEWLINE + \ "Rec 1" + NEWLINE + \ "Man 0" + NEWLINE + \ "Int 00:00:10" + NEWLINE + \ "Dat 07/11/13" + NEWLINE + \ "Clk 12:48:34" + NEWLINE + \ "Mst 12:48:31" + NEWLINE + \ "Mem 4095" SAMPLE_SAMPLE_RESPONSE = "07/16/13\t09:33:06\t700\t4130\t695\t1018\t525" + NEWLINE SAMPLE_MET_RESPONSE = "Sig_1,counts,,SO,3.000E+00,3" + NEWLINE + \ "5,Ref_2,Emission_WL," + NEWLINE + \ "6,Sig_2,counts,,SO,2.000E+00,2" + NEWLINE + \ "7,Ref_3,Emission_WL," + NEWLINE + \ "8,Sig_3,counts,,SO,1.000E+00,1"
bsd-2-clause
EDUlib/edx-platform
lms/djangoapps/mobile_api/users/views.py
2
14742
""" Views for user API """ from completion.exceptions import UnavailableCompletionData from completion.utilities import get_key_to_last_completed_block from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.contrib.auth.signals import user_logged_in from django.shortcuts import redirect from django.utils import dateparse from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import UsageKey from rest_framework import generics, views from rest_framework.decorators import api_view from rest_framework.response import Response from xblock.fields import Scope from xblock.runtime import KeyValueStore from common.djangoapps.student.models import CourseEnrollment, User # lint-amnesty, pylint: disable=reimported from lms.djangoapps.courseware.access import is_mobile_available_for_user from lms.djangoapps.courseware.access_utils import ACCESS_GRANTED from lms.djangoapps.courseware.courses import get_current_child from lms.djangoapps.courseware.model_data import FieldDataCache from lms.djangoapps.courseware.module_render import get_module_for_descriptor from lms.djangoapps.courseware.views.index import save_positions_recursively_up from lms.djangoapps.mobile_api.utils import API_V1, API_V05 from openedx.features.course_duration_limits.access import check_course_expired from xmodule.modulestore.django import modulestore from xmodule.modulestore.exceptions import ItemNotFoundError from .. import errors from ..decorators import mobile_course_access, mobile_view from .serializers import CourseEnrollmentSerializer, CourseEnrollmentSerializerv05, UserSerializer @mobile_view(is_user=True) class UserDetail(generics.RetrieveAPIView): """ **Use Case** Get information about the specified user and access other resources the user has permissions for. Users are redirected to this endpoint after they sign in. You can use the **course_enrollments** value in the response to get a list of courses the user is enrolled in. **Example Request** GET /api/mobile/{version}/users/{username} **Response Values** If the request is successful, the request returns an HTTP 200 "OK" response. The HTTP 200 response has the following values. * course_enrollments: The URI to list the courses the currently signed in user is enrolled in. * email: The email address of the currently signed in user. * id: The ID of the user. * name: The full name of the currently signed in user. * username: The username of the currently signed in user. """ queryset = ( User.objects.all().select_related('profile') ) serializer_class = UserSerializer lookup_field = 'username' def get_serializer_context(self): context = super().get_serializer_context() context['api_version'] = self.kwargs.get('api_version') return context @mobile_view(is_user=True) class UserCourseStatus(views.APIView): """ **Use Cases** Get or update the ID of the module that the specified user last visited in the specified course. Get ID of the last completed block in case of version v1 **Example Requests** GET /api/mobile/{version}/users/{username}/course_status_info/{course_id} PATCH /api/mobile/{version}/users/{username}/course_status_info/{course_id} **PATCH Parameters** The body of the PATCH request can include the following parameters. * last_visited_module_id={module_id} * modification_date={date} The modification_date parameter is optional. If it is present, the update will only take effect if the modification_date in the request is later than the modification_date saved on the server. **Response Values** If the request is successful, the request returns an HTTP 200 "OK" response. The HTTP 200 response has the following values. * last_visited_module_id: The ID of the last module that the user visited in the course. * last_visited_module_path: The ID of the modules in the path from the last visited module to the course module. For version v1 GET request response includes the following values. * last_visited_block_id: ID of the last completed block. """ http_method_names = ["get", "patch"] def _last_visited_module_path(self, request, course): """ Returns the path from the last module visited by the current user in the given course up to the course module. If there is no such visit, the first item deep enough down the course tree is used. """ field_data_cache = FieldDataCache.cache_for_descriptor_descendents( course.id, request.user, course, depth=2) course_module = get_module_for_descriptor( request.user, request, course, field_data_cache, course.id, course=course ) path = [course_module] chapter = get_current_child(course_module, min_depth=2) if chapter is not None: path.append(chapter) section = get_current_child(chapter, min_depth=1) if section is not None: path.append(section) path.reverse() return path def _get_course_info(self, request, course): """ Returns the course status """ path = self._last_visited_module_path(request, course) path_ids = [str(module.location) for module in path] return Response({ "last_visited_module_id": path_ids[0], "last_visited_module_path": path_ids, }) def _update_last_visited_module_id(self, request, course, module_key, modification_date): """ Saves the module id if the found modification_date is less recent than the passed modification date """ field_data_cache = FieldDataCache.cache_for_descriptor_descendents( course.id, request.user, course, depth=2) try: module_descriptor = modulestore().get_item(module_key) except ItemNotFoundError: return Response(errors.ERROR_INVALID_MODULE_ID, status=400) module = get_module_for_descriptor( request.user, request, module_descriptor, field_data_cache, course.id, course=course ) if modification_date: key = KeyValueStore.Key( scope=Scope.user_state, user_id=request.user.id, block_scope_id=course.location, field_name='position' ) original_store_date = field_data_cache.last_modified(key) if original_store_date is not None and modification_date < original_store_date: # old modification date so skip update return self._get_course_info(request, course) save_positions_recursively_up(request.user, request, field_data_cache, module, course=course) return self._get_course_info(request, course) @mobile_course_access(depth=2) def get(self, request, course, *args, **kwargs): # lint-amnesty, pylint: disable=unused-argument """ Get the ID of the module that the specified user last visited in the specified course. """ user_course_status = self._get_course_info(request, course) api_version = self.kwargs.get("api_version") if api_version == API_V1: # Get ID of the block that the specified user last visited in the specified course. try: block_id = str(get_key_to_last_completed_block(request.user, course.id)) except UnavailableCompletionData: block_id = "" user_course_status.data["last_visited_block_id"] = block_id return user_course_status @mobile_course_access(depth=2) def patch(self, request, course, *args, **kwargs): # lint-amnesty, pylint: disable=unused-argument """ Update the ID of the module that the specified user last visited in the specified course. """ module_id = request.data.get("last_visited_module_id") modification_date_string = request.data.get("modification_date") modification_date = None if modification_date_string: modification_date = dateparse.parse_datetime(modification_date_string) if not modification_date or not modification_date.tzinfo: return Response(errors.ERROR_INVALID_MODIFICATION_DATE, status=400) if module_id: try: module_key = UsageKey.from_string(module_id) except InvalidKeyError: return Response(errors.ERROR_INVALID_MODULE_ID, status=400) return self._update_last_visited_module_id(request, course, module_key, modification_date) else: # The arguments are optional, so if there's no argument just succeed return self._get_course_info(request, course) @mobile_view(is_user=True) class UserCourseEnrollmentsList(generics.ListAPIView): """ **Use Case** Get information about the courses that the currently signed in user is enrolled in. v1 differs from v0.5 version by returning ALL enrollments for a user rather than only the enrollments the user has access to (that haven't expired). An additional attribute "expiration" has been added to the response, which lists the date when access to the course will expire or null if it doesn't expire. **Example Request** GET /api/mobile/v1/users/{username}/course_enrollments/ **Response Values** If the request for information about the user is successful, the request returns an HTTP 200 "OK" response. The HTTP 200 response has the following values. * expiration: The course expiration date for given user course pair or null if the course does not expire. * certificate: Information about the user's earned certificate in the course. * course: A collection of the following data about the course. * courseware_access: A JSON representation with access information for the course, including any access errors. * course_about: The URL to the course about page. * course_sharing_utm_parameters: Encoded UTM parameters to be included in course sharing url * course_handouts: The URI to get data for course handouts. * course_image: The path to the course image. * course_updates: The URI to get data for course updates. * discussion_url: The URI to access data for course discussions if it is enabled, otherwise null. * end: The end date of the course. * id: The unique ID of the course. * name: The name of the course. * number: The course number. * org: The organization that created the course. * start: The date and time when the course starts. * start_display: If start_type is a string, then the advertised_start date for the course. If start_type is a timestamp, then a formatted date for the start of the course. If start_type is empty, then the value is None and it indicates that the course has not yet started. * start_type: One of either "string", "timestamp", or "empty" * subscription_id: A unique "clean" (alphanumeric with '_') ID of the course. * video_outline: The URI to get the list of all videos that the user can access in the course. * created: The date the course was created. * is_active: Whether the course is currently active. Possible values are true or false. * mode: The type of certificate registration for this course (honor or certified). * url: URL to the downloadable version of the certificate, if exists. """ queryset = CourseEnrollment.objects.all() lookup_field = 'username' # In Django Rest Framework v3, there is a default pagination # class that transmutes the response data into a dictionary # with pagination information. The original response data (a list) # is stored in a "results" value of the dictionary. # For backwards compatibility with the existing API, we disable # the default behavior by setting the pagination_class to None. pagination_class = None def is_org(self, check_org, course_org): """ Check course org matches request org param or no param provided """ return check_org is None or (check_org.lower() == course_org.lower()) def get_serializer_context(self): context = super().get_serializer_context() context['api_version'] = self.kwargs.get('api_version') return context def get_serializer_class(self): api_version = self.kwargs.get('api_version') if api_version == API_V05: return CourseEnrollmentSerializerv05 return CourseEnrollmentSerializer def get_queryset(self): api_version = self.kwargs.get('api_version') enrollments = self.queryset.filter( user__username=self.kwargs['username'], is_active=True ).order_by('created').reverse() org = self.request.query_params.get('org', None) same_org = ( enrollment for enrollment in enrollments if enrollment.course_overview and self.is_org(org, enrollment.course_overview.org) ) mobile_available = ( enrollment for enrollment in same_org if is_mobile_available_for_user(self.request.user, enrollment.course_overview) ) not_duration_limited = ( enrollment for enrollment in mobile_available if check_course_expired(self.request.user, enrollment.course) == ACCESS_GRANTED ) if api_version == API_V05: # for v0.5 don't return expired courses return list(not_duration_limited) else: # return all courses, with associated expiration return list(mobile_available) @api_view(["GET"]) @mobile_view() def my_user_info(request, api_version): """ Redirect to the currently-logged-in user's info page """ # update user's last logged in from here because # updating it from the oauth2 related code is too complex user_logged_in.send(sender=User, user=request.user, request=request) return redirect("user-detail", api_version=api_version, username=request.user.username)
agpl-3.0
McStasMcXtrace/McCode
tools/comp-test/mctestcomp.py
1
2118
#!/usr/bin/env python import glob import pathlib import subprocess import tempfile class McTestcomp: def __init__(self,comppath): self.comppath=comppath self.compname=self.path_to_compname(comppath) self.set_flavour('mcstas') self.compiler='gcc' self.cflags='-lm' def path_to_compname(self,path): #path is a ssumed to be a path object return path.stem def set_flavour(self,flavour="mcstas"): self.flavour=flavour def set_path_tree(path=None,pathstring=None): if ( path.exists() and path.isdir()): #assume a path-oject is passed pass else: pass def code_cenerate(self): pass def run(self): #write the test instrument to a temporary file with tempfile.NamedTemporaryFile(delete=False) as tf: print(tf.name) tf.write(self.test_instrument().encode()) tf.seek(0) tf.close() cogen_return=self.run_cogen(tf) print(cogen_return) compile_return=self.run_compiler(tf) #need to cleanup a bit return (cogen_return.returncode,compile_return.returncode) def run_cogen(self,instr): print(" ".join([f"{self.flavour}","-t",f"{instr.name}","-o",f"{instr.name}.c"])) return subprocess.run([f"{self.flavour}","-t",f"{instr.name}","-o",f"{instr.name}.c"]) def run_compiler(self,instr): #this needs to somehow deal with DEPENDENCY also, through m[cx]run? args=[f"{self.compiler}",f"{instr.name}.c","-o",f"{instr.name}.out",self.cflags] args.append(self.cflags) return subprocess.run(args) #[f"{self.compiler}",f"{instr.name}.c","-o",f"{instr.name}.out"]) def test_instrument(self): return f"""DEFINE INSTRUMENT Test{self.compname}(dummy=1) INITIALIZE %{{ %}} TRACE COMPONENT origin = Arm() AT (0, 0, 0) RELATIVE ABSOLUTE COMPONENT comp = {self.compname}() AT(0,0,0) RELATIVE origin END """ def print_instrument(self): print(self.test_instrument()) def mcrun_instrument(): pass if __name__=='__main__': results={} p=pathlib.Path('Source_simple.comp') t=McTestcomp(p) rcs=t.run() results.update({p.name:rcs}) print(results)
gpl-2.0
ewheeler/rapidpro
temba/reports/tests.py
1
2443
from __future__ import unicode_literals import json from django.core.urlresolvers import reverse from models import Report from temba.tests import TembaTest class ReportTest(TembaTest): def test_create(self): self.login(self.admin) create_url = reverse('reports.report_create') response = self.client.get(create_url) self.assertEquals(response.status_code, 302) response = self.client.get(create_url, follow=True) self.assertEquals(response.status_code, 200) self.assertEquals(response.request['PATH_INFO'], reverse('flows.ruleset_analytics')) response = self.client.post(create_url, {"title": "first report", "description": "some description", "config": "{}"}) self.assertEquals(json.loads(response.content)['status'], "error") self.assertFalse('report' in json.loads(response.content)) response = self.client.post(create_url, data='{"title":"first report", "description":"some description", "config":""}', content_type='application/json') self.assertEquals(json.loads(response.content)['status'], "success") self.assertTrue('report' in json.loads(response.content)) self.assertTrue('id' in json.loads(response.content)['report']) report = Report.objects.get() self.assertEquals(report.pk, json.loads(response.content)['report']['id']) def test_report_model(self): Report.create_report(self.org, self.admin, dict(title="first", description="blah blah text", config=dict(fields=[1, 2, 3]))) self.assertEqual(Report.objects.all().count(), 1) Report.create_report(self.org, self.admin, dict(title="second", description="yeah yeah yeah", config=dict(fields=[4, 5, 6]))) self.assertEqual(Report.objects.all().count(), 2) report_id = Report.objects.filter(title="first")[0].pk Report.create_report(self.org, self.admin, dict(title="updated", description="yeah yeah yeahnew description", config=dict(fields=[8, 4]), id=report_id)) self.assertEqual(Report.objects.all().count(), 2) self.assertFalse(Report.objects.filter(title="first")) self.assertEqual(Report.objects.get(title="updated").pk, report_id)
agpl-3.0
tushart91/study-usc
Information Integration/Homework/HW1/HW1/requests/packages/urllib3/util/ssl_.py
170
8755
from binascii import hexlify, unhexlify from hashlib import md5, sha1 from ..exceptions import SSLError SSLContext = None HAS_SNI = False create_default_context = None import errno import ssl try: # Test for SSL features from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23 from ssl import HAS_SNI # Has SNI? except ImportError: pass try: from ssl import OP_NO_SSLv2, OP_NO_SSLv3, OP_NO_COMPRESSION except ImportError: OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000 OP_NO_COMPRESSION = 0x20000 try: from ssl import _DEFAULT_CIPHERS except ImportError: _DEFAULT_CIPHERS = ( 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+HIGH:' 'DH+HIGH:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+HIGH:RSA+3DES:ECDH+RC4:' 'DH+RC4:RSA+RC4:!aNULL:!eNULL:!MD5' ) try: from ssl import SSLContext # Modern SSL? except ImportError: import sys class SSLContext(object): # Platform-specific: Python 2 & 3.1 supports_set_ciphers = sys.version_info >= (2, 7) def __init__(self, protocol_version): self.protocol = protocol_version # Use default values from a real SSLContext self.check_hostname = False self.verify_mode = ssl.CERT_NONE self.ca_certs = None self.options = 0 self.certfile = None self.keyfile = None self.ciphers = None def load_cert_chain(self, certfile, keyfile): self.certfile = certfile self.keyfile = keyfile def load_verify_locations(self, location): self.ca_certs = location def set_ciphers(self, cipher_suite): if not self.supports_set_ciphers: raise TypeError( 'Your version of Python does not support setting ' 'a custom cipher suite. Please upgrade to Python ' '2.7, 3.2, or later if you need this functionality.' ) self.ciphers = cipher_suite def wrap_socket(self, socket, server_hostname=None): kwargs = { 'keyfile': self.keyfile, 'certfile': self.certfile, 'ca_certs': self.ca_certs, 'cert_reqs': self.verify_mode, 'ssl_version': self.protocol, } if self.supports_set_ciphers: # Platform-specific: Python 2.7+ return wrap_socket(socket, ciphers=self.ciphers, **kwargs) else: # Platform-specific: Python 2.6 return wrap_socket(socket, **kwargs) def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ # Maps the length of a digest to a possible hash function producing # this digest. hashfunc_map = { 16: md5, 20: sha1 } fingerprint = fingerprint.replace(':', '').lower() digest_length, odd = divmod(len(fingerprint), 2) if odd or digest_length not in hashfunc_map: raise SSLError('Fingerprint is of invalid length.') # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) hashfunc = hashfunc_map[digest_length] cert_digest = hashfunc(cert).digest() if not cert_digest == fingerprint_bytes: raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(hexlify(fingerprint_bytes), hexlify(cert_digest))) def resolve_cert_reqs(candidate): """ Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to :data:`ssl.CERT_NONE`. If given a string it is assumed to be the name of the constant in the :mod:`ssl` module or its abbrevation. (So you can specify `REQUIRED` instead of `CERT_REQUIRED`. If it's neither `None` nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket. """ if candidate is None: return CERT_NONE if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'CERT_' + candidate) return res return candidate def resolve_ssl_version(candidate): """ like resolve_cert_reqs """ if candidate is None: return PROTOCOL_SSLv23 if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'PROTOCOL_' + candidate) return res return candidate def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ context = SSLContext(ssl_version or ssl.PROTOCOL_SSLv23) if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION context.options |= options if getattr(context, 'supports_set_ciphers', True): # Platform-specific: Python 2.6 context.set_ciphers(ciphers or _DEFAULT_CIPHERS) context.verify_mode = cert_reqs if getattr(context, 'check_hostname', None) is not None: # Platform-specific: Python 3.2 context.check_hostname = (context.verify_mode == ssl.CERT_REQUIRED) return context def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None): """ All arguments except for server_hostname and ssl_context have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. This is not supported on Python 2.6 as the ssl module does not support it. """ context = ssl_context if context is None: context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs: try: context.load_verify_locations(ca_certs) except IOError as e: # Platform-specific: Python 2.6, 2.7, 3.2 raise SSLError(e) # Py33 raises FileNotFoundError which subclasses OSError # These are not equivalent unless we check the errno attribute except OSError as e: # Platform-specific: Python 3.3 and beyond if e.errno == errno.ENOENT: raise SSLError(e) raise if certfile: context.load_cert_chain(certfile, keyfile) if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI return context.wrap_socket(sock, server_hostname=server_hostname) return context.wrap_socket(sock)
mit
rhndg/openedx
common/djangoapps/embargo/migrations/0003_add_countries.py
102
6889
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models from django_countries import countries class Migration(DataMigration): def forwards(self, orm): """Populate the available countries with all 2-character ISO country codes. """ for country_code, __ in list(countries): orm.Country.objects.get_or_create(country=country_code) def backwards(self, orm): """Clear all available countries. """ orm.Country.objects.all().delete() models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, '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': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, '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', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), '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', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, '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'}), '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'}) }, 'embargo.country': { 'Meta': {'object_name': 'Country'}, 'country': ('django_countries.fields.CountryField', [], {'unique': 'True', 'max_length': '2', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'embargo.countryaccessrule': { 'Meta': {'unique_together': "(('restricted_course', 'rule_type'),)", 'object_name': 'CountryAccessRule'}, 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['embargo.Country']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'restricted_course': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['embargo.RestrictedCourse']"}), 'rule_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'embargo.embargoedcourse': { 'Meta': {'object_name': 'EmbargoedCourse'}, 'course_id': ('xmodule_django.models.CourseKeyField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'embargoed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'embargo.embargoedstate': { 'Meta': {'object_name': 'EmbargoedState'}, 'change_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'on_delete': 'models.PROTECT'}), 'embargoed_countries': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'embargo.ipfilter': { 'Meta': {'object_name': 'IPFilter'}, 'blacklist': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'change_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'on_delete': 'models.PROTECT'}), 'enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'whitelist': ('django.db.models.fields.TextField', [], {'blank': 'True'}) }, 'embargo.restrictedcourse': { 'Meta': {'object_name': 'RestrictedCourse'}, 'access_msg_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'course_key': ('xmodule_django.models.CourseKeyField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}), 'enroll_msg_key': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) } } complete_apps = ['embargo'] symmetrical = True
agpl-3.0
DelazJ/QGIS
tests/src/python/test_provider_ogr.py
8
80339
# -*- coding: utf-8 -*- """QGIS Unit tests for the non-shapefile, non-tabfile datasources handled by OGR provider. .. note:: 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__ = 'Even Rouault' __date__ = '2016-04-11' __copyright__ = 'Copyright 2016, Even Rouault' import hashlib import os import shutil import sys import tempfile from datetime import datetime from osgeo import gdal, ogr # NOQA from qgis.PyQt.QtCore import QVariant, QByteArray, QTemporaryDir from qgis.PyQt.QtXml import QDomDocument from qgis.core import ( NULL, QgsAuthMethodConfig, QgsApplication, QgsCoordinateTransformContext, QgsProject, QgsField, QgsFields, QgsGeometry, QgsRectangle, QgsProviderRegistry, QgsFeature, QgsFeatureRequest, QgsSettings, QgsDataProvider, QgsVectorDataProvider, QgsVectorLayer, QgsVectorFileWriter, QgsWkbTypes, QgsNetworkAccessManager, QgsLayerMetadata, QgsNotSupportedException, QgsMapLayerType, QgsProviderSublayerDetails, Qgis ) from qgis.testing import start_app, unittest from qgis.utils import spatialite_connect import mockedwebserver from utilities import unitTestDataPath start_app() TEST_DATA_DIR = unitTestDataPath() def GDAL_COMPUTE_VERSION(maj, min, rev): return ((maj) * 1000000 + (min) * 10000 + (rev) * 100) # Note - doesn't implement ProviderTestCase as most OGR provider is tested by the shapefile provider test def count_opened_filedescriptors(filename_to_test): count = -1 if sys.platform.startswith('linux'): count = 0 open_files_dirname = '/proc/%d/fd' % os.getpid() filenames = os.listdir(open_files_dirname) for filename in filenames: full_filename = open_files_dirname + '/' + filename if os.path.exists(full_filename): link = os.readlink(full_filename) if os.path.basename(link) == os.path.basename(filename_to_test): count += 1 return count class PyQgsOGRProvider(unittest.TestCase): @classmethod def setUpClass(cls): """Run before all tests""" # Create test layer cls.basetestpath = tempfile.mkdtemp() cls.datasource = os.path.join(cls.basetestpath, 'test.csv') with open(cls.datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,POINT(2 49)\n') cls.dirs_to_cleanup = [cls.basetestpath] @classmethod def tearDownClass(cls): """Run after all tests""" for dirname in cls.dirs_to_cleanup: shutil.rmtree(dirname, True) def testCapabilities(self): self.assertTrue(QgsProviderRegistry.instance().providerCapabilities("ogr") & QgsDataProvider.File) self.assertTrue(QgsProviderRegistry.instance().providerCapabilities("ogr") & QgsDataProvider.Dir) def testUpdateMode(self): vl = QgsVectorLayer('{}|layerid=0'.format(self.datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) caps = vl.dataProvider().capabilities() self.assertTrue(caps & QgsVectorDataProvider.AddFeatures) self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-write") # No-op self.assertTrue(vl.dataProvider().enterUpdateMode()) self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-write") # No-op self.assertTrue(vl.dataProvider().leaveUpdateMode()) self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-write") def testGeometryTypeKnownAtSecondFeature(self): datasource = os.path.join(self.basetestpath, 'testGeometryTypeKnownAtSecondFeature.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,\n') f.write('2,POINT(2 49)\n') vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), QgsWkbTypes.Point) def testMixOfPolygonCurvePolygon(self): datasource = os.path.join(self.basetestpath, 'testMixOfPolygonCurvePolygon.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,"POLYGON((0 0,0 1,1 1,0 0))"\n') f.write('2,"CURVEPOLYGON((0 0,0 1,1 1,0 0))"\n') f.write('3,"MULTIPOLYGON(((0 0,0 1,1 1,0 0)))"\n') f.write('4,"MULTISURFACE(((0 0,0 1,1 1,0 0)))"\n') vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(len(vl.dataProvider().subLayers()), 1) self.assertEqual(vl.dataProvider().subLayers()[0], QgsDataProvider.SUBLAYER_SEPARATOR.join( ['0', 'testMixOfPolygonCurvePolygon', '4', 'CurvePolygon', '', ''])) def testMixOfLineStringCompoundCurve(self): datasource = os.path.join(self.basetestpath, 'testMixOfLineStringCompoundCurve.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,"LINESTRING(0 0,0 1)"\n') f.write('2,"COMPOUNDCURVE((0 0,0 1))"\n') f.write('3,"MULTILINESTRING((0 0,0 1))"\n') f.write('4,"MULTICURVE((0 0,0 1))"\n') f.write('5,"CIRCULARSTRING(0 0,1 1,2 0)"\n') vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(len(vl.dataProvider().subLayers()), 1) self.assertEqual(vl.dataProvider().subLayers()[0], QgsDataProvider.SUBLAYER_SEPARATOR.join( ['0', 'testMixOfLineStringCompoundCurve', '5', 'CompoundCurve', '', ''])) def testGpxElevation(self): # GPX without elevation data datasource = os.path.join(TEST_DATA_DIR, 'noelev.gpx') vl = QgsVectorLayer('{}|layername=routes'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) f = next(vl.getFeatures()) self.assertEqual(f.geometry().wkbType(), QgsWkbTypes.LineString) # GPX with elevation data datasource = os.path.join(TEST_DATA_DIR, 'elev.gpx') vl = QgsVectorLayer('{}|layername=routes'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) f = next(vl.getFeatures()) self.assertEqual(f.geometry().wkbType(), QgsWkbTypes.LineString25D) self.assertEqual(f.geometry().constGet().pointN(0).z(), 1) self.assertEqual(f.geometry().constGet().pointN(1).z(), 2) self.assertEqual(f.geometry().constGet().pointN(2).z(), 3) def testNoDanglingFileDescriptorAfterCloseVariant1(self): ''' Test that when closing the provider all file handles are released ''' datasource = os.path.join(self.basetestpath, 'testNoDanglingFileDescriptorAfterCloseVariant1.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,\n') f.write('2,POINT(2 49)\n') vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) # The iterator will take one extra connection myiter = vl.getFeatures() # Consume one feature but the iterator is still opened f = next(myiter) self.assertTrue(f.isValid()) if sys.platform.startswith('linux'): self.assertEqual(count_opened_filedescriptors(datasource), 2) # Should release one file descriptor del vl # Non portable, but Windows testing is done with trying to unlink if sys.platform.startswith('linux'): self.assertEqual(count_opened_filedescriptors(datasource), 1) f = next(myiter) self.assertTrue(f.isValid()) # Should release one file descriptor del myiter # Non portable, but Windows testing is done with trying to unlink if sys.platform.startswith('linux'): self.assertEqual(count_opened_filedescriptors(datasource), 0) # Check that deletion works well (can only fail on Windows) os.unlink(datasource) self.assertFalse(os.path.exists(datasource)) def testNoDanglingFileDescriptorAfterCloseVariant2(self): ''' Test that when closing the provider all file handles are released ''' datasource = os.path.join(self.basetestpath, 'testNoDanglingFileDescriptorAfterCloseVariant2.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,\n') f.write('2,POINT(2 49)\n') vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) # Consume all features. myiter = vl.getFeatures() for feature in myiter: pass # The iterator is closed, but the corresponding connection still not closed if sys.platform.startswith('linux'): self.assertEqual(count_opened_filedescriptors(datasource), 2) # Should release one file descriptor del vl # Non portable, but Windows testing is done with trying to unlink if sys.platform.startswith('linux'): self.assertEqual(count_opened_filedescriptors(datasource), 0) # Check that deletion works well (can only fail on Windows) os.unlink(datasource) self.assertFalse(os.path.exists(datasource)) def testGeometryCollection(self): ''' Test that we can at least retrieves attribute of features with geometry collection ''' datasource = os.path.join(self.basetestpath, 'testGeometryCollection.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,POINT Z(2 49 0)\n') f.write('2,GEOMETRYCOLLECTION Z (POINT Z (2 49 0))\n') vl = QgsVectorLayer('{}|layerid=0|geometrytype=GeometryCollection'.format(datasource), 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertTrue(vl.featureCount(), 1) values = [f['id'] for f in vl.getFeatures()] self.assertEqual(values, ['2']) del vl os.unlink(datasource) self.assertFalse(os.path.exists(datasource)) def testGdb(self): """ Test opening a GDB database layer""" gdb_path = os.path.join(unitTestDataPath(), 'test_gdb.gdb') for i in range(3): l = QgsVectorLayer(gdb_path + '|layerid=' + str(i), 'test', 'ogr') self.assertTrue(l.isValid()) def testGdbFilter(self): """ Test opening a GDB database layer with filter""" gdb_path = os.path.join(unitTestDataPath(), 'test_gdb.gdb') l = QgsVectorLayer(gdb_path + '|layerid=1|subset="text" = \'shape 2\'', 'test', 'ogr') self.assertTrue(l.isValid()) it = l.getFeatures() f = QgsFeature() while it.nextFeature(f): self.assertTrue(f.attribute("text") == "shape 2") def testTriangleTINPolyhedralSurface(self): """ Test support for Triangles (mapped to Polygons) """ testsets = ( ("Triangle((0 0, 0 1, 1 1, 0 0))", QgsWkbTypes.Triangle, "Triangle ((0 0, 0 1, 1 1, 0 0))"), ("Triangle Z((0 0 1, 0 1 2, 1 1 3, 0 0 1))", QgsWkbTypes.TriangleZ, "TriangleZ ((0 0 1, 0 1 2, 1 1 3, 0 0 1))"), ("Triangle M((0 0 4, 0 1 5, 1 1 6, 0 0 4))", QgsWkbTypes.TriangleM, "TriangleM ((0 0 4, 0 1 5, 1 1 6, 0 0 4))"), ("Triangle ZM((0 0 0 1, 0 1 2 3, 1 1 4 5, 0 0 0 1))", QgsWkbTypes.TriangleZM, "TriangleZM ((0 0 0 1, 0 1 2 3, 1 1 4 5, 0 0 0 1))"), ("TIN (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))", QgsWkbTypes.MultiPolygon, "MultiPolygon (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))"), ("TIN Z(((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))", QgsWkbTypes.MultiPolygonZ, "MultiPolygonZ (((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))"), ("TIN M(((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))", QgsWkbTypes.MultiPolygonM, "MultiPolygonM (((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))"), ("TIN ZM(((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))", QgsWkbTypes.MultiPolygonZM, "MultiPolygonZM (((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))"), ("PolyhedralSurface (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))", QgsWkbTypes.MultiPolygon, "MultiPolygon (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))"), ("PolyhedralSurface Z(((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))", QgsWkbTypes.MultiPolygonZ, "MultiPolygonZ (((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))"), ("PolyhedralSurface M(((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))", QgsWkbTypes.MultiPolygonM, "MultiPolygonM (((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))"), ("PolyhedralSurface ZM(((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))", QgsWkbTypes.MultiPolygonZM, "MultiPolygonZM (((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))") ) for row in testsets: datasource = os.path.join(self.basetestpath, 'test.csv') with open(datasource, 'wt') as f: f.write('id,WKT\n') f.write('1,"%s"' % row[0]) vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), row[1]) f = QgsFeature() self.assertTrue(vl.getFeatures(QgsFeatureRequest(1)).nextFeature(f)) self.assertTrue(f.geometry()) self.assertEqual(f.geometry().constGet().asWkt(), row[2]) """PolyhedralSurface, Tin => mapped to MultiPolygon Triangle => mapped to Polygon """ def testSetupProxy(self): """Test proxy setup""" settings = QgsSettings() settings.setValue("proxy/proxyEnabled", True) settings.setValue("proxy/proxyPort", '1234') settings.setValue("proxy/proxyHost", 'myproxyhostname.com') settings.setValue("proxy/proxyUser", 'username') settings.setValue("proxy/proxyPassword", 'password') settings.setValue("proxy/proxyExcludedUrls", "http://www.myhost.com|http://www.myotherhost.com") QgsNetworkAccessManager.instance().setupDefaultProxyAndCache() vl = QgsVectorLayer(TEST_DATA_DIR + '/' + 'lines.shp', 'proxy_test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXY"), "myproxyhostname.com:1234") self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXYUSERPWD"), "username:password") settings.setValue("proxy/proxyEnabled", True) settings.remove("proxy/proxyPort") settings.setValue("proxy/proxyHost", 'myproxyhostname.com') settings.setValue("proxy/proxyUser", 'username') settings.remove("proxy/proxyPassword") settings.setValue("proxy/proxyExcludedUrls", "http://www.myhost.com|http://www.myotherhost.com") QgsNetworkAccessManager.instance().setupDefaultProxyAndCache() vl = QgsVectorLayer(TEST_DATA_DIR + '/' + 'lines.shp', 'proxy_test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXY"), "myproxyhostname.com") self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXYUSERPWD"), "username") def testEditGeoJsonRemoveField(self): """ Test bugfix of https://github.com/qgis/QGIS/issues/26484 (deleting an existing field)""" datasource = os.path.join(self.basetestpath, 'testEditGeoJsonRemoveField.json') with open(datasource, 'wt') as f: f.write("""{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "x": 1, "y": 2, "z": 3, "w": 4 }, "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } } ] }""") vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertTrue(vl.startEditing()) self.assertTrue(vl.deleteAttribute(1)) self.assertTrue(vl.commitChanges()) self.assertEqual(len(vl.dataProvider().fields()), 4 - 1) f = QgsFeature() self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f)) self.assertEqual(f['x'], 1) self.assertEqual(f['z'], 3) self.assertEqual(f['w'], 4) def testEditGeoJsonAddField(self): """ Test bugfix of https://github.com/qgis/QGIS/issues/26484 (adding a new field)""" datasource = os.path.join(self.basetestpath, 'testEditGeoJsonAddField.json') with open(datasource, 'wt') as f: f.write("""{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "x": 1 }, "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } } ] }""") vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertTrue(vl.startEditing()) self.assertTrue(vl.addAttribute(QgsField('strfield', QVariant.String))) self.assertTrue(vl.commitChanges()) self.assertEqual(len(vl.dataProvider().fields()), 1 + 1) f = QgsFeature() self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f)) self.assertIsNone(f['strfield']) # Completely reload file vl = QgsVectorLayer(datasource, 'test', 'ogr') # As we didn't set any value to the new field, it is not written at # all in the GeoJSON file, so it has disappeared self.assertEqual(len(vl.fields()), 1) def testEditGeoJsonAddFieldAndThenAddFeatures(self): """ Test bugfix of https://github.com/qgis/QGIS/issues/26484 (adding a new field)""" datasource = os.path.join(self.basetestpath, 'testEditGeoJsonAddField.json') with open(datasource, 'wt') as f: f.write("""{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "x": 1 }, "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } } ] }""") vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertTrue(vl.startEditing()) self.assertTrue(vl.addAttribute(QgsField('strfield', QVariant.String))) self.assertTrue(vl.commitChanges()) self.assertEqual(len(vl.dataProvider().fields()), 1 + 1) self.assertEqual([f.name() for f in vl.dataProvider().fields()], ['x', 'strfield']) f = QgsFeature() self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f)) self.assertIsNone(f['strfield']) self.assertEqual([field.name() for field in f.fields()], ['x', 'strfield']) self.assertTrue(vl.startEditing()) vl.changeAttributeValue(f.id(), 1, 'x') self.assertTrue(vl.commitChanges()) f = QgsFeature() self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f)) self.assertEqual(f['strfield'], 'x') self.assertEqual([field.name() for field in f.fields()], ['x', 'strfield']) # Completely reload file vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertEqual(len(vl.fields()), 2) def testDataItems(self): registry = QgsApplication.dataItemProviderRegistry() ogrprovider = next(provider for provider in registry.providers() if provider.name() == 'OGR') # Single layer item = ogrprovider.createDataItem(os.path.join(TEST_DATA_DIR, 'lines.shp'), None) self.assertTrue(item.uri().endswith('lines.shp')) # Multiple layer item = ogrprovider.createDataItem(os.path.join(TEST_DATA_DIR, 'multilayer.kml'), None) children = item.createChildren() self.assertEqual(len(children), 2) self.assertIn('multilayer.kml|layername=Layer1', children[0].uri()) self.assertIn('multilayer.kml|layername=Layer2', children[1].uri()) # Multiple layer (geopackage) tmpfile = os.path.join(self.basetestpath, 'testDataItems.gpkg') ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) lyr = ds.CreateLayer('Layer1', geom_type=ogr.wkbPoint) lyr = ds.CreateLayer('Layer2', geom_type=ogr.wkbPoint) ds = None item = ogrprovider.createDataItem(tmpfile, None) children = item.createChildren() self.assertEqual(len(children), 2) self.assertIn('testDataItems.gpkg|layername=Layer1', children[0].uri()) self.assertIn('testDataItems.gpkg|layername=Layer2', children[1].uri()) def testDataItemsRaster(self): registry = QgsApplication.dataItemProviderRegistry() ogrprovider = next(provider for provider in registry.providers() if provider.name() == 'OGR') # Multiple layer (geopackage) path = os.path.join(unitTestDataPath(), 'two_raster_layers.gpkg') item = ogrprovider.createDataItem(path, None) children = item.createChildren() self.assertEqual(len(children), 2) self.assertIn('GPKG:' + path + ':layer01', children[0].uri()) self.assertIn('GPKG:' + path + ':layer02', children[1].uri()) def testOSM(self): """ Test that opening several layers of the same OSM datasource works properly """ datasource = os.path.join(TEST_DATA_DIR, 'test.osm') vl_points = QgsVectorLayer(datasource + "|layername=points", 'test', 'ogr') vl_multipolygons = QgsVectorLayer(datasource + "|layername=multipolygons", 'test', 'ogr') f = QgsFeature() # When sharing the same dataset handle, the spatial filter of test # points layer would apply to the other layers iter_points = vl_points.getFeatures(QgsFeatureRequest().setFilterRect(QgsRectangle(-200, -200, -200, -200))) self.assertFalse(iter_points.nextFeature(f)) iter_multipolygons = vl_multipolygons.getFeatures(QgsFeatureRequest()) self.assertTrue(iter_multipolygons.nextFeature(f)) self.assertTrue(iter_multipolygons.nextFeature(f)) self.assertTrue(iter_multipolygons.nextFeature(f)) self.assertFalse(iter_multipolygons.nextFeature(f)) # Re-start an iterator (tests #20098) iter_multipolygons = vl_multipolygons.getFeatures(QgsFeatureRequest()) self.assertTrue(iter_multipolygons.nextFeature(f)) # Test filter by id (#20308) f = next(vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFid(8))) self.assertTrue(f.isValid()) self.assertEqual(f.id(), 8) f = next(vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFid(1))) self.assertTrue(f.isValid()) self.assertEqual(f.id(), 1) f = next(vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFid(5))) self.assertTrue(f.isValid()) self.assertEqual(f.id(), 5) # 6 doesn't exist it = vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFids([1, 5, 6, 8])) f = next(it) self.assertTrue(f.isValid()) self.assertEqual(f.id(), 1) f = next(it) self.assertTrue(f.isValid()) self.assertEqual(f.id(), 5) f = next(it) self.assertTrue(f.isValid()) self.assertEqual(f.id(), 8) del it def testBinaryField(self): source = os.path.join(TEST_DATA_DIR, 'attachments.gdb') vl = QgsVectorLayer(source + "|layername=points__ATTACH") self.assertTrue(vl.isValid()) fields = vl.fields() data_field = fields[fields.lookupField('DATA')] self.assertEqual(data_field.type(), QVariant.ByteArray) self.assertEqual(data_field.typeName(), 'Binary') features = {f['ATTACHMENTID']: f for f in vl.getFeatures()} self.assertEqual(len(features), 2) self.assertIsInstance(features[1]['DATA'], QByteArray) self.assertEqual(hashlib.md5(features[1]['DATA'].data()).hexdigest(), 'ef3dbc530cc39a545832a6c82aac57b6') self.assertIsInstance(features[2]['DATA'], QByteArray) self.assertEqual(hashlib.md5(features[2]['DATA'].data()).hexdigest(), '4b952b80e4288ca5111be2f6dd5d6809') def testGmlStringListField(self): source = os.path.join(TEST_DATA_DIR, 'stringlist.gml') vl = QgsVectorLayer(source) self.assertTrue(vl.isValid()) fields = vl.fields() descriptive_group_field = fields[fields.lookupField('descriptiveGroup')] self.assertEqual(descriptive_group_field.type(), QVariant.StringList) self.assertEqual(descriptive_group_field.typeName(), 'StringList') self.assertEqual(descriptive_group_field.subType(), QVariant.String) feature = vl.getFeature(1000002717654) self.assertEqual(feature['descriptiveGroup'], ['Building']) self.assertEqual(feature['reasonForChange'], ['Reclassified', 'Attributes']) tmpfile = os.path.join(self.basetestpath, 'newstringlistfield.gml') ds = ogr.GetDriverByName('GML').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('strlistfield', ogr.OFTStringList)) ds = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) dp = vl.dataProvider() fields = dp.fields() list_field = fields[fields.lookupField('strlistfield')] self.assertEqual(list_field.type(), QVariant.StringList) self.assertEqual(list_field.typeName(), 'StringList') self.assertEqual(list_field.subType(), QVariant.String) def testStringListField(self): tmpfile = os.path.join(self.basetestpath, 'newstringlistfield.geojson') ds = ogr.GetDriverByName('GeoJSON').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('stringlistfield', ogr.OFTStringList)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 1)')) f.SetField('strfield', 'one') f.SetField('intfield', 1) f.SetFieldStringList(2, ['a', 'b', 'c']) lyr.CreateFeature(f) lyr = None ds = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) dp = vl.dataProvider() fields = dp.fields() list_field = fields[fields.lookupField('stringlistfield')] self.assertEqual(list_field.type(), QVariant.StringList) self.assertEqual(list_field.typeName(), 'StringList') self.assertEqual(list_field.subType(), QVariant.String) f = next(vl.getFeatures()) self.assertEqual(f.attributes(), ['one', 1, ['a', 'b', 'c']]) # add features f = QgsFeature() f.setAttributes(['two', 2, ['z', 'y', 'x']]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['three', 3, NULL]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['four', 4, []]) self.assertTrue(vl.dataProvider().addFeature(f)) vl = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, ['a', 'b', 'c']], ['two', 2, ['z', 'y', 'x']], ['three', 3, NULL], ['four', 4, NULL]]) # change attribute values f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues({f1_id: {2: NULL}, f3_id: {2: ['m', 'n', 'o']}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL], ['two', 2, ['z', 'y', 'x']], ['three', 3, ['m', 'n', 'o']], ['four', 4, NULL]]) # add attribute self.assertTrue( vl.dataProvider().addAttributes([QgsField('new_list', type=QVariant.StringList, subType=QVariant.String)])) f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues({f1_id: {3: ['111', '222']}, f3_id: {3: ['121', '122', '123']}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL, ['111', '222']], ['two', 2, ['z', 'y', 'x'], NULL], ['three', 3, ['m', 'n', 'o'], ['121', '122', '123']], ['four', 4, NULL, NULL]]) def testIntListField(self): tmpfile = os.path.join(self.basetestpath, 'newintlistfield.geojson') ds = ogr.GetDriverByName('GeoJSON').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('intlistfield', ogr.OFTIntegerList)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 1)')) f.SetField('strfield', 'one') f.SetField('intfield', 1) f.SetFieldIntegerList(2, [1, 2, 3, 4]) lyr.CreateFeature(f) lyr = None ds = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) dp = vl.dataProvider() fields = dp.fields() list_field = fields[fields.lookupField('intlistfield')] self.assertEqual(list_field.type(), QVariant.List) self.assertEqual(list_field.typeName(), 'IntegerList') self.assertEqual(list_field.subType(), QVariant.Int) f = next(vl.getFeatures()) self.assertEqual(f.attributes(), ['one', 1, [1, 2, 3, 4]]) # add features f = QgsFeature() f.setAttributes(['two', 2, [11, 12, 13, 14]]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['three', 3, NULL]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['four', 4, []]) self.assertTrue(vl.dataProvider().addFeature(f)) vl = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, [1, 2, 3, 4]], ['two', 2, [11, 12, 13, 14]], ['three', 3, NULL], ['four', 4, NULL]]) # change attribute values f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues({f1_id: {2: NULL}, f3_id: {2: [21, 22, 23]}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL], ['two', 2, [11, 12, 13, 14]], ['three', 3, [21, 22, 23]], ['four', 4, NULL]]) # add attribute self.assertTrue( vl.dataProvider().addAttributes([QgsField('new_list', type=QVariant.List, subType=QVariant.Int)])) f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues({f1_id: {3: [111, 222]}, f3_id: {3: [121, 122, 123]}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL, [111, 222]], ['two', 2, [11, 12, 13, 14], NULL], ['three', 3, [21, 22, 23], [121, 122, 123]], ['four', 4, NULL, NULL]]) def testDoubleListField(self): tmpfile = os.path.join(self.basetestpath, 'newdoublelistfield.geojson') ds = ogr.GetDriverByName('GeoJSON').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('doublelistfield', ogr.OFTRealList)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 1)')) f.SetField('strfield', 'one') f.SetField('intfield', 1) f.SetFieldDoubleList(2, [1.1, 2.2, 3.3, 4.4]) lyr.CreateFeature(f) lyr = None ds = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) dp = vl.dataProvider() fields = dp.fields() list_field = fields[fields.lookupField('doublelistfield')] self.assertEqual(list_field.type(), QVariant.List) self.assertEqual(list_field.typeName(), 'RealList') self.assertEqual(list_field.subType(), QVariant.Double) f = next(vl.getFeatures()) self.assertEqual(f.attributes(), ['one', 1, [1.1, 2.2, 3.3, 4.4]]) # add features f = QgsFeature() f.setAttributes(['two', 2, [11.1, 12.2, 13.3, 14.4]]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['three', 3, NULL]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['four', 4, []]) self.assertTrue(vl.dataProvider().addFeature(f)) vl = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, [1.1, 2.2, 3.3, 4.4]], ['two', 2, [11.1, 12.2, 13.3, 14.4]], ['three', 3, NULL], ['four', 4, NULL]]) # change attribute values f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues({f1_id: {2: NULL}, f3_id: {2: [21.1, 22.2, 23.3]}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL], ['two', 2, [11.1, 12.2, 13.3, 14.4]], ['three', 3, [21.1, 22.2, 23.3]], ['four', 4, NULL]]) # add attribute self.assertTrue( vl.dataProvider().addAttributes([QgsField('new_list', type=QVariant.List, subType=QVariant.Double)])) f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue( vl.dataProvider().changeAttributeValues({f1_id: {3: [111.1, 222.2]}, f3_id: {3: [121.1, 122.2, 123.3]}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL, [111.1, 222.2]], ['two', 2, [11.1, 12.2, 13.3, 14.4], NULL], ['three', 3, [21.1, 22.2, 23.3], [121.1, 122.2, 123.3]], ['four', 4, NULL, NULL]]) def testInteger64ListField(self): tmpfile = os.path.join(self.basetestpath, 'newlonglonglistfield.geojson') ds = ogr.GetDriverByName('GeoJSON').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) lyr.CreateField(ogr.FieldDefn('longlonglistfield', ogr.OFTInteger64List)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 1)')) f.SetField('strfield', 'one') f.SetField('intfield', 1) f.SetFieldDoubleList(2, [1234567890123, 1234567890124, 1234567890125, 1234567890126]) lyr.CreateFeature(f) lyr = None ds = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) dp = vl.dataProvider() fields = dp.fields() list_field = fields[fields.lookupField('longlonglistfield')] self.assertEqual(list_field.type(), QVariant.List) self.assertEqual(list_field.typeName(), 'Integer64List') self.assertEqual(list_field.subType(), QVariant.LongLong) f = next(vl.getFeatures()) self.assertEqual(f.attributes(), ['one', 1, [1234567890123, 1234567890124, 1234567890125, 1234567890126]]) # add features f = QgsFeature() f.setAttributes(['two', 2, [2234567890123, 2234567890124, 2234567890125, 2234567890126]]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['three', 3, NULL]) self.assertTrue(vl.dataProvider().addFeature(f)) f.setAttributes(['four', 4, []]) self.assertTrue(vl.dataProvider().addFeature(f)) vl = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, [1234567890123, 1234567890124, 1234567890125, 1234567890126]], ['two', 2, [2234567890123, 2234567890124, 2234567890125, 2234567890126]], ['three', 3, NULL], ['four', 4, NULL]]) # change attribute values f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues( {f1_id: {2: NULL}, f3_id: {2: [3234567890123, 3234567890124, 3234567890125, 3234567890126]}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL], ['two', 2, [2234567890123, 2234567890124, 2234567890125, 2234567890126]], ['three', 3, [3234567890123, 3234567890124, 3234567890125, 3234567890126]], ['four', 4, NULL]]) # add attribute self.assertTrue( vl.dataProvider().addAttributes([QgsField('new_list', type=QVariant.List, subType=QVariant.LongLong)])) f1_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 1][0] f3_id = [f.id() for f in vl.getFeatures() if f.attributes()[1] == 3][0] self.assertTrue(vl.dataProvider().changeAttributeValues( {f1_id: {3: [4234567890123, 4234567890124]}, f3_id: {3: [5234567890123, 5234567890124, 5234567890125]}})) vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) self.assertEqual([f.attributes() for f in vl.getFeatures()], [['one', 1, NULL, [4234567890123, 4234567890124]], ['two', 2, [2234567890123, 2234567890124, 2234567890125, 2234567890126], NULL], ['three', 3, [3234567890123, 3234567890124, 3234567890125, 3234567890126], [5234567890123, 5234567890124, 5234567890125]], ['four', 4, NULL, NULL]]) def testBlobCreation(self): """ Test creating binary blob field in existing table """ tmpfile = os.path.join(self.basetestpath, 'newbinaryfield.sqlite') ds = ogr.GetDriverByName('SQLite').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, options=['FID=fid']) lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString)) lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger)) f = None ds = None vl = QgsVectorLayer(tmpfile) self.assertTrue(vl.isValid()) dp = vl.dataProvider() f = QgsFeature(dp.fields()) f.setAttributes([1, 'str', 100]) self.assertTrue(dp.addFeature(f)) # add binary field self.assertTrue(dp.addAttributes([QgsField('binfield', QVariant.ByteArray)])) fields = dp.fields() bin1_field = fields[fields.lookupField('binfield')] self.assertEqual(bin1_field.type(), QVariant.ByteArray) self.assertEqual(bin1_field.typeName(), 'Binary') f = QgsFeature(fields) bin_1 = b'xxx' bin_val1 = QByteArray(bin_1) f.setAttributes([2, 'str2', 200, bin_val1]) self.assertTrue(dp.addFeature(f)) f2 = [f for f in dp.getFeatures()][1] self.assertEqual(f2.attributes(), [2, 'str2', 200, QByteArray(bin_1)]) def testBoolFieldEvaluation(self): datasource = os.path.join(unitTestDataPath(), 'bool_geojson.json') vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(vl.fields().at(0).name(), 'bool') self.assertEqual(vl.fields().at(0).type(), QVariant.Bool) self.assertEqual([f[0] for f in vl.getFeatures()], [True, False, NULL]) self.assertEqual([f[0].__class__.__name__ for f in vl.getFeatures()], ['bool', 'bool', 'QVariant']) def testReloadDataAndFeatureCount(self): filename = '/vsimem/test.json' gdal.FileFromMemBuffer(filename, """{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": null, "geometry": { "type": "Point", "coordinates": [2, 49] } }, { "type": "Feature", "properties": null, "geometry": { "type": "Point", "coordinates": [3, 50] } } ] }""") vl = QgsVectorLayer(filename, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(vl.featureCount(), 2) gdal.FileFromMemBuffer(filename, """{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": null, "geometry": { "type": "Point", "coordinates": [2, 49] } } ] }""") vl.reload() self.assertEqual(vl.featureCount(), 1) gdal.Unlink(filename) def testSpatialiteDefaultValues(self): """Test whether in spatialite table with default values like CURRENT_TIMESTAMP or (datetime('now','localtime')) they are respected. See GH #33383""" # Create the test table dbname = os.path.join(tempfile.gettempdir(), "test.sqlite") if os.path.exists(dbname): os.remove(dbname) con = spatialite_connect(dbname, isolation_level=None) cur = con.cursor() cur.execute("BEGIN") sql = "SELECT InitSpatialMetadata()" cur.execute(sql) # simple table with primary key sql = """ CREATE TABLE test_table_default_values ( id integer primary key autoincrement, comment TEXT, created_at_01 text DEFAULT (datetime('now','localtime')), created_at_02 text DEFAULT CURRENT_TIMESTAMP, anumber INTEGER DEFAULT 123, atext TEXT default 'My default' ) """ cur.execute(sql) cur.execute("COMMIT") con.close() vl = QgsVectorLayer(dbname + '|layername=test_table_default_values', 'test_table_default_values', 'ogr') self.assertTrue(vl.isValid()) # Save it for the test now = datetime.now() # Test default values dp = vl.dataProvider() # FIXME: should it be None? self.assertTrue(dp.defaultValue(0).isNull()) self.assertIsNone(dp.defaultValue(1)) # FIXME: This fails because there is no backend-side evaluation in this provider # self.assertTrue(dp.defaultValue(2).startswith(now.strftime('%Y-%m-%d'))) self.assertTrue(dp.defaultValue(3).startswith(now.strftime('%Y-%m-%d'))) self.assertEqual(dp.defaultValue(4), 123) self.assertEqual(dp.defaultValue(5), 'My default') self.assertEqual(dp.defaultValueClause(0), 'Autogenerate') self.assertEqual(dp.defaultValueClause(1), '') self.assertEqual(dp.defaultValueClause(2), "datetime('now','localtime')") self.assertEqual(dp.defaultValueClause(3), "CURRENT_TIMESTAMP") # FIXME: ogr provider simply returns values when asked for clauses # self.assertEqual(dp.defaultValueClause(4), '') # self.assertEqual(dp.defaultValueClause(5), '') feature = QgsFeature(vl.fields()) for idx in range(vl.fields().count()): default = vl.dataProvider().defaultValue(idx) if not default: feature.setAttribute(idx, 'A comment') else: feature.setAttribute(idx, default) self.assertTrue(vl.dataProvider().addFeature(feature)) del (vl) # Verify vl2 = QgsVectorLayer(dbname + '|layername=test_table_default_values', 'test_table_default_values', 'ogr') self.assertTrue(vl2.isValid()) feature = next(vl2.getFeatures()) self.assertEqual(feature.attribute(1), 'A comment') self.assertTrue(feature.attribute(2).startswith(now.strftime('%Y-%m-%d'))) self.assertTrue(feature.attribute(3).startswith(now.strftime('%Y-%m-%d'))) self.assertEqual(feature.attribute(4), 123) self.assertEqual(feature.attribute(5), 'My default') def testMixOfFilterExpressionAndSubsetStringWhenFilterExpressionCompilationFails(self): datasource = os.path.join(unitTestDataPath(), 'filter_test.shp') vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertCountEqual([f.attributes() for f in vl.getFeatures()], [['circle', '1'], ['circle', '2'], ['rectangle', '1'], ['rectangle', '2']]) # note - request uses wrong type for match (string vs int). This is OK for QGIS expressions, # but will be rejected after we try to compile the expression for OGR to use. request = QgsFeatureRequest().setFilterExpression('"color" = 1') self.assertCountEqual([f.attributes() for f in vl.getFeatures(request)], [['circle', '1'], ['rectangle', '1']]) request = QgsFeatureRequest().setFilterExpression('"color" = 1') self.assertCountEqual([f.attributes() for f in vl.getFeatures(request)], [['circle', '1'], ['rectangle', '1']]) vl.setSubsetString("\"shape\" = 'rectangle'") self.assertCountEqual([f.attributes() for f in vl.getFeatures()], [['rectangle', '1'], ['rectangle', '2']]) self.assertCountEqual([f.attributes() for f in vl.getFeatures(request)], [['rectangle', '1']]) @unittest.skipIf(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(3, 2, 0), "GDAL 3.2 required") def testFieldAliases(self): """ Test that field aliases are taken from OGR where available (requires GDAL 3.2 or later) """ datasource = os.path.join(unitTestDataPath(), 'field_alias.gdb') vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) fields = vl.fields() # proprietary FileGDB driver doesn't have the raster column if 'raster' not in set(f.name() for f in fields): expected_fieldnames = ['OBJECTID', 'text', 'short_int', 'long_int', 'float', 'double', 'date', 'blob', 'guid', 'SHAPE_Length', 'SHAPE_Area'] expected_alias = ['', 'My Text Field', 'My Short Int Field', 'My Long Int Field', 'My Float Field', 'My Double Field', 'My Date Field', 'My Blob Field', 'My GUID field', '', ''] expected_alias_map = {'OBJECTID': '', 'SHAPE_Area': '', 'SHAPE_Length': '', 'blob': 'My Blob Field', 'date': 'My Date Field', 'double': 'My Double Field', 'float': 'My Float Field', 'guid': 'My GUID field', 'long_int': 'My Long Int Field', 'short_int': 'My Short Int Field', 'text': 'My Text Field'} else: expected_fieldnames = ['OBJECTID', 'text', 'short_int', 'long_int', 'float', 'double', 'date', 'blob', 'guid', 'raster', 'SHAPE_Length', 'SHAPE_Area'] expected_alias = ['', 'My Text Field', 'My Short Int Field', 'My Long Int Field', 'My Float Field', 'My Double Field', 'My Date Field', 'My Blob Field', 'My GUID field', 'My Raster Field', '', ''] expected_alias_map = {'OBJECTID': '', 'SHAPE_Area': '', 'SHAPE_Length': '', 'blob': 'My Blob Field', 'date': 'My Date Field', 'double': 'My Double Field', 'float': 'My Float Field', 'guid': 'My GUID field', 'long_int': 'My Long Int Field', 'raster': 'My Raster Field', 'short_int': 'My Short Int Field', 'text': 'My Text Field'} self.assertEqual([f.name() for f in fields], expected_fieldnames) self.assertEqual([f.alias() for f in fields], expected_alias) self.assertEqual(vl.attributeAliases(), expected_alias_map) def testGdbLayerMetadata(self): """ Test that we translate GDB metadata to QGIS layer metadata on loading a GDB source """ datasource = os.path.join(unitTestDataPath(), 'gdb_metadata.gdb') vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(vl.metadata().identifier(), 'Test') self.assertEqual(vl.metadata().title(), 'Title') self.assertEqual(vl.metadata().type(), 'dataset') self.assertEqual(vl.metadata().language(), 'ENG') self.assertIn('This is the abstract', vl.metadata().abstract()) self.assertEqual(vl.metadata().keywords(), {'Search keys': ['Tags']}) self.assertEqual(vl.metadata().rights(), ['This is the credits']) self.assertEqual(vl.metadata().constraints()[0].type, 'Limitations of use') self.assertEqual(vl.metadata().constraints()[0].constraint, 'This is the use limitation') self.assertEqual(vl.metadata().extent().spatialExtents()[0].bounds.xMinimum(), 1) self.assertEqual(vl.metadata().extent().spatialExtents()[0].bounds.xMaximum(), 2) self.assertEqual(vl.metadata().extent().spatialExtents()[0].bounds.yMinimum(), 3) self.assertEqual(vl.metadata().extent().spatialExtents()[0].bounds.yMaximum(), 4) def testShpLayerMetadata(self): """ Test that we translate .shp.xml metadata to QGIS layer metadata on loading a shp file (if present) """ datasource = os.path.join(unitTestDataPath(), 'france_parts.shp') vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(vl.metadata().identifier(), 'QLD_STRUCTURAL_FRAMEWORK_OUTLINE') self.assertEqual(vl.metadata().title(), 'QLD_STRUCTURAL_FRAMEWORK_OUTLINE') self.assertEqual(vl.metadata().type(), 'dataset') self.assertEqual(vl.metadata().language(), 'EN') def testOpenOptions(self): filename = os.path.join(tempfile.gettempdir(), "testOpenOptions.gpkg") if os.path.exists(filename): os.remove(filename) ds = ogr.GetDriverByName("GPKG").CreateDataSource(filename) lyr = ds.CreateLayer("points", geom_type=ogr.wkbPoint) ds.ExecuteSQL("CREATE TABLE foo(id INTEGER PRIMARY KEY, name TEXT)") ds.ExecuteSQL("INSERT INTO foo VALUES(1, 'bar');") ds = None vl = QgsVectorLayer(filename + "|option:LIST_ALL_TABLES=NO", 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(len(vl.dataProvider().subLayers()), 1) del vl vl = QgsVectorLayer(filename + "|option:LIST_ALL_TABLES=YES", 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(len(vl.dataProvider().subLayers()), 2) del vl vl = QgsVectorLayer(filename + "|layername=foo|option:LIST_ALL_TABLES=YES", 'test', 'ogr') self.assertTrue(vl.isValid()) self.assertEqual(len([f for f in vl.getFeatures()]), 1) del vl os.remove(filename) def testTransactionGroupExpressionFields(self): """Test issue GH #39230, this is not really specific to GPKG""" project = QgsProject() project.setAutoTransaction(True) tmpfile = os.path.join( self.basetestpath, 'tempGeoPackageTransactionExpressionFields.gpkg') ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile) lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint) lyr.CreateField(ogr.FieldDefn('str_field', ogr.OFTString)) f = ogr.Feature(lyr.GetLayerDefn()) f.SetGeometry(ogr.CreateGeometryFromWkt('POINT (1 1)')) f.SetField('str_field', 'one') lyr.CreateFeature(f) del lyr del ds vl = QgsVectorLayer(tmpfile + '|layername=test', 'test', 'ogr') f = QgsField('expression_field', QVariant.Int) idx = vl.addExpressionField('123', f) self.assertEqual(vl.fields().fieldOrigin(idx), QgsFields.OriginExpression) project.addMapLayers([vl]) feature = next(vl.getFeatures()) feature.setAttributes([None, 'two', 123]) self.assertTrue(vl.startEditing()) self.assertTrue(vl.addFeature(feature)) self.assertFalse(vl.dataProvider().hasErrors()) @unittest.skipIf(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(3, 2, 0), "GDAL 3.2 required") @unittest.skipIf(ogr.GetDriverByName('OAPIF') is None, "OAPIF driver not available") def testHTTPRequestsOverrider(self): """ Test that GDAL curl network requests are redirected through QGIS networking """ with mockedwebserver.install_http_server() as port: handler = mockedwebserver.SequentialHandler() # Check failed network requests # Check that the driver requested Accept header is well propagated handler.add('GET', '/collections/foo', 404, expected_headers={'Accept': 'application/json'}) with mockedwebserver.install_http_handler(handler): QgsVectorLayer("OAPIF:http://127.0.0.1:%d/collections/foo" % port, 'test', 'ogr') # Error coming from Qt network stack, not GDAL/CURL one assert 'server replied: Not Found' in gdal.GetLastErrorMsg() # Test a nominal case handler = mockedwebserver.SequentialHandler() handler.add('GET', '/collections/foo', 200, {'Content-Type': 'application/json'}, '{ "id": "foo" }') handler.add('GET', '/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') handler.add('GET', '/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') if int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(3, 3, 0): handler.add('GET', '/collections/foo/items?limit=10', 200, {'Content-Type': 'application/geo+json'}, '{ "type": "FeatureCollection", "features": [] }') with mockedwebserver.install_http_handler(handler): vl = QgsVectorLayer("OAPIF:http://127.0.0.1:%d/collections/foo" % port, 'test', 'ogr') assert vl.isValid() # More complicated test using an anthentication configuration authm = QgsApplication.authManager() self.assertTrue(authm.setMasterPassword('masterpassword', True)) config = QgsAuthMethodConfig() config.setName('Basic') config.setMethod('Basic') config.setConfig('username', 'username') config.setConfig('password', 'password') self.assertTrue(authm.storeAuthenticationConfig(config, True)) handler = mockedwebserver.SequentialHandler() # Check that the authcfg gets expanded during the network request ! handler.add('GET', '/collections/foo', 404, expected_headers={ 'Authorization': 'Basic dXNlcm5hbWU6cGFzc3dvcmQ='}) with mockedwebserver.install_http_handler(handler): QgsVectorLayer("OAPIF:http://127.0.0.1:%d/collections/foo authcfg='%s'" % (port, config.id()), 'test', 'ogr') def testShapefilesWithNoAttributes(self): """Test issue GH #38834""" ml = QgsVectorLayer('Point?crs=epsg:4326', 'test', 'memory') self.assertTrue(ml.isValid()) d = QTemporaryDir() options = QgsVectorFileWriter.SaveVectorOptions() options.driverName = 'ESRI Shapefile' options.layerName = 'writetest' err, _ = QgsVectorFileWriter.writeAsVectorFormatV2(ml, os.path.join(d.path(), 'writetest.shp'), QgsCoordinateTransformContext(), options) self.assertEqual(err, QgsVectorFileWriter.NoError) self.assertTrue(os.path.isfile(os.path.join(d.path(), 'writetest.shp'))) vl = QgsVectorLayer(os.path.join(d.path(), 'writetest.shp')) self.assertTrue(bool(vl.dataProvider().capabilities() & QgsVectorDataProvider.AddFeatures)) # Let's try if we can really add features feature = QgsFeature(vl.fields()) geom = QgsGeometry.fromWkt('POINT(9 45)') feature.setGeometry(geom) self.assertTrue(vl.startEditing()) self.assertTrue(vl.addFeatures([feature])) self.assertTrue(vl.commitChanges()) del (vl) vl = QgsVectorLayer(os.path.join(d.path(), 'writetest.shp')) self.assertEqual(vl.featureCount(), 1) def testFidDoubleSaveAsGeopackage(self): """Test issue GH #25795""" ml = QgsVectorLayer('Point?crs=epsg:4326&field=fid:double(20,0)', 'test', 'memory') self.assertTrue(ml.isValid()) self.assertEqual(ml.fields()[0].type(), QVariant.Double) d = QTemporaryDir() options = QgsVectorFileWriter.SaveVectorOptions() options.driverName = 'GPKG' options.layerName = 'fid_double_test' err, _ = QgsVectorFileWriter.writeAsVectorFormatV2(ml, os.path.join(d.path(), 'fid_double_test.gpkg'), QgsCoordinateTransformContext(), options) self.assertEqual(err, QgsVectorFileWriter.NoError) self.assertTrue(os.path.isfile(os.path.join(d.path(), 'fid_double_test.gpkg'))) vl = QgsVectorLayer(os.path.join(d.path(), 'fid_double_test.gpkg')) self.assertEqual(vl.fields()[0].type(), QVariant.LongLong) def testNonGeopackageSaveMetadata(self): """ Save layer metadata for a file-based format which doesn't have native metadata support. In this case we should resort to a sidecar file instead. """ ml = QgsVectorLayer('Point?crs=epsg:4326&field=pk:integer&field=cnt:int8', 'test', 'memory') self.assertTrue(ml.isValid()) d = QTemporaryDir() options = QgsVectorFileWriter.SaveVectorOptions() options.driverName = 'ESRI Shapefile' options.layerName = 'metadatatest' err, _ = QgsVectorFileWriter.writeAsVectorFormatV2(ml, os.path.join(d.path(), 'metadatatest.shp'), QgsCoordinateTransformContext(), options) self.assertEqual(err, QgsVectorFileWriter.NoError) self.assertTrue(os.path.isfile(os.path.join(d.path(), 'metadatatest.shp'))) uri = d.path() + '/metadatatest.shp' # now save some metadata metadata = QgsLayerMetadata() metadata.setAbstract('my abstract') metadata.setIdentifier('my identifier') metadata.setLicenses(['l1', 'l2']) ok, err = QgsProviderRegistry.instance().saveLayerMetadata('ogr', uri, metadata) self.assertTrue(ok) self.assertTrue(os.path.exists(os.path.join(d.path(), 'metadatatest.qmd'))) with open(os.path.join(d.path(), 'metadatatest.qmd'), 'rt') as f: metadata_xml = ''.join(f.readlines()) metadata2 = QgsLayerMetadata() doc = QDomDocument() doc.setContent(metadata_xml) self.assertTrue(metadata2.readMetadataXml(doc.documentElement())) self.assertEqual(metadata2.abstract(), 'my abstract') self.assertEqual(metadata2.identifier(), 'my identifier') self.assertEqual(metadata2.licenses(), ['l1', 'l2']) # try updating existing metadata -- file should be overwritten metadata2.setAbstract('my abstract 2') metadata2.setIdentifier('my identifier 2') metadata2.setHistory(['h1', 'h2']) ok, err = QgsProviderRegistry.instance().saveLayerMetadata('ogr', uri, metadata2) self.assertTrue(ok) with open(os.path.join(d.path(), 'metadatatest.qmd'), 'rt') as f: metadata_xml = ''.join(f.readlines()) metadata3 = QgsLayerMetadata() doc = QDomDocument() doc.setContent(metadata_xml) self.assertTrue(metadata3.readMetadataXml(doc.documentElement())) self.assertEqual(metadata3.abstract(), 'my abstract 2') self.assertEqual(metadata3.identifier(), 'my identifier 2') self.assertEqual(metadata3.licenses(), ['l1', 'l2']) self.assertEqual(metadata3.history(), ['h1', 'h2']) def testSaveMetadataUnsupported(self): """ Test saving metadata to an unsupported URI """ metadata = QgsLayerMetadata() # this should raise a QgsNotSupportedException, as we don't support writing metadata to a WFS uri with self.assertRaises(QgsNotSupportedException): QgsProviderRegistry.instance().saveLayerMetadata('ogr', 'WFS:http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap', metadata) def testSaveDefaultMetadataUnsupported(self): """ Test saving default metadata to an unsupported layer """ layer = QgsVectorLayer('WFS:http://www2.dmsolutions.ca/cgi-bin/mswfs_gmap', 'test') # now save some metadata metadata = QgsLayerMetadata() metadata.setAbstract('my abstract') metadata.setIdentifier('my identifier') metadata.setLicenses(['l1', 'l2']) layer.setMetadata(metadata) # save as default msg, res = layer.saveDefaultMetadata() self.assertFalse(res) self.assertEqual(msg, 'Storing metadata for the specified uri is not supported') def testEmbeddedSymbolsKml(self): """ Test retrieving embedded symbols from a KML file """ layer = QgsVectorLayer(os.path.join(TEST_DATA_DIR, 'embedded_symbols', 'samples.kml') + '|layername=Paths', 'Lines') self.assertTrue(layer.isValid()) # symbols should not be fetched by default self.assertFalse(any(f.embeddedSymbol() for f in layer.getFeatures())) symbols = [f.embeddedSymbol().clone() if f.embeddedSymbol() else None for f in layer.getFeatures(QgsFeatureRequest().setFlags(QgsFeatureRequest.EmbeddedSymbols))] self.assertCountEqual([s.color().name() for s in symbols if s is not None], ['#ff00ff', '#ffff00', '#000000', '#ff0000']) self.assertCountEqual([s.color().alpha() for s in symbols if s is not None], [127, 135, 255, 127]) self.assertEqual(len([s for s in symbols if s is None]), 2) def testDecodeEncodeUriVsizip(self): """Test decodeUri/encodeUri for /vsizip/ prefixed URIs""" uri = '/vsizip//my/file.zip/shapefile.shp' parts = QgsProviderRegistry.instance().decodeUri('ogr', uri) self.assertEqual(parts, {'path': '/my/file.zip', 'layerName': None, 'layerId': None, 'vsiPrefix': '/vsizip/', 'vsiSuffix': '/shapefile.shp'}) encodedUri = QgsProviderRegistry.instance().encodeUri('ogr', parts) self.assertEqual(encodedUri, uri) uri = '/my/file.zip' parts = QgsProviderRegistry.instance().decodeUri('ogr', uri) self.assertEqual(parts, {'path': '/my/file.zip', 'layerName': None, 'layerId': None}) encodedUri = QgsProviderRegistry.instance().encodeUri('ogr', parts) self.assertEqual(encodedUri, uri) uri = '/vsizip//my/file.zip|layername=shapefile' parts = QgsProviderRegistry.instance().decodeUri('ogr', uri) self.assertEqual(parts, {'path': '/my/file.zip', 'layerName': 'shapefile', 'layerId': None, 'vsiPrefix': '/vsizip/'}) encodedUri = QgsProviderRegistry.instance().encodeUri('ogr', parts) self.assertEqual(encodedUri, uri) uri = '/vsizip//my/file.zip|layername=shapefile|subset="field"=\'value\'' parts = QgsProviderRegistry.instance().decodeUri('ogr', uri) self.assertEqual(parts, {'path': '/my/file.zip', 'layerName': 'shapefile', 'layerId': None, 'subset': '"field"=\'value\'', 'vsiPrefix': '/vsizip/'}) encodedUri = QgsProviderRegistry.instance().encodeUri('ogr', parts) self.assertEqual(encodedUri, uri) @unittest.skipIf(int(gdal.VersionInfo('VERSION_NUM')) < GDAL_COMPUTE_VERSION(3, 3, 0), "GDAL 3.3 required") def testFieldDomains(self): """ Test that field domains are translated from OGR where available (requires GDAL 3.3 or later) """ datasource = os.path.join(unitTestDataPath(), 'domains.gpkg') vl = QgsVectorLayer(datasource, 'test', 'ogr') self.assertTrue(vl.isValid()) fields = vl.fields() range_int_field = fields[fields.lookupField('with_range_domain_int')] range_int_setup = range_int_field.editorWidgetSetup() self.assertEqual(range_int_setup.type(), 'Range') self.assertTrue(range_int_setup.config()['AllowNull']) self.assertEqual(range_int_setup.config()['Max'], 2) self.assertEqual(range_int_setup.config()['Min'], 1) self.assertEqual(range_int_setup.config()['Precision'], 0) self.assertEqual(range_int_setup.config()['Step'], 1) self.assertEqual(range_int_setup.config()['Style'], 'SpinBox') # make sure editor widget config from provider has been copied to layer! self.assertEqual(vl.editorWidgetSetup(fields.lookupField('with_range_domain_int')).type(), 'Range') range_int64_field = fields[fields.lookupField('with_range_domain_int64')] range_int64_setup = range_int64_field.editorWidgetSetup() self.assertEqual(range_int64_setup.type(), 'Range') self.assertTrue(range_int64_setup.config()['AllowNull']) self.assertEqual(range_int64_setup.config()['Max'], 1234567890123) self.assertEqual(range_int64_setup.config()['Min'], -1234567890123) self.assertEqual(range_int64_setup.config()['Precision'], 0) self.assertEqual(range_int64_setup.config()['Step'], 1) self.assertEqual(range_int64_setup.config()['Style'], 'SpinBox') self.assertEqual(vl.editorWidgetSetup(fields.lookupField('with_range_domain_int64')).type(), 'Range') range_real_field = fields[fields.lookupField('with_range_domain_real')] range_real_setup = range_real_field.editorWidgetSetup() self.assertEqual(range_real_setup.type(), 'Range') self.assertTrue(range_real_setup.config()['AllowNull']) self.assertEqual(range_real_setup.config()['Max'], 2.5) self.assertEqual(range_real_setup.config()['Min'], 1.5) self.assertEqual(range_real_setup.config()['Precision'], 0) self.assertEqual(range_real_setup.config()['Step'], 1) self.assertEqual(range_real_setup.config()['Style'], 'SpinBox') self.assertEqual(vl.editorWidgetSetup(fields.lookupField('with_range_domain_real')).type(), 'Range') enum_field = fields[fields.lookupField('with_enum_domain')] enum_setup = enum_field.editorWidgetSetup() self.assertEqual(enum_setup.type(), 'ValueMap') self.assertTrue(enum_setup.config()['map'], [{'one': '1'}, {'2': '2'}]) self.assertEqual(vl.editorWidgetSetup(fields.lookupField('with_enum_domain')).type(), 'ValueMap') def test_provider_sublayer_details(self): """ Test retrieving sublayer details from data provider metadata """ metadata = QgsProviderRegistry.instance().providerMetadata('ogr') # invalid uri res = metadata.querySublayers('') self.assertFalse(res) # not a vector res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, 'landsat.tif')) self.assertFalse(res) # single layer vector res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, 'lines.shp')) self.assertEqual(len(res), 1) self.assertEqual(res[0].layerNumber(), 0) self.assertEqual(res[0].name(), "lines") self.assertEqual(res[0].description(), '') self.assertEqual(res[0].uri(), TEST_DATA_DIR + "/lines.shp") self.assertEqual(res[0].providerKey(), "ogr") self.assertEqual(res[0].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[0].wkbType(), QgsWkbTypes.LineString) self.assertEqual(res[0].geometryColumnName(), '') # make sure result is valid to load layer from options = QgsProviderSublayerDetails.LayerOptions(QgsCoordinateTransformContext()) vl = res[0].toLayer(options) self.assertTrue(vl.isValid()) # geopackage with two vector layers res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, "mixed_layers.gpkg")) self.assertEqual(len(res), 2) self.assertEqual(res[0].layerNumber(), 0) self.assertEqual(res[0].name(), "points") self.assertEqual(res[0].description(), "") self.assertEqual(res[0].uri(), "{}/mixed_layers.gpkg|layername=points".format(TEST_DATA_DIR)) self.assertEqual(res[0].providerKey(), "ogr") self.assertEqual(res[0].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[0].featureCount(), Qgis.FeatureCountState.Uncounted) self.assertEqual(res[0].wkbType(), QgsWkbTypes.Point) self.assertEqual(res[0].geometryColumnName(), 'geometry') vl = res[0].toLayer(options) self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), QgsWkbTypes.Point) self.assertEqual(res[1].layerNumber(), 1) self.assertEqual(res[1].name(), "lines") self.assertEqual(res[1].description(), "") self.assertEqual(res[1].uri(), "{}/mixed_layers.gpkg|layername=lines".format(TEST_DATA_DIR)) self.assertEqual(res[1].providerKey(), "ogr") self.assertEqual(res[1].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[1].featureCount(), Qgis.FeatureCountState.Uncounted) self.assertEqual(res[1].wkbType(), QgsWkbTypes.MultiLineString) self.assertEqual(res[1].geometryColumnName(), 'geom') vl = res[1].toLayer(options) self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), QgsWkbTypes.MultiLineString) # request feature count res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, "mixed_layers.gpkg"), Qgis.SublayerQueryFlag.CountFeatures) self.assertEqual(len(res), 2) self.assertEqual(res[0].name(), "points") self.assertEqual(res[0].featureCount(), 0) self.assertEqual(res[0].geometryColumnName(), 'geometry') self.assertEqual(res[1].name(), "lines") self.assertEqual(res[1].featureCount(), 6) self.assertEqual(res[1].geometryColumnName(), 'geom') # layer with mixed geometry types - without resolving geometry types res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, "mixed_types.TAB")) self.assertEqual(len(res), 1) self.assertEqual(res[0].layerNumber(), 0) self.assertEqual(res[0].name(), "mixed_types") self.assertEqual(res[0].description(), "") self.assertEqual(res[0].uri(), "{}/mixed_types.TAB".format(TEST_DATA_DIR)) self.assertEqual(res[0].providerKey(), "ogr") self.assertEqual(res[0].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[0].featureCount(), Qgis.FeatureCountState.Uncounted) self.assertEqual(res[0].wkbType(), QgsWkbTypes.Unknown) self.assertEqual(res[0].geometryColumnName(), '') vl = res[0].toLayer(options) self.assertTrue(vl.isValid()) # layer with mixed geometry types - without resolving geometry types, but with feature count res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, "mixed_types.TAB"), Qgis.SublayerQueryFlag.CountFeatures) self.assertEqual(len(res), 1) self.assertEqual(res[0].layerNumber(), 0) self.assertEqual(res[0].name(), "mixed_types") self.assertEqual(res[0].description(), "") self.assertEqual(res[0].uri(), "{}/mixed_types.TAB".format(TEST_DATA_DIR)) self.assertEqual(res[0].providerKey(), "ogr") self.assertEqual(res[0].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[0].featureCount(), 13) self.assertEqual(res[0].wkbType(), QgsWkbTypes.Unknown) self.assertEqual(res[0].geometryColumnName(), '') # layer with mixed geometry types - resolve geometry type (for OGR provider this implies also that we count features!) res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, "mixed_types.TAB"), Qgis.SublayerQueryFlag.ResolveGeometryType) self.assertEqual(len(res), 3) self.assertEqual(res[0].layerNumber(), 0) self.assertEqual(res[0].name(), "mixed_types") self.assertEqual(res[0].description(), "") self.assertEqual(res[0].uri(), "{}/mixed_types.TAB|geometrytype=Point".format(TEST_DATA_DIR)) self.assertEqual(res[0].providerKey(), "ogr") self.assertEqual(res[0].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[0].featureCount(), 4) self.assertEqual(res[0].wkbType(), QgsWkbTypes.Point) self.assertEqual(res[0].geometryColumnName(), '') vl = res[0].toLayer(options) self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), QgsWkbTypes.Point) self.assertEqual(res[1].layerNumber(), 0) self.assertEqual(res[1].name(), "mixed_types") self.assertEqual(res[1].description(), "") self.assertEqual(res[1].uri(), "{}/mixed_types.TAB|geometrytype=LineString".format(TEST_DATA_DIR)) self.assertEqual(res[1].providerKey(), "ogr") self.assertEqual(res[1].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[1].featureCount(), 4) self.assertEqual(res[1].wkbType(), QgsWkbTypes.LineString) self.assertEqual(res[1].geometryColumnName(), '') vl = res[1].toLayer(options) self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), QgsWkbTypes.LineString) self.assertEqual(res[2].layerNumber(), 0) self.assertEqual(res[2].name(), "mixed_types") self.assertEqual(res[2].description(), "") self.assertEqual(res[2].uri(), "{}/mixed_types.TAB|geometrytype=Polygon".format(TEST_DATA_DIR)) self.assertEqual(res[2].providerKey(), "ogr") self.assertEqual(res[2].type(), QgsMapLayerType.VectorLayer) self.assertEqual(res[2].featureCount(), 3) self.assertEqual(res[2].wkbType(), QgsWkbTypes.Polygon) self.assertEqual(res[2].geometryColumnName(), '') vl = res[2].toLayer(options) self.assertTrue(vl.isValid()) self.assertEqual(vl.wkbType(), QgsWkbTypes.Polygon) # spatialite res = metadata.querySublayers(os.path.join(TEST_DATA_DIR, "provider/spatialite.db")) self.assertCountEqual([{'name': r.name(), 'description': r.description(), 'uri': r.uri(), 'providerKey': r.providerKey(), 'wkbType': r.wkbType(), 'geomColName': r.geometryColumnName()} for r in res], [{'name': 'somedata', 'description': '', 'uri': '{}/provider/spatialite.db|layername=somedata'.format(TEST_DATA_DIR), 'providerKey': 'ogr', 'wkbType': 1, 'geomColName': 'geom'}, {'name': 'somepolydata', 'description': '', 'uri': '{}/provider/spatialite.db|layername=somepolydata'.format(TEST_DATA_DIR), 'providerKey': 'ogr', 'wkbType': 6, 'geomColName': 'geom'}, {'name': 'some data', 'description': '', 'uri': '{}/provider/spatialite.db|layername=some data'.format(TEST_DATA_DIR), 'providerKey': 'ogr', 'wkbType': 1, 'geomColName': 'geom'}, {'name': 'validator_project_test', 'description': '', 'uri': '{}/provider/spatialite.db|layername=validator_project_test'.format(TEST_DATA_DIR), 'providerKey': 'ogr', 'wkbType': 1, 'geomColName': 'geom'}, {'name': 'data_licenses', 'description': '', 'uri': '{}/provider/spatialite.db|layername=data_licenses'.format(TEST_DATA_DIR), 'providerKey': 'ogr', 'wkbType': 100, 'geomColName': ''}, {'name': 'some view', 'description': '', 'uri': '{}/provider/spatialite.db|layername=some view'.format(TEST_DATA_DIR), 'providerKey': 'ogr', 'wkbType': 100, 'geomColName': ''}]) if __name__ == '__main__': unittest.main()
gpl-2.0
piyushroshan/xen-4.3
tools/python/xen/remus/device.py
19
12280
# Remus device interface # # Coordinates with devices at suspend, resume, and commit hooks import os, re, fcntl import netlink, qdisc, util class ReplicatedDiskException(Exception): pass class BufferedNICException(Exception): pass class CheckpointedDevice(object): 'Base class for buffered devices' def postsuspend(self): 'called after guest has suspended' pass def preresume(self): 'called before guest resumes' pass def commit(self): 'called when backup has acknowledged checkpoint reception' pass class ReplicatedDisk(CheckpointedDevice): """ Send a checkpoint message to a replicated disk while the domain is paused between epochs. """ FIFODIR = '/var/run/tap' SEND_CHECKPOINT = 20 WAIT_CHECKPOINT_ACK = 30 def __init__(self, disk): # look up disk, make sure it is tap:buffer, and set up socket # to request commits. self.ctlfd = None self.msgfd = None self.is_drbd = False self.ackwait = False if disk.uname.startswith('tap:remus:') or disk.uname.startswith('tap:tapdisk:remus:'): fifo = re.match("tap:.*(remus.*)\|", disk.uname).group(1).replace(':', '_') absfifo = os.path.join(self.FIFODIR, fifo) absmsgfifo = absfifo + '.msg' self.installed = False self.ctlfd = open(absfifo, 'w+b') self.msgfd = open(absmsgfifo, 'r+b') elif disk.uname.startswith('drbd:'): #get the drbd device associated with this resource drbdres = re.match("drbd:(.*)", disk.uname).group(1) drbddev = util.runcmd("drbdadm sh-dev %s" % drbdres).rstrip() #check for remus supported drbd installation rconf = util.runcmd("drbdsetup %s show" % drbddev) if rconf.find('protocol D;') == -1: raise ReplicatedDiskException('Remus support for DRBD disks requires the ' 'resources to operate in protocol D. Please make ' 'sure that you have installed the remus supported DRBD ' 'version from git://aramis.nss.cs.ubc.ca/drbd-8.3-remus ' 'and enabled protocol D in the resource config') #check if resource is in connected state cstate = util.runcmd("drbdadm cstate %s" % drbdres).rstrip() if cstate != 'Connected': raise ReplicatedDiskException('DRBD resource %s is not in connected state!' % drbdres) #open a handle to the resource so that we could issue chkpt ioctls self.ctlfd = open(drbddev, 'r') self.is_drbd = True else: raise ReplicatedDiskException('Disk is not replicated: %s' % str(disk)) def __del__(self): self.uninstall() def uninstall(self): if self.ctlfd: self.ctlfd.close() self.ctlfd = None def postsuspend(self): if not self.is_drbd: os.write(self.ctlfd.fileno(), 'flush') elif not self.ackwait: if (fcntl.ioctl(self.ctlfd.fileno(), self.SEND_CHECKPOINT, 0) > 0): self.ackwait = False else: self.ackwait = True def preresume(self): if self.is_drbd and self.ackwait: fcntl.ioctl(self.ctlfd.fileno(), self.WAIT_CHECKPOINT_ACK, 0) self.ackwait = False def commit(self): if not self.is_drbd: msg = os.read(self.msgfd.fileno(), 4) if msg != 'done': print 'Unknown message: %s' % msg ### Network # shared rtnl handle _rth = None def getrth(): global _rth if not _rth: _rth = netlink.rtnl() return _rth class Netbuf(object): "Proxy for netdev with a queueing discipline" @staticmethod def devclass(): "returns the name of this device class" return 'unknown' @classmethod def available(cls): "returns True if this module can proxy the device" return cls._hasdev(cls.devclass()) def __init__(self, devname): self.devname = devname self.vif = None # override in subclasses def install(self, vif): "set up proxy on device" raise BufferedNICException('unimplemented') def uninstall(self): "remove proxy on device" raise BufferedNICException('unimplemented') # protected @staticmethod def _hasdev(devclass): """check for existence of device, attempting to load kernel module if not present""" devname = '%s0' % devclass rth = getrth() if rth.getlink(devname): return True if util.modprobe(devclass) and rth.getlink(devname): return True return False class IFBBuffer(Netbuf): """Capture packets arriving on a VIF using an ingress filter and tc mirred action to forward them to an IFB device. """ @staticmethod def devclass(): return 'ifb' def install(self, vif): self.vif = vif # voodoo from http://www.linuxfoundation.org/collaborate/workgroups/networking/ifb#Typical_Usage util.runcmd('ip link set %s up' % self.devname) try: util.runcmd('tc qdisc add dev %s ingress' % vif.dev) except util.PipeException, e: # check if error indicates that ingress qdisc # already exists on the vif. If so, ignore it. ignoreme = 'RTNETLINK answers: File exists' if ignoreme in str(e): pass else: raise e util.runcmd('tc filter add dev %s parent ffff: proto ip pref 10 ' 'u32 match u32 0 0 action mirred egress redirect ' 'dev %s' % (vif.dev, self.devname)) def uninstall(self): try: util.runcmd('tc qdisc del dev %s ingress' % self.vif.dev) except util.PipeException, e: pass util.runcmd('ip link set %s down' % self.devname) class IMQBuffer(Netbuf): """Redirect packets coming in on vif to an IMQ device.""" imqebt = '/usr/lib/xen/bin/imqebt' @staticmethod def devclass(): return 'imq' def install(self, vif): # stopgap hack to set up IMQ for an interface. Wrong in many ways. self.vif = vif for mod in ['imq', 'ebt_imq']: util.runcmd(['modprobe', mod]) util.runcmd("ip link set %s up" % self.devname) util.runcmd("%s -F FORWARD" % self.imqebt) util.runcmd("%s -A FORWARD -i %s -j imq --todev %s" % (self.imqebt, vif.dev, self.devname)) def uninstall(self): util.runcmd("%s -F FORWARD" % self.imqebt) util.runcmd('ip link set %s down' % self.devname) # in order of desirability netbuftypes = [IFBBuffer, IMQBuffer] def selectnetbuf(): "Find the best available buffer type" for driver in netbuftypes: if driver.available(): return driver raise BufferedNICException('no net buffer available') class Netbufpool(object): """Allocates/releases proxy netdevs (IMQ/IFB) A file contains a list of entries of the form <pid>:<device>\n To allocate a device, lock the file, then claim a new device if one is free. If there are no free devices, check each PID for liveness and take a device if the PID is dead, otherwise return failure. Add an entry to the file before releasing the lock. """ def __init__(self, netbufclass): "Create a pool of Device" self.netbufclass = netbufclass self.path = '/var/run/remus/' + self.netbufclass.devclass() self.devices = self.getdevs() pooldir = os.path.dirname(self.path) if not os.path.exists(pooldir): os.makedirs(pooldir, 0755) def get(self): "allocate a free device" def getfreedev(table): for dev in self.devices: if dev not in table or not util.checkpid(table[dev]): return dev return None lock = util.Lock(self.path) table = self.load() dev = getfreedev(table) if not dev: lock.unlock() raise BufferedNICException('no free devices') dev = self.netbufclass(dev) table[dev.devname] = os.getpid() self.save(table) lock.unlock() return dev def put(self, dev): "release claim on device" lock = util.Lock(self.path) table = self.load() del table[dev.devname] self.save(table) lock.unlock() # private def load(self): """load and parse allocation table""" table = {} if not os.path.exists(self.path): return table fd = open(self.path) for line in fd.readlines(): iface, pid = line.strip().split() table[iface] = int(pid) fd.close() return table def save(self, table): """write table to disk""" lines = ['%s %d\n' % (iface, table[iface]) for iface in sorted(table)] fd = open(self.path, 'w') fd.writelines(lines) fd.close() def getdevs(self): """find all available devices of our device type""" ifaces = [] for line in util.runcmd('ifconfig -a -s').splitlines(): iface = line.split()[0] if iface.startswith(self.netbufclass.devclass()): ifaces.append(iface) return ifaces class BufferedNIC(CheckpointedDevice): """ Buffer a protected domain's network output between rounds so that nothing is issued that a failover might not know about. """ def __init__(self, vif): self.installed = False self.vif = vif self.pool = Netbufpool(selectnetbuf()) self.rth = getrth() self.setup() def __del__(self): self.uninstall() def postsuspend(self): if not self.installed: self.install() self._sendqmsg(qdisc.TC_PLUG_BUFFER) def commit(self): '''Called when checkpoint has been acknowledged by the backup''' self._sendqmsg(qdisc.TC_PLUG_RELEASE_ONE) # private def _sendqmsg(self, action): self.q.action = action req = qdisc.changerequest(self.bufdevno, self.handle, self.q) self.rth.talk(req.pack()) return True def setup(self): """install Remus plug on VIF outbound traffic""" self.bufdev = self.pool.get() devname = self.bufdev.devname bufdev = self.rth.getlink(devname) if not bufdev: raise BufferedNICException('could not find device %s' % devname) self.bufdev.install(self.vif) self.bufdevno = bufdev['index'] self.handle = qdisc.TC_H_ROOT self.q = qdisc.PlugQdisc() if not util.modprobe('sch_plug'): raise BufferedNICException('could not load sch_plug module') def install(self): devname = self.bufdev.devname q = self.rth.getqdisc(self.bufdevno) if q: if q['kind'] == 'plug': self.installed = True return if q['kind'] not in ('ingress', 'pfifo_fast', 'mq'): raise BufferedNICException('there is already a queueing ' 'discipline %s on %s' % (q['kind'], devname)) print ('installing buffer on %s... ' % devname), req = qdisc.addrequest(self.bufdevno, self.handle, self.q) self.rth.talk(req.pack()) self.installed = True print 'done.' def uninstall(self): if self.installed: try: req = qdisc.delrequest(self.bufdevno, self.handle) self.rth.talk(req.pack()) except IOError, e: pass self.installed = False try: self.bufdev.uninstall() except util.PipeException, e: pass self.pool.put(self.bufdev)
gpl-2.0
repotvsupertuga/repo
plugin.video.TVsupertuga/resources/lib/sources/en/ymovies.py
7
10669
# -*- coding: utf-8 -*- ''' Exodus Add-on Copyright (C) 2016 Exodus 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 <http://www.gnu.org/licenses/>. ''' import re,urllib,urlparse,hashlib,random,string,json,base64,sys from resources.lib.modules import cleantitle from resources.lib.modules import client from resources.lib.modules import cache from resources.lib.modules import directstream from resources.lib.modules import jsunfuck CODE = '''def retA(): class Infix: def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __or__(self, other): return self.function(other) def __rlshift__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) def my_add(x, y): try: return x + y except Exception: return str(x) + str(y) x = Infix(my_add) return %s param = retA()''' class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['yesmovies.to'] self.base_link = 'https://yesmovies.to' self.search_link = '/movie/search/%s.html' self.info_link = '/ajax/movie_info/%s.html?is_login=false' self.server_link = '/ajax/v4_movie_episodes/%s' self.embed_link = '/ajax/movie_embed/%s' self.token_link = '/ajax/movie_token?eid=%s&mid=%s' self.source_link = '/ajax/movie_sources/%s?x=%s&y=%s' def matchAlias(self, title, aliases): try: for alias in aliases: if cleantitle.get(title) == cleantitle.get(alias['title']): return True except: return False def movie(self, imdb, title, localtitle, aliases, year): try: aliases.append({'country': 'us', 'title': title}) url = {'imdb': imdb, 'title': title, 'year': year, 'aliases': aliases} url = urllib.urlencode(url) return url except: return def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year): try: aliases.append({'country': 'us', 'title': tvshowtitle}) url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year, 'aliases': aliases} url = urllib.urlencode(url) return url except: return def episode(self, url, imdb, tvdb, title, premiered, season, episode): try: if url == None: return url = urlparse.parse_qs(url) url = dict([(i, url[i][0]) if url[i] else (i, '') for i in url]) url['title'], url['premiered'], url['season'], url['episode'] = title, premiered, season, episode url = urllib.urlencode(url) return url except: return def searchShow(self, title, season, aliases, headers): try: title = cleantitle.normalize(title) search = '%s Season %01d' % (title, int(season)) url = urlparse.urljoin(self.base_link, self.search_link % urllib.quote_plus(cleantitle.getsearch(search))) r = client.request(url, headers=headers, timeout='15') r = client.parseDOM(r, 'div', attrs={'class': 'ml-item'}) r = zip(client.parseDOM(r, 'a', ret='href'), client.parseDOM(r, 'a', ret='title')) r = [(i[0], i[1], re.findall('(.*?)\s+-\s+Season\s+(\d)', i[1])) for i in r] r = [(i[0], i[1], i[2][0]) for i in r if len(i[2]) > 0] url = [i[0] for i in r if self.matchAlias(i[2][0], aliases) and i[2][1] == season][0] return url except: return def searchMovie(self, title, year, aliases, headers): try: title = cleantitle.normalize(title) url = urlparse.urljoin(self.base_link, self.search_link % urllib.quote_plus(cleantitle.getsearch(title))) r = client.request(url, headers=headers, timeout='15') r = client.parseDOM(r, 'div', attrs={'class': 'ml-item'}) r = zip(client.parseDOM(r, 'a', ret='href'), client.parseDOM(r, 'a', ret='title')) results = [(i[0], i[1], re.findall('\((\d{4})', i[1])) for i in r] try: r = [(i[0], i[1], i[2][0]) for i in results if len(i[2]) > 0] url = [i[0] for i in r if self.matchAlias(i[1], aliases) and (year == i[2])][0] except: url = None pass if (url == None): url = [i[0] for i in results if self.matchAlias(i[1], aliases)][0] return url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] if url is None: return sources data = urlparse.parse_qs(url) data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data]) aliases = eval(data['aliases']) headers = {} if 'tvshowtitle' in data: episode = int(data['episode']) url = self.searchShow(data['tvshowtitle'], data['season'], aliases, headers) else: episode = 0 url = self.searchMovie(data['title'], data['year'], aliases, headers) mid = re.findall('-(\d+)', url)[-1] try: headers = {'Referer': url} u = urlparse.urljoin(self.base_link, self.server_link % mid) r = client.request(u, headers=headers, XHR=True) r = json.loads(r)['html'] r = client.parseDOM(r, 'div', attrs = {'class': 'pas-list'}) ids = client.parseDOM(r, 'li', ret='data-id') servers = client.parseDOM(r, 'li', ret='data-server') labels = client.parseDOM(r, 'a', ret='title') r = zip(ids, servers, labels) for eid in r: try: try: ep = re.findall('episode.*?(\d+).*?',eid[2].lower())[0] except: ep = 0 if (episode == 0) or (int(ep) == episode): url = urlparse.urljoin(self.base_link, self.token_link % (eid[0], mid)) script = client.request(url) if '$_$' in script: params = self.uncensored1(script) elif script.startswith('[]') and script.endswith('()'): params = self.uncensored2(script) elif '_x=' in script: x = re.search('''_x=['"]([^"']+)''', script).group(1) y = re.search('''_y=['"]([^"']+)''', script).group(1) params = {'x': x, 'y': y} else: raise Exception() u = urlparse.urljoin(self.base_link, self.source_link % (eid[0], params['x'], params['y'])) r = client.request(u, XHR=True) url = json.loads(r)['playlist'][0]['sources'] url = [i['file'] for i in url if 'file' in i] url = [directstream.googletag(i) for i in url] url = [i[0] for i in url if i] for s in url: sources.append({'source': 'gvideo', 'quality': s['quality'], 'language': 'en', 'url': s['url'], 'direct': True, 'debridonly': False}) except: pass except: pass return sources except: return sources def resolve(self, url): try: if self.embed_link in url: result = client.request(url, XHR=True) url = json.loads(result)['embed_url'] return url try: for i in range(3): u = directstream.googlepass(url) if not u == None: break return u except: return except: return def uncensored(a, b): x = '' ; i = 0 for i, y in enumerate(a): z = b[i % len(b) - 1] y = int(ord(str(y)[0])) + int(ord(str(z)[0])) x += chr(y) x = base64.b64encode(x) return x def uncensored1(self, script): try: script = '(' + script.split("(_$$)) ('_');")[0].split("/* `$$` */")[-1].strip() script = script.replace('(__$)[$$$]', '\'"\'') script = script.replace('(__$)[_$]', '"\\\\"') script = script.replace('(o^_^o)', '3') script = script.replace('(c^_^o)', '0') script = script.replace('(_$$)', '1') script = script.replace('($$_)', '4') vGlobals = {"__builtins__": None, '__name__': __name__, 'str': str, 'Exception': Exception} vLocals = {'param': None} exec (CODE % script.replace('+', '|x|'), vGlobals, vLocals) data = vLocals['param'].decode('string_escape') x = re.search('''_x=['"]([^"']+)''', data).group(1) y = re.search('''_y=['"]([^"']+)''', data).group(1) return {'x': x, 'y': y} except: pass def uncensored2(self, script): try: js = jsunfuck.JSUnfuck(script).decode() x = re.search('''_x=['"]([^"']+)''', js).group(1) y = re.search('''_y=['"]([^"']+)''', js).group(1) return {'x': x, 'y': y} except: pass
gpl-2.0
sidzan/netforce
netforce_account/netforce_account/tests/product_sale.py
4
3204
from netforce.test import TestCase from netforce.model import get_model from datetime import * import time class Test(TestCase): _name="product.sale" _description="Product sale invoice and payment" def test_run(self): # create invoice vals={ "type": "out", "inv_type": "invoice", "partner_id": get_model("partner").search([["name","=","ABC Food"]])[0], "date": time.strftime("%Y-%m-%d"), "due_date": (datetime.now()+timedelta(days=30)).strftime("%Y-%m-%d"), "tax_type": "tax_ex", "lines": [("create",{ "description": "Test product", "qty": 1, "unit_price": 1000, "account_id": get_model("account.account").search([["name","=","Sales Income"]])[0], "tax_id": get_model("account.tax.rate").search([["name","=","Sales Goods"]])[0], "amount": 1000, })], } inv_id=get_model("account.invoice").create(vals,context={"type":"out","inv_type":"invoice"}) get_model("account.invoice").post([inv_id]) inv=get_model("account.invoice").browse(inv_id) self.assertEqual(inv.state,"waiting_payment") self.assertIsNotNone(inv.tax_no) move=inv.move_id self.assertEqual(move.lines[0].account_id.name,"Account receivables - Trade") self.assertEqual(move.lines[0].debit,1070) self.assertEqual(move.lines[0].partner_id.id,vals["partner_id"]) self.assertEqual(move.lines[1].account_id.name,"Output Vat") self.assertEqual(move.lines[1].credit,70) self.assertEqual(move.lines[1].partner_id.id,vals["partner_id"]) self.assertEqual(move.lines[1].tax_comp_id.name,"Output VAT") self.assertEqual(move.lines[1].tax_base,1000) self.assertEqual(move.lines[1].tax_no,inv.tax_no) self.assertEqual(move.lines[2].account_id.name,"Sales Income") self.assertEqual(move.lines[2].credit,1000) # create payment vals={ "partner_id": get_model("partner").search([["name","=","ABC Food"]])[0], "type": "in", "pay_type": "invoice", "date": time.strftime("%Y-%m-%d"), "account_id": get_model("account.account").search([["name","=","Saving Account -Kbank"]])[0], "lines": [("create",{ "invoice_id": inv_id, "amount": 1070, })], } pmt_id=get_model("account.payment").create(vals,context={"type":"in"}) get_model("account.payment").post([pmt_id]) pmt=get_model("account.payment").browse(pmt_id) inv=get_model("account.invoice").browse(inv_id) self.assertEqual(pmt.state,"posted") self.assertEqual(inv.state,"paid") move=pmt.move_id self.assertEqual(move.lines[0].account_id.name,"Saving Account -Kbank") self.assertEqual(move.lines[0].debit,1070) self.assertEqual(move.lines[1].account_id.name,"Account receivables - Trade") self.assertEqual(move.lines[1].credit,1070) self.assertEqual(move.lines[1].partner_id.id,vals["partner_id"]) Test.register()
mit
hybrid-storage-dev/cinder-fs-111t-hybrid-cherry
backup/drivers/swift.py
2
24689
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P. # 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. """Implementation of a backup service that uses Swift as the backend **Related Flags** :backup_swift_url: The URL of the Swift endpoint (default: None, use catalog). :swift_catalog_info: Info to match when looking for swift in the service ' catalog. :backup_swift_object_size: The size in bytes of the Swift objects used for volume backups (default: 52428800). :backup_swift_retry_attempts: The number of retries to make for Swift operations (default: 10). :backup_swift_retry_backoff: The backoff time in seconds between retrying failed Swift operations (default: 10). :backup_compression_algorithm: Compression algorithm to use for volume backups. Supported options are: None (to disable), zlib and bz2 (default: zlib) """ import hashlib import json import os import socket import eventlet from oslo.config import cfg import six from swiftclient import client as swift from cinder.backup.driver import BackupDriver from cinder import exception from cinder.i18n import _ from cinder.openstack.common import excutils from cinder.openstack.common import log as logging from cinder.openstack.common import timeutils from cinder.openstack.common import units LOG = logging.getLogger(__name__) swiftbackup_service_opts = [ cfg.StrOpt('backup_swift_url', default=None, help='The URL of the Swift endpoint'), cfg.StrOpt('swift_catalog_info', default='object-store:swift:publicURL', help='Info to match when looking for swift in the service ' 'catalog. Format is: separated values of the form: ' '<service_type>:<service_name>:<endpoint_type> - ' 'Only used if backup_swift_url is unset'), cfg.StrOpt('backup_swift_auth', default='per_user', help='Swift authentication mechanism'), cfg.StrOpt('backup_swift_auth_version', default='1', help='Swift authentication version. Specify "1" for auth 1.0' ', or "2" for auth 2.0'), cfg.StrOpt('backup_swift_tenant', default=None, help='Swift tenant/account name. Required when connecting' ' to an auth 2.0 system'), cfg.StrOpt('backup_swift_user', default=None, help='Swift user name'), cfg.StrOpt('backup_swift_key', default=None, secret=True, help='Swift key for authentication'), cfg.StrOpt('backup_swift_container', default='volumebackups', help='The default Swift container to use'), cfg.IntOpt('backup_swift_object_size', default=52428800, help='The size in bytes of Swift backup objects'), cfg.IntOpt('backup_swift_retry_attempts', default=3, help='The number of retries to make for Swift operations'), cfg.IntOpt('backup_swift_retry_backoff', default=2, help='The backoff time in seconds between Swift retries'), cfg.StrOpt('backup_compression_algorithm', default='zlib', help='Compression algorithm (None to disable)'), ] CONF = cfg.CONF CONF.register_opts(swiftbackup_service_opts) class SwiftBackupDriver(BackupDriver): """Provides backup, restore and delete of backup objects within Swift.""" DRIVER_VERSION = '1.0.0' DRIVER_VERSION_MAPPING = {'1.0.0': '_restore_v1'} def _get_compressor(self, algorithm): try: if algorithm.lower() in ('none', 'off', 'no'): return None elif algorithm.lower() in ('zlib', 'gzip'): import zlib as compressor return compressor elif algorithm.lower() in ('bz2', 'bzip2'): import bz2 as compressor return compressor except ImportError: pass err = _('unsupported compression algorithm: %s') % algorithm raise ValueError(unicode(err)) def __init__(self, context, db_driver=None): super(SwiftBackupDriver, self).__init__(context, db_driver) if CONF.backup_swift_url is None: self.swift_url = None info = CONF.swift_catalog_info try: service_type, service_name, endpoint_type = info.split(':') except ValueError: raise exception.BackupDriverException(_( "Failed to parse the configuration option " "'swift_catalog_info', must be in the form " "<service_type>:<service_name>:<endpoint_type>")) for entry in context.service_catalog: if entry.get('type') == service_type: self.swift_url = entry.get( 'endpoints')[0].get(endpoint_type) else: self.swift_url = '%s%s' % (CONF.backup_swift_url, context.project_id) if self.swift_url is None: raise exception.BackupDriverException(_( "Could not determine which Swift endpoint to use. This can " " either be set in the service catalog or with the " " cinder.conf config option 'backup_swift_url'.")) LOG.debug("Using swift URL %s", self.swift_url) self.az = CONF.storage_availability_zone self.data_block_size_bytes = CONF.backup_swift_object_size self.swift_attempts = CONF.backup_swift_retry_attempts self.swift_backoff = CONF.backup_swift_retry_backoff self.compressor = \ self._get_compressor(CONF.backup_compression_algorithm) LOG.debug('Connect to %s in "%s" mode' % (CONF.backup_swift_url, CONF.backup_swift_auth)) if CONF.backup_swift_auth == 'single_user': if CONF.backup_swift_user is None: LOG.error(_("single_user auth mode enabled, " "but %(param)s not set") % {'param': 'backup_swift_user'}) raise exception.ParameterNotFound(param='backup_swift_user') self.conn = swift.Connection( authurl=CONF.backup_swift_url, auth_version=CONF.backup_swift_auth_version, tenant_name=CONF.backup_swift_tenant, user=CONF.backup_swift_user, key=CONF.backup_swift_key, retries=self.swift_attempts, starting_backoff=self.swift_backoff) else: self.conn = swift.Connection(retries=self.swift_attempts, preauthurl=self.swift_url, preauthtoken=self.context.auth_token, starting_backoff=self.swift_backoff) def _create_container(self, context, backup): backup_id = backup['id'] container = backup['container'] LOG.debug('_create_container started, container: %(container)s,' 'backup: %(backup_id)s' % {'container': container, 'backup_id': backup_id}) if container is None: container = CONF.backup_swift_container self.db.backup_update(context, backup_id, {'container': container}) # NOTE(gfidente): accordingly to the Object Storage API reference, we # do not need to check if a container already exists, container PUT # requests are idempotent and a code of 202 (Accepted) is returned when # the container already existed. self.conn.put_container(container) return container def _generate_swift_object_name_prefix(self, backup): az = 'az_%s' % self.az backup_name = '%s_backup_%s' % (az, backup['id']) volume = 'volume_%s' % (backup['volume_id']) timestamp = timeutils.strtime(fmt="%Y%m%d%H%M%S") prefix = volume + '/' + timestamp + '/' + backup_name LOG.debug('_generate_swift_object_name_prefix: %s' % prefix) return prefix def _generate_object_names(self, backup): prefix = backup['service_metadata'] swift_objects = self.conn.get_container(backup['container'], prefix=prefix, full_listing=True)[1] swift_object_names = [swift_obj['name'] for swift_obj in swift_objects] LOG.debug('generated object list: %s' % swift_object_names) return swift_object_names def _metadata_filename(self, backup): swift_object_name = backup['service_metadata'] filename = '%s_metadata' % swift_object_name return filename def _write_metadata(self, backup, volume_id, container, object_list, volume_meta): filename = self._metadata_filename(backup) LOG.debug('_write_metadata started, container name: %(container)s,' ' metadata filename: %(filename)s' % {'container': container, 'filename': filename}) metadata = {} metadata['version'] = self.DRIVER_VERSION metadata['backup_id'] = backup['id'] metadata['volume_id'] = volume_id metadata['backup_name'] = backup['display_name'] metadata['backup_description'] = backup['display_description'] metadata['created_at'] = str(backup['created_at']) metadata['objects'] = object_list metadata['volume_meta'] = volume_meta metadata_json = json.dumps(metadata, sort_keys=True, indent=2) reader = six.StringIO(metadata_json) etag = self.conn.put_object(container, filename, reader, content_length=reader.len) md5 = hashlib.md5(metadata_json).hexdigest() if etag != md5: err = _('error writing metadata file to swift, MD5 of metadata' ' file in swift [%(etag)s] is not the same as MD5 of ' 'metadata file sent to swift [%(md5)s]') % {'etag': etag, 'md5': md5} raise exception.InvalidBackup(reason=err) LOG.debug('_write_metadata finished') def _read_metadata(self, backup): container = backup['container'] filename = self._metadata_filename(backup) LOG.debug('_read_metadata started, container name: %(container)s, ' 'metadata filename: %(filename)s' % {'container': container, 'filename': filename}) (resp, body) = self.conn.get_object(container, filename) metadata = json.loads(body) LOG.debug('_read_metadata finished (%s)' % metadata) return metadata def _prepare_backup(self, backup): """Prepare the backup process and return the backup metadata.""" backup_id = backup['id'] volume_id = backup['volume_id'] volume = self.db.volume_get(self.context, volume_id) if volume['size'] <= 0: err = _('volume size %d is invalid.') % volume['size'] raise exception.InvalidVolume(reason=err) try: container = self._create_container(self.context, backup) except socket.error as err: raise exception.SwiftConnectionFailed(reason=err) object_prefix = self._generate_swift_object_name_prefix(backup) backup['service_metadata'] = object_prefix self.db.backup_update(self.context, backup_id, {'service_metadata': object_prefix}) volume_size_bytes = volume['size'] * units.Gi availability_zone = self.az LOG.debug('starting backup of volume: %(volume_id)s to swift,' ' volume size: %(volume_size_bytes)d, swift object names' ' prefix %(object_prefix)s, availability zone:' ' %(availability_zone)s' % { 'volume_id': volume_id, 'volume_size_bytes': volume_size_bytes, 'object_prefix': object_prefix, 'availability_zone': availability_zone, }) object_meta = {'id': 1, 'list': [], 'prefix': object_prefix, 'volume_meta': None} return object_meta, container def _backup_chunk(self, backup, container, data, data_offset, object_meta): """Backup data chunk based on the object metadata and offset.""" object_prefix = object_meta['prefix'] object_list = object_meta['list'] object_id = object_meta['id'] object_name = '%s-%05d' % (object_prefix, object_id) obj = {} obj[object_name] = {} obj[object_name]['offset'] = data_offset obj[object_name]['length'] = len(data) LOG.debug('reading chunk of data from volume') if self.compressor is not None: algorithm = CONF.backup_compression_algorithm.lower() obj[object_name]['compression'] = algorithm data_size_bytes = len(data) data = self.compressor.compress(data) comp_size_bytes = len(data) LOG.debug('compressed %(data_size_bytes)d bytes of data ' 'to %(comp_size_bytes)d bytes using ' '%(algorithm)s' % { 'data_size_bytes': data_size_bytes, 'comp_size_bytes': comp_size_bytes, 'algorithm': algorithm, }) else: LOG.debug('not compressing data') obj[object_name]['compression'] = 'none' reader = six.StringIO(data) LOG.debug('About to put_object') try: etag = self.conn.put_object(container, object_name, reader, content_length=len(data)) except socket.error as err: raise exception.SwiftConnectionFailed(reason=err) LOG.debug('swift MD5 for %(object_name)s: %(etag)s' % {'object_name': object_name, 'etag': etag, }) md5 = hashlib.md5(data).hexdigest() obj[object_name]['md5'] = md5 LOG.debug('backup MD5 for %(object_name)s: %(md5)s' % {'object_name': object_name, 'md5': md5}) if etag != md5: err = _('error writing object to swift, MD5 of object in ' 'swift %(etag)s is not the same as MD5 of object sent ' 'to swift %(md5)s') % {'etag': etag, 'md5': md5} raise exception.InvalidBackup(reason=err) object_list.append(obj) object_id += 1 object_meta['list'] = object_list object_meta['id'] = object_id LOG.debug('Calling eventlet.sleep(0)') eventlet.sleep(0) def _finalize_backup(self, backup, container, object_meta): """Finalize the backup by updating its metadata on Swift.""" object_list = object_meta['list'] object_id = object_meta['id'] volume_meta = object_meta['volume_meta'] try: self._write_metadata(backup, backup['volume_id'], container, object_list, volume_meta) except socket.error as err: raise exception.SwiftConnectionFailed(reason=err) self.db.backup_update(self.context, backup['id'], {'object_count': object_id}) LOG.debug('backup %s finished.' % backup['id']) def _backup_metadata(self, backup, object_meta): """Backup volume metadata. NOTE(dosaboy): the metadata we are backing up is obtained from a versioned api so we should not alter it in any way here. We must also be sure that the service that will perform the restore is compatible with version used. """ json_meta = self.get_metadata(backup['volume_id']) if not json_meta: LOG.debug("No volume metadata to backup") return object_meta["volume_meta"] = json_meta def backup(self, backup, volume_file, backup_metadata=True): """Backup the given volume to Swift.""" object_meta, container = self._prepare_backup(backup) while True: data = volume_file.read(self.data_block_size_bytes) data_offset = volume_file.tell() if data == '': break self._backup_chunk(backup, container, data, data_offset, object_meta) if backup_metadata: try: self._backup_metadata(backup, object_meta) except Exception as err: with excutils.save_and_reraise_exception(): LOG.exception( _("Backup volume metadata to swift failed: %s") % six.text_type(err)) self.delete(backup) self._finalize_backup(backup, container, object_meta) def _restore_v1(self, backup, volume_id, metadata, volume_file): """Restore a v1 swift volume backup from swift.""" backup_id = backup['id'] LOG.debug('v1 swift volume backup restore of %s started', backup_id) container = backup['container'] metadata_objects = metadata['objects'] metadata_object_names = sum((obj.keys() for obj in metadata_objects), []) LOG.debug('metadata_object_names = %s' % metadata_object_names) prune_list = [self._metadata_filename(backup)] swift_object_names = [swift_object_name for swift_object_name in self._generate_object_names(backup) if swift_object_name not in prune_list] if sorted(swift_object_names) != sorted(metadata_object_names): err = _('restore_backup aborted, actual swift object list in ' 'swift does not match object list stored in metadata') raise exception.InvalidBackup(reason=err) for metadata_object in metadata_objects: object_name = metadata_object.keys()[0] LOG.debug('restoring object from swift. backup: %(backup_id)s, ' 'container: %(container)s, swift object name: ' '%(object_name)s, volume: %(volume_id)s' % { 'backup_id': backup_id, 'container': container, 'object_name': object_name, 'volume_id': volume_id, }) try: (resp, body) = self.conn.get_object(container, object_name) except socket.error as err: raise exception.SwiftConnectionFailed(reason=err) compression_algorithm = metadata_object[object_name]['compression'] decompressor = self._get_compressor(compression_algorithm) if decompressor is not None: LOG.debug('decompressing data using %s algorithm' % compression_algorithm) decompressed = decompressor.decompress(body) volume_file.write(decompressed) else: volume_file.write(body) # force flush every write to avoid long blocking write on close volume_file.flush() # Be tolerant to IO implementations that do not support fileno() try: fileno = volume_file.fileno() except IOError: LOG.info("volume_file does not support fileno() so skipping " "fsync()") else: os.fsync(fileno) # Restoring a backup to a volume can take some time. Yield so other # threads can run, allowing for among other things the service # status to be updated eventlet.sleep(0) LOG.debug('v1 swift volume backup restore of %s finished', backup_id) def restore(self, backup, volume_id, volume_file): """Restore the given volume backup from swift.""" backup_id = backup['id'] container = backup['container'] object_prefix = backup['service_metadata'] LOG.debug('starting restore of backup %(object_prefix)s from swift' ' container: %(container)s, to volume %(volume_id)s, ' 'backup: %(backup_id)s' % { 'object_prefix': object_prefix, 'container': container, 'volume_id': volume_id, 'backup_id': backup_id, }) try: metadata = self._read_metadata(backup) except socket.error as err: raise exception.SwiftConnectionFailed(reason=err) metadata_version = metadata['version'] LOG.debug('Restoring swift backup version %s', metadata_version) try: restore_func = getattr(self, self.DRIVER_VERSION_MAPPING.get( metadata_version)) except TypeError: err = (_('No support to restore swift backup version %s') % metadata_version) raise exception.InvalidBackup(reason=err) restore_func(backup, volume_id, metadata, volume_file) volume_meta = metadata.get('volume_meta', None) try: if volume_meta: self.put_metadata(volume_id, volume_meta) else: LOG.debug("No volume metadata in this backup") except exception.BackupMetadataUnsupportedVersion: msg = _("Metadata restore failed due to incompatible version") LOG.error(msg) raise exception.BackupOperationError(msg) LOG.debug('restore %(backup_id)s to %(volume_id)s finished.' % {'backup_id': backup_id, 'volume_id': volume_id}) def delete(self, backup): """Delete the given backup from swift.""" container = backup['container'] LOG.debug('delete started, backup: %s, container: %s, prefix: %s', backup['id'], container, backup['service_metadata']) if container is not None: swift_object_names = [] try: swift_object_names = self._generate_object_names(backup) except Exception: LOG.warn(_('swift error while listing objects, continuing' ' with delete')) for swift_object_name in swift_object_names: try: self.conn.delete_object(container, swift_object_name) except socket.error as err: raise exception.SwiftConnectionFailed(reason=err) except Exception: LOG.warn(_('swift error while deleting object %s, ' 'continuing with delete') % swift_object_name) else: LOG.debug('deleted swift object: %(swift_object_name)s' ' in container: %(container)s' % { 'swift_object_name': swift_object_name, 'container': container }) # Deleting a backup's objects from swift can take some time. # Yield so other threads can run eventlet.sleep(0) LOG.debug('delete %s finished' % backup['id']) def get_backup_driver(context): return SwiftBackupDriver(context)
apache-2.0
maniteja123/numpy
numpy/f2py/tests/test_return_character.py
130
3967
from __future__ import division, absolute_import, print_function from numpy import array from numpy.compat import asbytes from numpy.testing import run_module_suite, assert_, dec import util class TestReturnCharacter(util.F2PyTest): def check_function(self, t): tname = t.__doc__.split()[0] if tname in ['t0', 't1', 's0', 's1']: assert_(t(23) == asbytes('2')) r = t('ab') assert_(r == asbytes('a'), repr(r)) r = t(array('ab')) assert_(r == asbytes('a'), repr(r)) r = t(array(77, 'u1')) assert_(r == asbytes('M'), repr(r)) #assert_(_raises(ValueError, t, array([77,87]))) #assert_(_raises(ValueError, t, array(77))) elif tname in ['ts', 'ss']: assert_(t(23) == asbytes('23 '), repr(t(23))) assert_(t('123456789abcdef') == asbytes('123456789a')) elif tname in ['t5', 's5']: assert_(t(23) == asbytes('23 '), repr(t(23))) assert_(t('ab') == asbytes('ab '), repr(t('ab'))) assert_(t('123456789abcdef') == asbytes('12345')) else: raise NotImplementedError class TestF77ReturnCharacter(TestReturnCharacter): code = """ function t0(value) character value character t0 t0 = value end function t1(value) character*1 value character*1 t1 t1 = value end function t5(value) character*5 value character*5 t5 t5 = value end function ts(value) character*(*) value character*(*) ts ts = value end subroutine s0(t0,value) character value character t0 cf2py intent(out) t0 t0 = value end subroutine s1(t1,value) character*1 value character*1 t1 cf2py intent(out) t1 t1 = value end subroutine s5(t5,value) character*5 value character*5 t5 cf2py intent(out) t5 t5 = value end subroutine ss(ts,value) character*(*) value character*10 ts cf2py intent(out) ts ts = value end """ @dec.slow def test_all(self): for name in "t0,t1,t5,s0,s1,s5,ss".split(","): self.check_function(getattr(self.module, name)) class TestF90ReturnCharacter(TestReturnCharacter): suffix = ".f90" code = """ module f90_return_char contains function t0(value) character :: value character :: t0 t0 = value end function t0 function t1(value) character(len=1) :: value character(len=1) :: t1 t1 = value end function t1 function t5(value) character(len=5) :: value character(len=5) :: t5 t5 = value end function t5 function ts(value) character(len=*) :: value character(len=10) :: ts ts = value end function ts subroutine s0(t0,value) character :: value character :: t0 !f2py intent(out) t0 t0 = value end subroutine s0 subroutine s1(t1,value) character(len=1) :: value character(len=1) :: t1 !f2py intent(out) t1 t1 = value end subroutine s1 subroutine s5(t5,value) character(len=5) :: value character(len=5) :: t5 !f2py intent(out) t5 t5 = value end subroutine s5 subroutine ss(ts,value) character(len=*) :: value character(len=10) :: ts !f2py intent(out) ts ts = value end subroutine ss end module f90_return_char """ @dec.slow def test_all(self): for name in "t0,t1,t5,ts,s0,s1,s5,ss".split(","): self.check_function(getattr(self.module.f90_return_char, name)) if __name__ == "__main__": run_module_suite()
bsd-3-clause
NoctuaNivalis/qutebrowser
tests/unit/utils/usertypes/test_timer.py
4
2427
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Tests for Timer.""" from qutebrowser.utils import usertypes import pytest from PyQt5.QtCore import QObject class Parent(QObject): """Class for test_parent().""" pass def test_parent(): """Make sure the parent is set correctly.""" parent = Parent() t = usertypes.Timer(parent) assert t.parent() is parent def test_named(): """Make sure the name is set correctly.""" t = usertypes.Timer(name='foobar') assert t._name == 'foobar' assert t.objectName() == 'foobar' assert repr(t) == "<qutebrowser.utils.usertypes.Timer name='foobar'>" def test_unnamed(): """Make sure an unnamed Timer is named correctly.""" t = usertypes.Timer() assert not t.objectName() assert t._name == 'unnamed' assert repr(t) == "<qutebrowser.utils.usertypes.Timer name='unnamed'>" def test_set_interval_overflow(): """Make sure setInterval raises OverflowError with very big numbers.""" t = usertypes.Timer() with pytest.raises(OverflowError): t.setInterval(2 ** 64) def test_start_overflow(): """Make sure start raises OverflowError with very big numbers.""" t = usertypes.Timer() with pytest.raises(OverflowError): t.start(2 ** 64) def test_timeout_start(qtbot): """Make sure the timer works with start().""" t = usertypes.Timer() with qtbot.waitSignal(t.timeout, timeout=3000): t.start(200) def test_timeout_set_interval(qtbot): """Make sure the timer works with setInterval().""" t = usertypes.Timer() with qtbot.waitSignal(t.timeout, timeout=3000): t.setInterval(200) t.start()
gpl-3.0
gpoesia/servo
tests/wpt/css-tests/tools/html5lib/html5lib/treewalkers/__init__.py
1229
2323
"""A collection of modules for iterating through different kinds of tree, generating tokens identical to those produced by the tokenizer module. To create a tree walker for a new type of tree, you need to do implement a tree walker object (called TreeWalker by convention) that implements a 'serialize' method taking a tree as sole argument and returning an iterator generating tokens. """ from __future__ import absolute_import, division, unicode_literals import sys from ..utils import default_etree treeWalkerCache = {} def getTreeWalker(treeType, implementation=None, **kwargs): """Get a TreeWalker class for various types of tree with built-in support treeType - the name of the tree type required (case-insensitive). Supported values are: "dom" - The xml.dom.minidom DOM implementation "pulldom" - The xml.dom.pulldom event stream "etree" - A generic walker for tree implementations exposing an elementtree-like interface (known to work with ElementTree, cElementTree and lxml.etree). "lxml" - Optimized walker for lxml.etree "genshi" - a Genshi stream implementation - (Currently applies to the "etree" tree type only). A module implementing the tree type e.g. xml.etree.ElementTree or cElementTree.""" treeType = treeType.lower() if treeType not in treeWalkerCache: if treeType in ("dom", "pulldom"): name = "%s.%s" % (__name__, treeType) __import__(name) mod = sys.modules[name] treeWalkerCache[treeType] = mod.TreeWalker elif treeType == "genshi": from . import genshistream treeWalkerCache[treeType] = genshistream.TreeWalker elif treeType == "lxml": from . import lxmletree treeWalkerCache[treeType] = lxmletree.TreeWalker elif treeType == "etree": from . import etree if implementation is None: implementation = default_etree # XXX: NEVER cache here, caching is done in the etree submodule return etree.getETreeModule(implementation, **kwargs).TreeWalker return treeWalkerCache.get(treeType)
mpl-2.0
stoeps13/ibmcnxscripting
WebSphere/cnxMemberCheckExIDByEmail.py
1
2934
# To run this script with Windows or SLES, you have to modify setupCmdLine # # setupCmdLine.bat|sh # add on line 40: "SET WAS_USER_SCRIPT=d:\ibm\wasuserscript.cmd" # # Create d:\ibm\wasuserscript.cmd: # "SET WAS_EXT_DIRS=%WAS_EXT_DIRS%;c:\ibm\sqllib\java" # import os import sys from java.util import Properties # Load all jython commands, when they are not loaded try: NewsActivityStreamService.listApplicationRegistrations() except NameError: print "Connections Commands not loaded! Load now: " execfile("loadAll.py") # add the jar to your classpath, then import it # better to read WebSphere variable PROFILES_JDBC_DRIVER_HOME import com.ibm.db2.jcc.DB2Driver as Driver # Change User and Password props = Properties() props.put( 'user', 'lcuser' ) props.put( 'password', 'password' ) # Change Hostname, Port and maybe DB Name conn = Driver().connect( 'jdbc:db2://cnxdb2.stoeps.local:50000/PEOPLEDB', props ) stmt = conn.createStatement() email = raw_input( "Mail address of profile you want to check: " ).lower() sql = 'select PROF_UID_LOWER,PROF_MAIL_LOWER,PROF_GUID,PROF_MAIL from empinst.employee where PROF_MAIL_LOWER = \'' + email + '\' order by PROF_UID_LOWER' rs = stmt.executeQuery( sql ) employeeList = [] while ( rs.next() ): row = {} row['PROF_UID_LOWER'] = rs.getString( 1 ) row['PROF_MAIL_LOWER'] = rs.getString( 2 ) row['PROF_GUID'] = rs.getString( 3 ) row['PROF_MAIL'] = rs.getString( 4 ) employeeList.append( row ) rs.close() stmt.close() conn.close() # print the result for e in employeeList: # print e['PROF_UID_LOWER'] + "\t\t" + e['PROF_MAIL_LOWER'] + "\t\t" + e['PROF_GUID'] # print e['PROF_MAIL'] print "Profiles:\t\t\t " + e['PROF_GUID'] LOGIN = e['PROF_MAIL'] try: print "Activities:\t\t\t", ActivitiesMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "Blogs:\t\t\t\t", BlogsMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "Communities:\t\t\t", CommunitiesMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "Dogear:\t\t\t\t", DogearMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "Files:\t\t\t\t", FilesMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "Forums:\t\t\t\t", ForumsMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "News, Search, Homepage:\t\t", NewsMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found' try: print "Wikis:\t\t\t\t", WikisMemberService.getMemberExtIdByLogin( LOGIN ) except: print 'No user with Login ' + LOGIN + ' found'
apache-2.0
mitre/hybrid-curation
src/unbundle-hits.py
1
7869
import sys import re import codecs import types import csv import json import optparse import fileinput import collections import datetime import time """ Essentially reverses the process of bundle-items. Processes the CSV download from MTurk and bursts out multiple items in each HIT. Each field name that ends in "_1", "_2" etc is assumed to be such a multiplexed field. Any other fields will be repeated in the output. Can produce JSON format rather than CSV if desired. """ csv.field_size_limit(10**6) ###################################################################### def maybeOpen (file, mode="r", encoding="utf8"): if type(file) is types.StringType: file = open(file, mode) if encoding: file = (mode == "r" and codecs.getreader or codecs.getwriter)(encoding)(file) return file ###################################################################### # class batchFileReader: # def __init__ (self, file): # self.csvReader = csv.DictReader(maybeOpen(file, "r", None)) # wsRE = re.compile(r"\s") # re.U # NO!!! # def __iter__ (self): # n = 0 # for row in self.csvReader: # n += 1 # for key, old in row.items(): # if old: # new = self.wsRE.sub(" ", row[key]) # if new is not old: # row[key] = new # yield row # # print >>sys.stderr, self, self.csvReader.fieldnames # print >>sys.stderr, "%s: %d" % (self, n) wsRE = re.compile(r"\s") # re.U # NO!!! def readBatchFile (input): n = 0 for n, row in enumerate(csv.DictReader(input), 1): for key, old in row.items(): if old: new = wsRE.sub(" ", row[key]) if new is not old: row[key] = new yield row # print >>sys.stderr, self, self.csvReader.fieldnames print >>sys.stderr, "%d batch items read" % n # class hitUnbundler: # def __init__ (self, source, burstplain=False, addSequenceID=False): # self.source = source # self.addSequenceID = addSequenceID # self.splitKeyRE = re.compile(burstplain and "^(.*[^0-9])([0-9]+)$" or "^(.+)_([0-9]+)$", # re.U | re.I) def burstBundle (bundle, splitKeyRE): burst = {} # Maps sequence number to attributes with that numeric suffix shared = {} # Attributes without a numeric suffix for key in bundle: m = splitKeyRE.match(key) if m: newKey, index = m.groups() index = int(index) assert(index > 0) subBundle = burst.get(index, None) if not subBundle: burst[index] = subBundle = {} subBundle[newKey] = bundle[key] else: shared[key] = bundle[key] return burst, shared def unbundleHITs (source, burstplain=False, addSequenceID=False): splitKeyRE = re.compile(burstplain and "^(.*[^0-9])([0-9]+)$" or "^(.+)_([0-9]+)$", re.U | re.I) nIn = nOut = 0 # indexCount = {} for bundle in source: nIn += 1 # tempIndex = {} # for index in tempIndex: # indexCount[index] = indexCount.get(index, 0) + 1 burst, shared = burstBundle(bundle, splitKeyRE) if addSequenceID: for index, subBundle in burst.iteritems(): subBundle["sequenceID"] = index for item in burst.values() or [{}]: # Add the shared ones back in to the burst items # print >>sys.stderr, "Burst item:", item for key in shared: if item.has_key(key): print >>sys.stderr, "Collision: %s=%s %s_n=%s" % (key, shared[key], key, item[key]) item[key] = shared[key] nOut += 1 yield item print >>sys.stderr, "%s: %d => %d" % ("unbundle", nIn, nOut) def adjustTimes (bundles): groups = collections.defaultdict(list) for b in bundles: # Clip out the timezone, which is not reliably parsed by strptime aTime, sTime = map(lambda t: time.mktime(datetime.datetime.strptime(t[:-8] + t[-5:], "%a %b %d %H:%M:%S %Y").timetuple()), (b["AcceptTime"], b["SubmitTime"])) groups[b["WorkerId"]].append((sTime, aTime, b)) origWorktime = adjustedWorktime = 0 for workerID, bundles in groups.iteritems(): lastSubmit = 0 bundles.sort() for i, (sTime, aTime, b) in enumerate(bundles): b["AdjustedWorkTime"] = sTime - max(aTime, lastSubmit) assert b["AdjustedWorkTime"] >= 0 # if b["AdjustedWorkTime"] == 0: # print >>sys.stderr, "Zero work time!!! (%s %s), (%s %s)" % (bundles[i - 1][-1]["AcceptTime"], bundles[i - 1][-1]["SubmitTime"], b["AcceptTime"], b["SubmitTime"]) lastSubmit = sTime class tabItemWriter: def __init__ (self, file): self.file = maybeOpen(file, "w", None) # Hacky stuff to make some columns come first keyWeights = [(1, re.compile("^answer[.]", re.I | re.U)), (2, re.compile("^input[.]", re.I | re.U)), ] knowns = "itemID en fr1 score1 fr2 score2 fr3 score3 control_wrong control_right".split() for i in xrange(len(knowns)): keyWeights.append((100 + i, re.compile("^%s$" % knowns[i]))) keyWeights.append((1000, None)) self.keyWeights = keyWeights def sortKeys (self, keys): weightedKeys = [] for key in keys: for weight, pattern in self.keyWeights: if not pattern or pattern.match(key): weightedKeys.append((weight, key)) break keys = weightedKeys keys.sort() # keys.reverse() return [key for (weight, key) in keys] def writeAll (self, source): source = iter(source) firstItem = source.next() keys = self.sortKeys(firstItem.keys()) print >>self.file, "\t".join(keys) for fake in ((firstItem, ), source): for item in fake: print >>self.file, "\t".join([str(item.get(key, "EMPTY")) for key in keys]) class jsonItemWriter: def __init__ (self, file): self.file = maybeOpen(file, "w", None) def writeAll (self, source): for item in source: print >>self.file, json.dumps(item, sort_keys=True) ###################################################################### optparser = optparse.OptionParser() optparser.add_option("-v", "--verbose", dest="verbose", action = "count", help = "More verbose output") optparser.add_option("--plain", action="store_true", help="Burst keys that end in digits; Default is to burst keys that end in underscore-digit") optparser.add_option("--addseq", action="store_true", help="Add a sequence ID to the burst items") optparser.add_option("--json", action="store_true", help="Produce json output rather than tab-sep") (options, args) = optparser.parse_args() # (infile, ) = args or (None, ) # infile = infile in ("-", None) and sys.stdin or open(infile, "r") bundles = list(readBatchFile(fileinput.input(args))) adjustTimes(bundles) print >>sys.stderr, "Average adjusted worktime %.1fs" % (sum(b["AdjustedWorkTime"] for b in bundles)/(len(bundles) or 1)) items = unbundleHITs(bundles, burstplain=options.plain, addSequenceID=options.addseq) writer = (options.json and jsonItemWriter or tabItemWriter)(sys.stdout) writer.writeAll(items) ######################################################################
apache-2.0
inovtec-solutions/OpenERP
openerp/addons/hr/__init__.py
54
1096
# -*- 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/>. # ############################################################################## import hr_department import hr import res_config # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ronin-gw/cqstat
cqstat/setup.py
1
7196
import argparse import os import sys import json import getpass from template import Coloring from cluster import Cluster from queue import Queue from lib import generate_pattern, Re_dummy from test import print_detail CONFIG_PATH = "~/.cqstat_config.json" class Invert(argparse.Action): def __init__(self, **kwargs): if "nargs" in kwargs: nargs = kwargs["nargs"] del kwargs["nargs"] else: nargs = 0 super(Invert, self).__init__(nargs=nargs, **kwargs) def __call__(self, parser, namespace, values, option_string=None): if self.default not in (True, False): parser.error("Invalid argument default value {}; Invert action requires boolean as default of argument.".format(self.default)) if values: setattr(namespace, self.dest, values) else: setattr(namespace, self.dest, not self.default) def parse_args(): settings = _load_settings() parser = argparse.ArgumentParser(description="Colorful wrapper for Grid Engine qstat command", add_help=False) parser.add_argument("-h", action='help', default="==SUPPRESS==", help='Show this help message and exit') parser.add_argument("--help", action="store_true", help='Show preview and current settings') parser.add_argument("-c", "--cluster-only", action="store_true", help="Show cluster information summary") formats = parser.add_argument_group("formats") formats.add_argument("-e", "--expand", action=Invert, default=settings["expand"], help="Full format display of information only visible jobs") formats.add_argument("-f", "--full", action=Invert, default=settings["full"], help="Full format display of information") filters = parser.add_argument_group("filters") filters.add_argument("-l", "--resource", nargs='+', help="Define the GE resources") filters.add_argument("-q", "--queue", nargs='+', help="Define the GE queues") filters.add_argument("-u", "--user", nargs='+', default=[settings["username"]], help="Display only jobs and queues being associated with the users") filters.add_argument("-a", "--all-user", action="store_true", help="Display all user jobs (same as -u *)") memory = parser.add_argument_group("memory") memory.add_argument("-r", "--required-memory", nargs='?', choices=("s_vmem", "mem_req"), action=Invert, default=settings["required-memory"], help="Add required memory amount specified by GE resource option (take time to refer job status)") memory.add_argument("-m", "--physical-memory", action=Invert, default=settings["physical-memory"], help="Add host memory usage") memory.add_argument("-s", "--swapped-memory", action=Invert, default=settings["swapped-memory"], help="Add host swap usage") parser.add_argument("-p", "--pending-jobs", action=Invert, default=settings["pending-jobs"], help="Display pending jobs") others = parser.add_argument_group("others") others.add_argument("-w", "--watch", nargs='?', const=settings["watch"], default=False, metavar="sec", help="Show status periodically (like watch command)") others.add_argument("--no-sort", action=Invert, default=settings["no-sort"], help="Disable sorting (As default, hosts are sorted by their status, usage and load average.)") others.add_argument("--bleach", action=Invert, default=settings["bleach"], help="Disable coloring") args = parser.parse_args() _setup_class(args, settings) options = '' if args.resource: options += " -l " + ','.join(args.resource) if args.queue: options += " -q " + ','.join(args.queue) setattr(args, "options", options) if args.all_user: setattr(args, "user_pattern", Re_dummy(True)) else: setattr(args, "user_pattern", generate_pattern(args.user)) if args.help: print_detail(args, settings) sys.exit(0) else: return args def _load_settings(): COLORS = dict( black=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37, b_black=90, b_red=91, b_green=92, b_yellow=93, b_blue=94, b_magenta=95, b_cyan=96, b_white=97, ) default_settings = { "expand": False, "full": False, "required-memory": False, "physical-memory": False, "swapped-memory": False, "pending-jobs": False, "no-sort": False, "bleach": False, "username": getpass.getuser(), "red": "red", "yellow": "yellow", "green": "green", "blue": "blue", "black": "b_black", "watch": 5 } config_path = os.path.expanduser(CONFIG_PATH) user_settings = {} if os.path.exists(config_path): try: with open(config_path) as conf: user_settings = json.load(conf) except (IOError, ValueError) as e: print >>sys.stderr, "WARNING: Faild to open {} ({})".format( config_path, "{}: {}".format(e.__class__.__name__, str(e)) ) else: try: with open(config_path, "w") as conf: json.dump(default_settings, conf, sort_keys=True, indent=4) except (IOError, ValueError) as e: print >>sys.stderr, "WARNING: Faild to create {} ({})".format( config_path, "{}: {}".format(e.__class__.__name__, str(e)) ) for k, v in user_settings.items(): if k == "username": if not isinstance(v, basestring): del user_settings["username"] else: continue elif k not in COLORS and v not in (True, False): del user_settings[k] settings = dict( {k: v for k, v in user_settings.items() if k in default_settings}, **{k: v for k, v in default_settings.items() if k not in user_settings} ) for color in settings: if color in COLORS and settings[color] in COLORS: settings[color] = "\033[{}m".format(COLORS[settings[color]]) return settings def _setup_class(args, settings): Coloring.enable = not args.bleach Coloring.COLOR = {k: v for k, v in settings.items() if k in ("red", "yellow", "green", "blue", "black")} Cluster.required_memory = True if args.required_memory else False Cluster.physical_memory = args.physical_memory Cluster.swapped_memory = args.swapped_memory Queue.required_memory = True if args.required_memory else False Queue.physical_memory = args.physical_memory Queue.swapped_memory = args.swapped_memory
mit
sunlightlabs/tcamp
tcamp/sms/views.py
1
4763
from twilio.twiml import Response from django_twilio.decorators import twilio_view from django.template.defaultfilters import striptags from django.views.decorators.http import require_http_methods from django.views.decorators.cache import never_cache from django.utils import timezone from dateutil.parser import parse as dateparse from sked.models import Event, Session import base62 @never_cache @twilio_view @require_http_methods(['POST', ]) def coming_up(request): sessions = Session.objects.filter(is_public=True, event=Event.objects.current()) r = Response() inmsg = request.POST.get('Body').strip() or 'next' if inmsg.lower() == 'next': messages = _as_sms(Session.objects.next()) elif inmsg.lower() == 'now': messages = _as_sms(Session.objects.current()) elif inmsg.lower() == 'lunch': try: now = timezone.now() messages = _as_sms(Session.objects.filter(start_time__day=now.day, start_time__month=now.month, start_time__year=now.year, title__icontains='lunch')[0]) except IndexError: messages = ["No lunch on the schedule for today, sorry.\n"] else: # First try to base62 decode the message try: session = _get_session_from_base62(inmsg) messages = _as_sms(session) except Session.DoesNotExist: messages = ["Couldn't find that session.\n\nText 'next' to get the upcoming block of sessions."] except ValueError: # Not b62-encoded, check to see if it's a time. try: ts = dateparse(inmsg) if ts.hour is 0 and ts.minute is 0: messages = ["A lot of stuff can happen in a whole day! Try specifying a time.\n"] else: messages = _as_sms(sessions.filter(start_time__lte=ts, end_time__gte=ts)) except: messages = ["Welcome to TCamp!\n\nOptions:\nnow: Current sessions\nnext: Next timeslot\nlunch: When's lunch?\n<time>, eg. 4:30pm: What's happening at 4:30?\n"] l = len(messages) for i, message in enumerate(messages): r.sms(message + '\n(%d/%d)' % (i+1, l)) return r def _get_session_from_base62(id): session_id = base62.decode(id) session = Session.objects.published().filter(pk=session_id) return session def _as_sms(qset): msgs = ['No events.\n'] if qset.count() > 1: return _format_multiple(qset) elif qset.count() is 1: return _format_single(qset) return msgs def _format_multiple(qset): msgs = ['No events.\n'] now = timezone.now() tm = _convert_time(qset[0].start_time) if tm.date() == now.date(): msgs[0] = u'At %s\n' % tm.strftime('%-I:%M') else: msgs[0] = u'%s at %s\n' % (tm.strftime('%A'), tm.strftime('%-I:%M')) msgs[0] += u' (text shortcode for more info):' for s in qset: line = u'\n%s: \n%s (%s)\n' % (base62.encode(s.id), s.title, s.location.name) if len(msgs[-1] + line) <= 150: msgs[-1] += line else: msgs.append(line) return msgs def _format_single(qset): sess = qset[0] tm = _convert_time(qset[0].start_time) msgs = [] detail = u'''{title} {time}, in {room} {speaker_names} {description} '''.format(title=sess.title, time=u'%s at %s' % (tm.strftime('%A'), tm.strftime('%-I:%M')), room=sess.location.name, description=striptags(sess.description).replace('&amp;', '&'), speaker_names=sess.speaker_names, ) if sess.tags.count(): detail += u"\n\nTagged: %s" % sess.tag_string lines = detail.split('\n') msgs.append(lines[0]) def build_line(tokens, **kwargs): maxlen = kwargs.get('maxlen', 146) i = kwargs.get('offset', 0) curline = [] while len(u' '.join(curline) + u' %s' % tokens[i]) <= maxlen: curline.append(tokens[i]) i += 1 if i >= len(tokens): break return (u' '.join(curline), i) for line in lines[1:]: if len(msgs[-1] + line) <= 146: msgs[-1] += "\n%s" % line else: if len(line) > 146: tokens = line.split() offset = 0 while offset < len(tokens): newline, offset = build_line(tokens, offset=offset) msgs.append(newline) else: msgs.append(line) return msgs def _convert_time(tm): return tm.astimezone(timezone.get_current_timezone())
bsd-3-clause
subutai/nupic
src/nupic/support/fs_helpers.py
10
1566
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2013, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- """ This module contains file-system helper functions. """ import os def makeDirectoryFromAbsolutePath(absDirPath): """ Makes directory for the given directory path with default permissions. If the directory already exists, it is treated as success. :param absDirPath: (string) absolute path of the directory to create. :raises: OSError if directory creation fails :returns: (string) absolute path provided """ assert os.path.isabs(absDirPath) try: os.makedirs(absDirPath) except OSError, e: if e.errno != os.errno.EEXIST: raise return absDirPath
agpl-3.0
tianweizhang/nova
nova/tests/api/openstack/test_faults.py
12
11289
# Copyright 2013 IBM Corp. # Copyright 2010 OpenStack Foundation # 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 xml.dom import minidom import mock import webob import webob.dec import webob.exc import nova.api.openstack from nova.api.openstack import common from nova.api.openstack import wsgi from nova import exception from nova import i18n from nova.i18n import _ from nova.openstack.common import jsonutils from nova import test class TestFaultWrapper(test.NoDBTestCase): """Tests covering `nova.api.openstack:FaultWrapper` class.""" @mock.patch('oslo.i18n.translate') @mock.patch('nova.i18n.get_available_languages') def test_safe_exception_translated(self, mock_languages, mock_translate): def fake_translate(value, locale): return "I've been translated!" mock_translate.side_effect = fake_translate # Create an exception, passing a translatable message with a # known value we can test for later. safe_exception = exception.NotFound(_('Should be translated.')) safe_exception.safe = True safe_exception.code = 404 req = webob.Request.blank('/') def raiser(*args, **kwargs): raise safe_exception wrapper = nova.api.openstack.FaultWrapper(raiser) response = req.get_response(wrapper) # The text of the exception's message attribute (replaced # above with a non-default value) should be passed to # translate(). mock_translate.assert_any_call(u'Should be translated.', None) # The return value from translate() should appear in the response. self.assertIn("I've been translated!", unicode(response.body)) class TestFaults(test.NoDBTestCase): """Tests covering `nova.api.openstack.faults:Fault` class.""" def _prepare_xml(self, xml_string): """Remove characters from string which hinder XML equality testing.""" xml_string = xml_string.replace(" ", "") xml_string = xml_string.replace("\n", "") xml_string = xml_string.replace("\t", "") return xml_string def test_400_fault_json(self): # Test fault serialized to JSON via file-extension and/or header. requests = [ webob.Request.blank('/.json'), webob.Request.blank('/', headers={"Accept": "application/json"}), ] for request in requests: fault = wsgi.Fault(webob.exc.HTTPBadRequest(explanation='scram')) response = request.get_response(fault) expected = { "badRequest": { "message": "scram", "code": 400, }, } actual = jsonutils.loads(response.body) self.assertEqual(response.content_type, "application/json") self.assertEqual(expected, actual) def test_413_fault_json(self): # Test fault serialized to JSON via file-extension and/or header. requests = [ webob.Request.blank('/.json'), webob.Request.blank('/', headers={"Accept": "application/json"}), ] for request in requests: exc = webob.exc.HTTPRequestEntityTooLarge # NOTE(aloga): we intentionally pass an integer for the # 'Retry-After' header. It should be then converted to a str fault = wsgi.Fault(exc(explanation='sorry', headers={'Retry-After': 4})) response = request.get_response(fault) expected = { "overLimit": { "message": "sorry", "code": 413, "retryAfter": "4", }, } actual = jsonutils.loads(response.body) self.assertEqual(response.content_type, "application/json") self.assertEqual(expected, actual) def test_429_fault_json(self): # Test fault serialized to JSON via file-extension and/or header. requests = [ webob.Request.blank('/.json'), webob.Request.blank('/', headers={"Accept": "application/json"}), ] for request in requests: exc = webob.exc.HTTPTooManyRequests # NOTE(aloga): we intentionally pass an integer for the # 'Retry-After' header. It should be then converted to a str fault = wsgi.Fault(exc(explanation='sorry', headers={'Retry-After': 4})) response = request.get_response(fault) expected = { "overLimit": { "message": "sorry", "code": 429, "retryAfter": "4", }, } actual = jsonutils.loads(response.body) self.assertEqual(response.content_type, "application/json") self.assertEqual(expected, actual) def test_raise(self): # Ensure the ability to raise :class:`Fault` in WSGI-ified methods. @webob.dec.wsgify def raiser(req): raise wsgi.Fault(webob.exc.HTTPNotFound(explanation='whut?')) req = webob.Request.blank('/.xml') resp = req.get_response(raiser) self.assertEqual(resp.content_type, "application/xml") self.assertEqual(resp.status_int, 404) self.assertIn('whut?', resp.body) def test_raise_403(self): # Ensure the ability to raise :class:`Fault` in WSGI-ified methods. @webob.dec.wsgify def raiser(req): raise wsgi.Fault(webob.exc.HTTPForbidden(explanation='whut?')) req = webob.Request.blank('/.xml') resp = req.get_response(raiser) self.assertEqual(resp.content_type, "application/xml") self.assertEqual(resp.status_int, 403) self.assertNotIn('resizeNotAllowed', resp.body) self.assertIn('forbidden', resp.body) def test_raise_localize_explanation(self): msgid = "String with params: %s" params = ('blah', ) lazy_gettext = i18n._ expl = lazy_gettext(msgid) % params @webob.dec.wsgify def raiser(req): raise wsgi.Fault(webob.exc.HTTPNotFound(explanation=expl)) req = webob.Request.blank('/.xml') resp = req.get_response(raiser) self.assertEqual(resp.content_type, "application/xml") self.assertEqual(resp.status_int, 404) self.assertIn((msgid % params), resp.body) def test_fault_has_status_int(self): # Ensure the status_int is set correctly on faults. fault = wsgi.Fault(webob.exc.HTTPBadRequest(explanation='what?')) self.assertEqual(fault.status_int, 400) def test_xml_serializer(self): # Ensure that a v1.1 request responds with a v1.1 xmlns. request = webob.Request.blank('/v1.1', headers={"Accept": "application/xml"}) fault = wsgi.Fault(webob.exc.HTTPBadRequest(explanation='scram')) response = request.get_response(fault) self.assertIn(common.XML_NS_V11, response.body) self.assertEqual(response.content_type, "application/xml") self.assertEqual(response.status_int, 400) class FaultsXMLSerializationTestV11(test.NoDBTestCase): """Tests covering `nova.api.openstack.faults:Fault` class.""" def _prepare_xml(self, xml_string): xml_string = xml_string.replace(" ", "") xml_string = xml_string.replace("\n", "") xml_string = xml_string.replace("\t", "") return xml_string def test_400_fault(self): metadata = {'attributes': {"badRequest": 'code'}} serializer = wsgi.XMLDictSerializer(metadata=metadata, xmlns=common.XML_NS_V11) fixture = { "badRequest": { "message": "scram", "code": 400, }, } output = serializer.serialize(fixture) actual = minidom.parseString(self._prepare_xml(output)) expected = minidom.parseString(self._prepare_xml(""" <badRequest code="400" xmlns="%s"> <message>scram</message> </badRequest> """) % common.XML_NS_V11) self.assertEqual(expected.toxml(), actual.toxml()) def test_413_fault(self): metadata = {'attributes': {"overLimit": 'code'}} serializer = wsgi.XMLDictSerializer(metadata=metadata, xmlns=common.XML_NS_V11) fixture = { "overLimit": { "message": "sorry", "code": 413, "retryAfter": 4, }, } output = serializer.serialize(fixture) actual = minidom.parseString(self._prepare_xml(output)) expected = minidom.parseString(self._prepare_xml(""" <overLimit code="413" xmlns="%s"> <message>sorry</message> <retryAfter>4</retryAfter> </overLimit> """) % common.XML_NS_V11) self.assertEqual(expected.toxml(), actual.toxml()) def test_429_fault(self): metadata = {'attributes': {"overLimit": 'code'}} serializer = wsgi.XMLDictSerializer(metadata=metadata, xmlns=common.XML_NS_V11) fixture = { "overLimit": { "message": "sorry", "code": 429, "retryAfter": 4, }, } output = serializer.serialize(fixture) actual = minidom.parseString(self._prepare_xml(output)) expected = minidom.parseString(self._prepare_xml(""" <overLimit code="429" xmlns="%s"> <message>sorry</message> <retryAfter>4</retryAfter> </overLimit> """) % common.XML_NS_V11) self.assertEqual(expected.toxml(), actual.toxml()) def test_404_fault(self): metadata = {'attributes': {"itemNotFound": 'code'}} serializer = wsgi.XMLDictSerializer(metadata=metadata, xmlns=common.XML_NS_V11) fixture = { "itemNotFound": { "message": "sorry", "code": 404, }, } output = serializer.serialize(fixture) actual = minidom.parseString(self._prepare_xml(output)) expected = minidom.parseString(self._prepare_xml(""" <itemNotFound code="404" xmlns="%s"> <message>sorry</message> </itemNotFound> """) % common.XML_NS_V11) self.assertEqual(expected.toxml(), actual.toxml())
apache-2.0
PerkinsRay/pox
pox/datapaths/pcap_switch.py
42
7186
# Copyright 2013 James McCauley # # 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. """ Software switch with PCap ports Example: ./pox.py --no-openflow datapaths.pcap_switch --address=localhost """ from pox.core import core from pox.datapaths import do_launch from pox.datapaths.switch import SoftwareSwitchBase, OFConnection from pox.datapaths.switch import ExpireMixin import pox.lib.pxpcap as pxpcap from Queue import Queue from threading import Thread import pox.openflow.libopenflow_01 as of from pox.lib.packet import ethernet import logging log = core.getLogger() DEFAULT_CTL_PORT = 7791 _switches = {} def _do_ctl (event): r = _do_ctl2(event) if r is None: r = "Okay." event.worker.send(r + "\n") def _do_ctl2 (event): def errf (msg, *args): raise RuntimeError(msg % args) args = event.args def ra (low, high = None): if high is None: high = low if len(args) < low or len(args) > high: raise RuntimeError("Wrong number of arguments") return False try: if event.first == "add-port": ra(1,2) if len(event.args) == 1 and len(_switches) == 1: sw = _switches[_switches.keys()[0]] p = args[0] else: ra(2) if event.args[0] not in _switches: raise RuntimeError("No such switch") sw = _switches[event.args[0]] p = args[1] sw.add_interface(p, start=True, on_error=errf) elif event.first == "del-port": ra(1,2) if len(event.args) == 1: for sw in _switches.values(): for p in sw.ports: if p.name == event.args[0]: sw.remove_interface(event.args[0]) return raise RuntimeError("No such interface") sw = _switches[event.args[0]] sw.remove_interface(args[1]) elif event.first == "show": ra(0) s = [] for sw in _switches.values(): s.append("Switch %s" % (sw.name,)) for no,p in sw.ports.iteritems(): s.append(" %3s %s" % (no, p.name)) return "\n".join(s) else: raise RuntimeError("Unknown command") except Exception as e: log.exception("While processing command") return "Error: " + str(e) def launch (address = '127.0.0.1', port = 6633, max_retry_delay = 16, dpid = None, ports = '', extra = None, ctl_port = None, __INSTANCE__ = None): """ Launches a switch """ if not pxpcap.enabled: raise RuntimeError("You need PXPCap to use this component") if ctl_port: if core.hasComponent('ctld'): raise RuntimeError("Only one ctl_port is allowed") if ctl_port is True: ctl_port = DEFAULT_CTL_PORT import ctl ctl.server(ctl_port) core.ctld.addListenerByName("CommandEvent", _do_ctl) _ports = ports.strip() def up (event): ports = [p for p in _ports.split(",") if p] sw = do_launch(PCapSwitch, address, port, max_retry_delay, dpid, ports=ports, extra_args=extra) _switches[sw.name] = sw core.addListenerByName("UpEvent", up) class PCapSwitch (ExpireMixin, SoftwareSwitchBase): # Default level for loggers of this class default_log_level = logging.INFO def __init__ (self, **kw): """ Create a switch instance Additional options over superclass: log_level (default to default_log_level) is level for this instance ports is a list of interface names """ log_level = kw.pop('log_level', self.default_log_level) self.q = Queue() self.t = Thread(target=self._consumer_threadproc) core.addListeners(self) ports = kw.pop('ports', []) kw['ports'] = [] super(PCapSwitch,self).__init__(**kw) self._next_port = 1 self.px = {} for p in ports: self.add_interface(p, start=False) self.log.setLevel(log_level) for px in self.px.itervalues(): px.start() self.t.start() def add_interface (self, name, port_no=-1, on_error=None, start=False): if on_error is None: on_error = log.error devs = pxpcap.PCap.get_devices() if name not in devs: on_error("Device %s not available -- ignoring", name) return dev = devs[name] if dev.get('addrs',{}).get('ethernet',{}).get('addr') is None: on_error("Device %s has no ethernet address -- ignoring", name) return if dev.get('addrs',{}).get('AF_INET') != None: on_error("Device %s has an IP address -- ignoring", name) return for no,p in self.px.iteritems(): if p.device == name: on_error("Device %s already added", name) if port_no == -1: while True: port_no = self._next_port self._next_port += 1 if port_no not in self.ports: break if port_no in self.ports: on_error("Port %s already exists -- ignoring", port_no) return phy = of.ofp_phy_port() phy.port_no = port_no phy.hw_addr = dev['addrs']['ethernet']['addr'] phy.name = name # Fill in features sort of arbitrarily phy.curr = of.OFPPF_10MB_HD phy.advertised = of.OFPPF_10MB_HD phy.supported = of.OFPPF_10MB_HD phy.peer = of.OFPPF_10MB_HD self.add_port(phy) px = pxpcap.PCap(name, callback = self._pcap_rx, start = False) px.port_no = phy.port_no self.px[phy.port_no] = px if start: px.start() return px def remove_interface (self, name_or_num): if isinstance(name_or_num, basestring): for no,p in self.px.iteritems(): if p.device == name_or_num: self.remove_interface(no) return raise ValueError("No such interface") px = self.px[name_or_num] px.stop() px.port_no = None self.delete_port(name_or_num) def _handle_GoingDownEvent (self, event): self.q.put(None) def _consumer_threadproc (self): timeout = 3 while core.running: try: data = self.q.get(timeout=timeout) except: continue if data is None: # Signal to quit break batch = [] while True: self.q.task_done() port_no,data = data data = ethernet(data) batch.append((data,port_no)) try: data = self.q.get(block=False) except: break core.callLater(self.rx_batch, batch) def rx_batch (self, batch): for data,port_no in batch: self.rx_packet(data, port_no) def _pcap_rx (self, px, data, sec, usec, length): if px.port_no is None: return self.q.put((px.port_no, data)) def _output_packet_physical (self, packet, port_no): """ send a packet out a single physical port This is called by the more general _output_packet(). """ px = self.px.get(port_no) if not px: return px.inject(packet)
apache-2.0
kwailamchan/programming-languages
javascript/backbone/backbone-templates/backbone-fileupload/venvs/lib/python2.7/site-packages/django/contrib/localflavor/it/util.py
436
1807
from django.utils.encoding import smart_str, smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26] def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_str(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
mit
gdgellatly/OCB1
addons/purchase/company.py
51
1586
# -*- 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 openerp.osv import osv,fields class company(osv.osv): _inherit = 'res.company' _columns = { 'po_lead': fields.float( 'Purchase Lead Time', required=True, help="Margin of error for supplier lead times. When the system"\ "generates Purchase Orders for procuring products,"\ "they will be scheduled that many days earlier "\ "to cope with unexpected supplier delays."), } _defaults = { 'po_lead': lambda *a: 1.0, } company() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0